diff --git a/cirq-google/cirq_google/cloud/quantum/__init__.py b/cirq-google/cirq_google/cloud/quantum/__init__.py index df76298594d..752ac85ab3f 100644 --- a/cirq-google/cirq_google/cloud/quantum/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -32,6 +32,7 @@ from cirq_google.cloud.quantum_v1alpha1.types.engine import DeleteQuantumReservationRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumCalibrationRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumJobRequest +from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumProcessorConfigRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumProcessorRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumProgramRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumReservationRequest @@ -61,6 +62,7 @@ from cirq_google.cloud.quantum_v1alpha1.types.engine import UpdateQuantumJobRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import UpdateQuantumProgramRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import UpdateQuantumReservationRequest +from cirq_google.cloud.quantum_v1alpha1.types.quantum import DeviceConfigKey from cirq_google.cloud.quantum_v1alpha1.types.quantum import DeviceConfigSelector from cirq_google.cloud.quantum_v1alpha1.types.quantum import ExecutionStatus from cirq_google.cloud.quantum_v1alpha1.types.quantum import GcsLocation @@ -70,6 +72,7 @@ from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumJob from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumJobEvent from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumProcessor +from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumProcessorConfig from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumProgram from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumReservation from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumReservationBudget @@ -77,7 +80,6 @@ from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumResult from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumTimeSlot from cirq_google.cloud.quantum_v1alpha1.types.quantum import SchedulingConfig -from cirq_google.cloud.quantum_v1alpha1.types.quantum import DeviceConfigKey __all__ = ( 'QuantumEngineServiceClient', @@ -93,6 +95,7 @@ 'DeleteQuantumReservationRequest', 'GetQuantumCalibrationRequest', 'GetQuantumJobRequest', + 'GetQuantumProcessorConfigRequest', 'GetQuantumProcessorRequest', 'GetQuantumProgramRequest', 'GetQuantumReservationRequest', @@ -122,6 +125,7 @@ 'UpdateQuantumJobRequest', 'UpdateQuantumProgramRequest', 'UpdateQuantumReservationRequest', + 'DeviceConfigKey', 'DeviceConfigSelector', 'ExecutionStatus', 'GcsLocation', @@ -131,6 +135,7 @@ 'QuantumJob', 'QuantumJobEvent', 'QuantumProcessor', + 'QuantumProcessorConfig', 'QuantumProgram', 'QuantumReservation', 'QuantumReservationBudget', @@ -138,5 +143,4 @@ 'QuantumResult', 'QuantumTimeSlot', 'SchedulingConfig', - 'DeviceConfigKey', ) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py index 8d2c1d80b27..42cd1d84046 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ from .types.engine import DeleteQuantumReservationRequest from .types.engine import GetQuantumCalibrationRequest from .types.engine import GetQuantumJobRequest +from .types.engine import GetQuantumProcessorConfigRequest from .types.engine import GetQuantumProcessorRequest from .types.engine import GetQuantumProgramRequest from .types.engine import GetQuantumReservationRequest @@ -57,6 +58,7 @@ from .types.engine import UpdateQuantumJobRequest from .types.engine import UpdateQuantumProgramRequest from .types.engine import UpdateQuantumReservationRequest +from .types.quantum import DeviceConfigKey from .types.quantum import DeviceConfigSelector from .types.quantum import ExecutionStatus from .types.quantum import GcsLocation @@ -66,6 +68,7 @@ from .types.quantum import QuantumJob from .types.quantum import QuantumJobEvent from .types.quantum import QuantumProcessor +from .types.quantum import QuantumProcessorConfig from .types.quantum import QuantumProgram from .types.quantum import QuantumReservation from .types.quantum import QuantumReservationBudget @@ -73,7 +76,6 @@ from .types.quantum import QuantumResult from .types.quantum import QuantumTimeSlot from .types.quantum import SchedulingConfig -from .types.quantum import DeviceConfigKey __all__ = ( 'QuantumEngineServiceAsyncClient', @@ -86,11 +88,13 @@ 'DeleteQuantumJobRequest', 'DeleteQuantumProgramRequest', 'DeleteQuantumReservationRequest', + 'DeviceConfigKey', 'DeviceConfigSelector', 'ExecutionStatus', 'GcsLocation', 'GetQuantumCalibrationRequest', 'GetQuantumJobRequest', + 'GetQuantumProcessorConfigRequest', 'GetQuantumProcessorRequest', 'GetQuantumProgramRequest', 'GetQuantumReservationRequest', @@ -120,6 +124,7 @@ 'QuantumJob', 'QuantumJobEvent', 'QuantumProcessor', + 'QuantumProcessorConfig', 'QuantumProgram', 'QuantumReservation', 'QuantumReservationBudget', @@ -134,5 +139,4 @@ 'UpdateQuantumJobRequest', 'UpdateQuantumProgramRequest', 'UpdateQuantumReservationRequest', - 'DeviceConfigKey', ) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_metadata.json b/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_metadata.json index be41be96981..fd2ec7bfb5d 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_metadata.json +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_metadata.json @@ -65,6 +65,11 @@ "get_quantum_processor" ] }, + "GetQuantumProcessorConfig": { + "methods": [ + "get_quantum_processor_config" + ] + }, "GetQuantumProgram": { "methods": [ "get_quantum_program" @@ -210,6 +215,161 @@ "get_quantum_processor" ] }, + "GetQuantumProcessorConfig": { + "methods": [ + "get_quantum_processor_config" + ] + }, + "GetQuantumProgram": { + "methods": [ + "get_quantum_program" + ] + }, + "GetQuantumReservation": { + "methods": [ + "get_quantum_reservation" + ] + }, + "GetQuantumResult": { + "methods": [ + "get_quantum_result" + ] + }, + "ListQuantumCalibrations": { + "methods": [ + "list_quantum_calibrations" + ] + }, + "ListQuantumJobEvents": { + "methods": [ + "list_quantum_job_events" + ] + }, + "ListQuantumJobs": { + "methods": [ + "list_quantum_jobs" + ] + }, + "ListQuantumProcessors": { + "methods": [ + "list_quantum_processors" + ] + }, + "ListQuantumPrograms": { + "methods": [ + "list_quantum_programs" + ] + }, + "ListQuantumReservationBudgets": { + "methods": [ + "list_quantum_reservation_budgets" + ] + }, + "ListQuantumReservationGrants": { + "methods": [ + "list_quantum_reservation_grants" + ] + }, + "ListQuantumReservations": { + "methods": [ + "list_quantum_reservations" + ] + }, + "ListQuantumTimeSlots": { + "methods": [ + "list_quantum_time_slots" + ] + }, + "QuantumRunStream": { + "methods": [ + "quantum_run_stream" + ] + }, + "ReallocateQuantumReservationGrant": { + "methods": [ + "reallocate_quantum_reservation_grant" + ] + }, + "UpdateQuantumJob": { + "methods": [ + "update_quantum_job" + ] + }, + "UpdateQuantumProgram": { + "methods": [ + "update_quantum_program" + ] + }, + "UpdateQuantumReservation": { + "methods": [ + "update_quantum_reservation" + ] + } + } + }, + "rest": { + "libraryClient": "QuantumEngineServiceClient", + "rpcs": { + "CancelQuantumJob": { + "methods": [ + "cancel_quantum_job" + ] + }, + "CancelQuantumReservation": { + "methods": [ + "cancel_quantum_reservation" + ] + }, + "CreateQuantumJob": { + "methods": [ + "create_quantum_job" + ] + }, + "CreateQuantumProgram": { + "methods": [ + "create_quantum_program" + ] + }, + "CreateQuantumReservation": { + "methods": [ + "create_quantum_reservation" + ] + }, + "DeleteQuantumJob": { + "methods": [ + "delete_quantum_job" + ] + }, + "DeleteQuantumProgram": { + "methods": [ + "delete_quantum_program" + ] + }, + "DeleteQuantumReservation": { + "methods": [ + "delete_quantum_reservation" + ] + }, + "GetQuantumCalibration": { + "methods": [ + "get_quantum_calibration" + ] + }, + "GetQuantumJob": { + "methods": [ + "get_quantum_job" + ] + }, + "GetQuantumProcessor": { + "methods": [ + "get_quantum_processor" + ] + }, + "GetQuantumProcessorConfig": { + "methods": [ + "get_quantum_processor_config" + ] + }, "GetQuantumProgram": { "methods": [ "get_quantum_program" diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/__init__.py index e8e1c3845db..cbf94b283c7 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/__init__.py index 5d1df2327fd..9d8d7fff59d 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py index e66026f47dc..555025bf607 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,32 +12,32 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# +import importlib.util +import logging as std_logging +from typing import AsyncIterable, AsyncIterator, Awaitable, Callable, Optional, Sequence -# ruff: noqa: E501 - -from __future__ import annotations +import google.protobuf +from google.api_core import gapic_v1, retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials -import importlib.metadata -from typing import AsyncIterable, AsyncIterator, Awaitable, Sequence, TYPE_CHECKING +import cirq_google -from google.api_core import gapic_v1, retry as retries +try: + OptionalRetry = retries.AsyncRetry | gapic_v1.method._MethodDefault | None +except AttributeError: # pragma: NO COVER + OptionalRetry = retries.AsyncRetry, object, None # type: ignore from cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service import pagers from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum from .client import QuantumEngineServiceClient -from .transports.base import DEFAULT_CLIENT_INFO +from .transports.base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport -if TYPE_CHECKING: - from google.api_core.client_options import ClientOptions - from google.auth import credentials as ga_credentials +CLIENT_LOGGING_SUPPORTED = importlib.util.find_spec("google.api_core.client_logging") is not None - from .transports.base import QuantumEngineServiceTransport - -try: - OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault -except AttributeError: # pragma: NO COVER - OptionalRetry = retries.Retry | object # type: ignore +_LOGGER = std_logging.getLogger(__name__) class QuantumEngineServiceAsyncClient: @@ -45,8 +45,12 @@ class QuantumEngineServiceAsyncClient: _client: QuantumEngineServiceClient + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = QuantumEngineServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = QuantumEngineServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = QuantumEngineServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = QuantumEngineServiceClient._DEFAULT_UNIVERSE quantum_job_path = staticmethod(QuantumEngineServiceClient.quantum_job_path) parse_quantum_job_path = staticmethod(QuantumEngineServiceClient.parse_quantum_job_path) @@ -54,6 +58,12 @@ class QuantumEngineServiceAsyncClient: parse_quantum_processor_path = staticmethod( QuantumEngineServiceClient.parse_quantum_processor_path ) + quantum_processor_config_path = staticmethod( + QuantumEngineServiceClient.quantum_processor_config_path + ) + parse_quantum_processor_config_path = staticmethod( + QuantumEngineServiceClient.parse_quantum_processor_config_path + ) quantum_program_path = staticmethod(QuantumEngineServiceClient.quantum_program_path) parse_quantum_program_path = staticmethod(QuantumEngineServiceClient.parse_quantum_program_path) quantum_reservation_path = staticmethod(QuantumEngineServiceClient.quantum_reservation_path) @@ -90,7 +100,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: QuantumEngineServiceAsyncClient: The constructed client. """ - return QuantumEngineServiceClient.from_service_account_info.__func__(QuantumEngineServiceAsyncClient, info, *args, **kwargs) # type: ignore + return QuantumEngineServiceClient.from_service_account_info.__func__( # type: ignore + QuantumEngineServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -106,12 +118,14 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: QuantumEngineServiceAsyncClient: The constructed client. """ - return QuantumEngineServiceClient.from_service_account_file.__func__(QuantumEngineServiceAsyncClient, filename, *args, **kwargs) # type: ignore + return QuantumEngineServiceClient.from_service_account_file.__func__( # type: ignore + QuantumEngineServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: ClientOptions | None = None): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -136,7 +150,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: ClientOptions | None in this method. Returns: - tuple[str, Callable[[], tuple[bytes, bytes]]]: returns the API endpoint and the + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the client cert source to use. Raises: @@ -153,17 +167,38 @@ def transport(self) -> QuantumEngineServiceTransport: """ return self._client.transport + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + get_transport_class = QuantumEngineServiceClient.get_transport_class def __init__( self, *, - credentials: ga_credentials.Credentials | None = None, - transport: str | QuantumEngineServiceTransport = "grpc_asyncio", - client_options: ClientOptions | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + str | QuantumEngineServiceTransport | Callable[..., QuantumEngineServiceTransport] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiates the quantum engine service client. + """Instantiates the quantum engine service async client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -171,26 +206,49 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (str | ~.QuantumEngineServiceTransport): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: + transport ( + Optional[ + str | + QuantumEngineServiceTransport | + Callable[..., QuantumEngineServiceTransport] + ] + ): + The transport to use, or a Callable that constructs and returns a new transport to + use. If a Callable is given, it will be called with the same set of initialization + arguments as used in the QuantumEngineServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[google.api_core.client_options.ClientOptions | dict]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If + to provide a client certificate for mTLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. @@ -202,57 +260,96 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + ( + "Created client `cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceAsyncClient`." + ), + extra=( + { + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", # noqa E501 + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "credentialsType": None, + } + ), + ) + async def create_quantum_program( self, - request: engine.CreateQuantumProgramRequest | dict | None = None, + request: Optional[engine.CreateQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_create_quantum_program(): + async def sample_create_quantum_program(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CreateQuantumProgramRequest( ) # Make the request - response = client.create_quantum_program(request=request) + response = await client.create_quantum_program(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumProgramRequest | dict): + request ( + Optional[ + cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumProgramRequest | dict + ] + ): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - """ # Create or coerce a protobuf request object. - request = engine.CreateQuantumProgramRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CreateQuantumProgramRequest): + request = engine.CreateQuantumProgramRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_quantum_program, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_quantum_program + ] # Certain fields should be provided within the metadata header; # add these here. @@ -260,6 +357,9 @@ def sample_create_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -268,55 +368,63 @@ def sample_create_quantum_program(): async def get_quantum_program( self, - request: engine.GetQuantumProgramRequest | dict | None = None, + request: Optional[engine.GetQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_program(): + async def sample_get_quantum_program(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumProgramRequest( ) # Make the request - response = client.get_quantum_program(request=request) + response = await client.get_quantum_program(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumProgramRequest | dict): + request (Optional[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProgramRequest | dict]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumProgramRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumProgramRequest): + request = engine.GetQuantumProgramRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_program, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.get_quantum_program] # Certain fields should be provided within the metadata header; # add these here. @@ -324,6 +432,9 @@ def sample_get_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -332,21 +443,28 @@ def sample_get_quantum_program(): async def list_quantum_programs( self, - request: engine.ListQuantumProgramsRequest | dict | None = None, + request: Optional[engine.ListQuantumProgramsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumProgramsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_programs(): + async def sample_list_quantum_programs(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumProgramsRequest( @@ -356,36 +474,40 @@ def sample_list_quantum_programs(): page_result = client.list_quantum_programs(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProgramsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProgramsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumProgramsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumProgramsRequest): + request = engine.ListQuantumProgramsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_programs, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_programs + ] # Certain fields should be provided within the metadata header; # add these here. @@ -393,13 +515,21 @@ def sample_list_quantum_programs(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumProgramsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -407,48 +537,58 @@ def sample_list_quantum_programs(): async def delete_quantum_program( self, - request: engine.DeleteQuantumProgramRequest | dict | None = None, + request: Optional[engine.DeleteQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_delete_quantum_program(): + async def sample_delete_quantum_program(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.DeleteQuantumProgramRequest( ) # Make the request - client.delete_quantum_program(request=request) + await client.delete_quantum_program(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumProgramRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumProgramRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.DeleteQuantumProgramRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.DeleteQuantumProgramRequest): + request = engine.DeleteQuantumProgramRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_quantum_program, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_quantum_program + ] # Certain fields should be provided within the metadata header; # add these here. @@ -456,60 +596,73 @@ def sample_delete_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. await rpc(request, retry=retry, timeout=timeout, metadata=metadata) async def update_quantum_program( self, - request: engine.UpdateQuantumProgramRequest | dict | None = None, + request: Optional[engine.UpdateQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_update_quantum_program(): + async def sample_update_quantum_program(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.UpdateQuantumProgramRequest( ) # Make the request - response = client.update_quantum_program(request=request) + response = await client.update_quantum_program(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumProgramRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumProgramRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.UpdateQuantumProgramRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.UpdateQuantumProgramRequest): + request = engine.UpdateQuantumProgramRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_quantum_program, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_quantum_program + ] # Certain fields should be provided within the metadata header; # add these here. @@ -517,6 +670,9 @@ def sample_update_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -525,55 +681,63 @@ def sample_update_quantum_program(): async def create_quantum_job( self, - request: engine.CreateQuantumJobRequest | dict | None = None, + request: Optional[engine.CreateQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_create_quantum_job(): + async def sample_create_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CreateQuantumJobRequest( ) # Make the request - response = client.create_quantum_job(request=request) + response = await client.create_quantum_job(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.CreateQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CreateQuantumJobRequest): + request = engine.CreateQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_quantum_job, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.create_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -581,6 +745,9 @@ def sample_create_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -589,55 +756,63 @@ def sample_create_quantum_job(): async def get_quantum_job( self, - request: engine.GetQuantumJobRequest | dict | None = None, + request: Optional[engine.GetQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_job(): + async def sample_get_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumJobRequest( ) # Make the request - response = client.get_quantum_job(request=request) + response = await client.get_quantum_job(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumJobRequest): + request = engine.GetQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_job, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.get_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -645,6 +820,9 @@ def sample_get_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -653,21 +831,28 @@ def sample_get_quantum_job(): async def list_quantum_jobs( self, - request: engine.ListQuantumJobsRequest | dict | None = None, + request: Optional[engine.ListQuantumJobsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumJobsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_jobs(): + async def sample_list_quantum_jobs(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumJobsRequest( @@ -677,36 +862,38 @@ def sample_list_quantum_jobs(): page_result = client.list_quantum_jobs(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumJobsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumJobsRequest): + request = engine.ListQuantumJobsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_jobs, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.list_quantum_jobs] # Certain fields should be provided within the metadata header; # add these here. @@ -714,13 +901,21 @@ def sample_list_quantum_jobs(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumJobsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -728,48 +923,56 @@ def sample_list_quantum_jobs(): async def delete_quantum_job( self, - request: engine.DeleteQuantumJobRequest | dict | None = None, + request: Optional[engine.DeleteQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_delete_quantum_job(): + async def sample_delete_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.DeleteQuantumJobRequest( ) # Make the request - client.delete_quantum_job(request=request) + await client.delete_quantum_job(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.DeleteQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.DeleteQuantumJobRequest): + request = engine.DeleteQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_quantum_job, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -777,60 +980,71 @@ def sample_delete_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. await rpc(request, retry=retry, timeout=timeout, metadata=metadata) async def update_quantum_job( self, - request: engine.UpdateQuantumJobRequest | dict | None = None, + request: Optional[engine.UpdateQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_update_quantum_job(): + async def sample_update_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.UpdateQuantumJobRequest( ) # Make the request - response = client.update_quantum_job(request=request) + response = await client.update_quantum_job(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.UpdateQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.UpdateQuantumJobRequest): + request = engine.UpdateQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_quantum_job, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.update_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -838,6 +1052,9 @@ def sample_update_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -846,48 +1063,56 @@ def sample_update_quantum_job(): async def cancel_quantum_job( self, - request: engine.CancelQuantumJobRequest | dict | None = None, + request: Optional[engine.CancelQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_cancel_quantum_job(): + async def sample_cancel_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CancelQuantumJobRequest( ) # Make the request - client.cancel_quantum_job(request=request) + await client.cancel_quantum_job(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.CancelQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.CancelQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.CancelQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CancelQuantumJobRequest): + request = engine.CancelQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_quantum_job, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.cancel_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -895,26 +1120,36 @@ def sample_cancel_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. await rpc(request, retry=retry, timeout=timeout, metadata=metadata) async def list_quantum_job_events( self, - request: engine.ListQuantumJobEventsRequest | dict | None = None, + request: Optional[engine.ListQuantumJobEventsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumJobEventsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_job_events(): + async def sample_list_quantum_job_events(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumJobEventsRequest( @@ -924,36 +1159,40 @@ def sample_list_quantum_job_events(): page_result = client.list_quantum_job_events(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobEventsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobEventsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumJobEventsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumJobEventsRequest): + request = engine.ListQuantumJobEventsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_job_events, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_job_events + ] # Certain fields should be provided within the metadata header; # add these here. @@ -961,13 +1200,21 @@ def sample_list_quantum_job_events(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumJobEventsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -975,55 +1222,63 @@ def sample_list_quantum_job_events(): async def get_quantum_result( self, - request: engine.GetQuantumResultRequest | dict | None = None, + request: Optional[engine.GetQuantumResultRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumResult: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_result(): + async def sample_get_quantum_result(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumResultRequest( ) # Make the request - response = client.get_quantum_result(request=request) + response = await client.get_quantum_result(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumResult: + cirq_google.cloud.quantum_v1alpha1.types.QuantumResult: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumResultRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumResultRequest): + request = engine.GetQuantumResultRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_result, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.get_quantum_result] # Certain fields should be provided within the metadata header; # add these here. @@ -1031,6 +1286,9 @@ def sample_get_quantum_result(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1039,21 +1297,28 @@ def sample_get_quantum_result(): async def list_quantum_processors( self, - request: engine.ListQuantumProcessorsRequest | dict | None = None, + request: Optional[engine.ListQuantumProcessorsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumProcessorsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_processors(): + async def sample_list_quantum_processors(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumProcessorsRequest( @@ -1063,36 +1328,40 @@ def sample_list_quantum_processors(): page_result = client.list_quantum_processors(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProcessorsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProcessorsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumProcessorsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumProcessorsRequest): + request = engine.ListQuantumProcessorsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_processors, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_processors + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1100,13 +1369,21 @@ def sample_list_quantum_processors(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumProcessorsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1114,62 +1391,174 @@ def sample_list_quantum_processors(): async def get_quantum_processor( self, - request: engine.GetQuantumProcessorRequest | dict | None = None, + request: Optional[engine.GetQuantumProcessorRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProcessor: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_processor(): + async def sample_get_quantum_processor(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumProcessorRequest( ) # Make the request - response = client.get_quantum_processor(request=request) + response = await client.get_quantum_processor(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumProcessorRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProcessorRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProcessor: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumProcessorRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumProcessorRequest): + request = engine.GetQuantumProcessorRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_processor, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_quantum_processor + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) + + # Done; return the response. + return response + + async def get_quantum_processor_config( + self, + request: Optional[engine.GetQuantumProcessorConfigRequest | dict] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProcessorConfig: + r"""- + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import quantum_v1alpha1 + + async def sample_get_quantum_processor_config(): + # Create a client + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() + + # Initialize request argument(s) + request = quantum_v1alpha1.GetQuantumProcessorConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_quantum_processor_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProcessorConfigRequest, dict]]): + The request object. - + name (:class:`str`): + Required. - + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessorConfig: + - + """ # noqa E501 + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumProcessorConfigRequest): + request = engine.GetQuantumProcessorConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_quantum_processor_config + ] + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1178,21 +1567,28 @@ def sample_get_quantum_processor(): async def list_quantum_calibrations( self, - request: engine.ListQuantumCalibrationsRequest | dict | None = None, + request: Optional[engine.ListQuantumCalibrationsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumCalibrationsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_calibrations(): + async def sample_list_quantum_calibrations(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumCalibrationsRequest( @@ -1202,36 +1598,40 @@ def sample_list_quantum_calibrations(): page_result = client.list_quantum_calibrations(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumCalibrationsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumCalibrationsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumCalibrationsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumCalibrationsRequest): + request = engine.ListQuantumCalibrationsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_calibrations, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_calibrations + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1239,13 +1639,21 @@ def sample_list_quantum_calibrations(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumCalibrationsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1253,55 +1661,65 @@ def sample_list_quantum_calibrations(): async def get_quantum_calibration( self, - request: engine.GetQuantumCalibrationRequest | dict | None = None, + request: Optional[engine.GetQuantumCalibrationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumCalibration: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_calibration(): + async def sample_get_quantum_calibration(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumCalibrationRequest( ) # Make the request - response = client.get_quantum_calibration(request=request) + response = await client.get_quantum_calibration(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumCalibrationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumCalibrationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumCalibration: + cirq_google.cloud.quantum_v1alpha1.types.QuantumCalibration: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumCalibrationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumCalibrationRequest): + request = engine.GetQuantumCalibrationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_calibration, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_quantum_calibration + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1309,6 +1727,9 @@ def sample_get_quantum_calibration(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1317,55 +1738,65 @@ def sample_get_quantum_calibration(): async def create_quantum_reservation( self, - request: engine.CreateQuantumReservationRequest | dict | None = None, + request: Optional[engine.CreateQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_create_quantum_reservation(): + async def sample_create_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CreateQuantumReservationRequest( ) # Make the request - response = client.create_quantum_reservation(request=request) + response = await client.create_quantum_reservation(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.CreateQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CreateQuantumReservationRequest): + request = engine.CreateQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1373,6 +1804,9 @@ def sample_create_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1381,55 +1815,65 @@ def sample_create_quantum_reservation(): async def cancel_quantum_reservation( self, - request: engine.CancelQuantumReservationRequest | dict | None = None, + request: Optional[engine.CancelQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_cancel_quantum_reservation(): + async def sample_cancel_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CancelQuantumReservationRequest( ) # Make the request - response = client.cancel_quantum_reservation(request=request) + response = await client.cancel_quantum_reservation(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CancelQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.CancelQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.CancelQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CancelQuantumReservationRequest): + request = engine.CancelQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.cancel_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1437,6 +1881,9 @@ def sample_cancel_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1445,48 +1892,58 @@ def sample_cancel_quantum_reservation(): async def delete_quantum_reservation( self, - request: engine.DeleteQuantumReservationRequest | dict | None = None, + request: Optional[engine.DeleteQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_delete_quantum_reservation(): + async def sample_delete_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.DeleteQuantumReservationRequest( ) # Make the request - client.delete_quantum_reservation(request=request) + await client.delete_quantum_reservation(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.DeleteQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.DeleteQuantumReservationRequest): + request = engine.DeleteQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1494,60 +1951,73 @@ def sample_delete_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. await rpc(request, retry=retry, timeout=timeout, metadata=metadata) async def get_quantum_reservation( self, - request: engine.GetQuantumReservationRequest | dict | None = None, + request: Optional[engine.GetQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_reservation(): + async def sample_get_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumReservationRequest( ) # Make the request - response = client.get_quantum_reservation(request=request) + response = await client.get_quantum_reservation(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumReservationRequest): + request = engine.GetQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1555,6 +2025,9 @@ def sample_get_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1563,21 +2036,28 @@ def sample_get_quantum_reservation(): async def list_quantum_reservations( self, - request: engine.ListQuantumReservationsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_reservations(): + async def sample_list_quantum_reservations(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumReservationsRequest( @@ -1587,36 +2067,40 @@ def sample_list_quantum_reservations(): page_result = client.list_quantum_reservations(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumReservationsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumReservationsRequest): + request = engine.ListQuantumReservationsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_reservations, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_reservations + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1624,13 +2108,21 @@ def sample_list_quantum_reservations(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumReservationsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1638,55 +2130,65 @@ def sample_list_quantum_reservations(): async def update_quantum_reservation( self, - request: engine.UpdateQuantumReservationRequest | dict | None = None, + request: Optional[engine.UpdateQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_update_quantum_reservation(): + async def sample_update_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.UpdateQuantumReservationRequest( ) # Make the request - response = client.update_quantum_reservation(request=request) + response = await client.update_quantum_reservation(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.UpdateQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.UpdateQuantumReservationRequest): + request = engine.UpdateQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1694,6 +2196,9 @@ def sample_update_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1702,21 +2207,28 @@ def sample_update_quantum_reservation(): def quantum_run_stream( self, - requests: AsyncIterator[engine.QuantumRunStreamRequest] | None = None, + requests: Optional[AsyncIterator[engine.QuantumRunStreamRequest]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> Awaitable[AsyncIterable[engine.QuantumRunStreamResponse]]: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_quantum_run_stream(): + async def sample_quantum_run_stream(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.QuantumRunStreamRequest( @@ -1733,33 +2245,34 @@ def request_generator(): yield request # Make the request - stream = client.quantum_run_stream(requests=request_generator()) + stream = await client.quantum_run_stream(requests=request_generator()) # Handle the response - for response in stream: + async for response in stream: print(response) Args: - requests (AsyncIterator[`google.cloud.quantum_v1alpha1.types.QuantumRunStreamRequest`]): + requests (AsyncIterator[`cirq_google.cloud.quantum_v1alpha1.types.QuantumRunStreamRequest`]): The request object AsyncIterator. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - AsyncIterable[google.cloud.quantum_v1alpha1.types.QuantumRunStreamResponse]: + AsyncIterable[cirq_google.cloud.quantum_v1alpha1.types.QuantumRunStreamResponse]: - - """ + """ # noqa E501 # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.quantum_run_stream, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.quantum_run_stream] + + # Validate the universe domain. + self._client._validate_universe_domain() # Send the request. response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata) @@ -1769,21 +2282,28 @@ def request_generator(): async def list_quantum_reservation_grants( self, - request: engine.ListQuantumReservationGrantsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationGrantsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationGrantsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_reservation_grants(): + async def sample_list_quantum_reservation_grants(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumReservationGrantsRequest( @@ -1793,36 +2313,40 @@ def sample_list_quantum_reservation_grants(): page_result = client.list_quantum_reservation_grants(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationGrantsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationGrantsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumReservationGrantsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumReservationGrantsRequest): + request = engine.ListQuantumReservationGrantsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_reservation_grants, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_reservation_grants + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1830,13 +2354,21 @@ def sample_list_quantum_reservation_grants(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumReservationGrantsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1844,55 +2376,65 @@ def sample_list_quantum_reservation_grants(): async def reallocate_quantum_reservation_grant( self, - request: engine.ReallocateQuantumReservationGrantRequest | dict | None = None, + request: Optional[engine.ReallocateQuantumReservationGrantRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservationGrant: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_reallocate_quantum_reservation_grant(): + async def sample_reallocate_quantum_reservation_grant(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ReallocateQuantumReservationGrantRequest( ) # Make the request - response = client.reallocate_quantum_reservation_grant(request=request) + response = await client.reallocate_quantum_reservation_grant(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ReallocateQuantumReservationGrantRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ReallocateQuantumReservationGrantRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservationGrant: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationGrant: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ReallocateQuantumReservationGrantRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ReallocateQuantumReservationGrantRequest): + request = engine.ReallocateQuantumReservationGrantRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.reallocate_quantum_reservation_grant, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.reallocate_quantum_reservation_grant + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1900,6 +2442,9 @@ def sample_reallocate_quantum_reservation_grant(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1908,21 +2453,28 @@ def sample_reallocate_quantum_reservation_grant(): async def list_quantum_reservation_budgets( self, - request: engine.ListQuantumReservationBudgetsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationBudgetsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationBudgetsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_reservation_budgets(): + async def sample_list_quantum_reservation_budgets(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumReservationBudgetsRequest( @@ -1932,36 +2484,40 @@ def sample_list_quantum_reservation_budgets(): page_result = client.list_quantum_reservation_budgets(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationBudgetsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationBudgetsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumReservationBudgetsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumReservationBudgetsRequest): + request = engine.ListQuantumReservationBudgetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_reservation_budgets, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_reservation_budgets + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1969,13 +2525,21 @@ def sample_list_quantum_reservation_budgets(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumReservationBudgetsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1983,21 +2547,28 @@ def sample_list_quantum_reservation_budgets(): async def list_quantum_time_slots( self, - request: engine.ListQuantumTimeSlotsRequest | dict | None = None, + request: Optional[engine.ListQuantumTimeSlotsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumTimeSlotsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_time_slots(): + async def sample_list_quantum_time_slots(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumTimeSlotsRequest( @@ -2007,36 +2578,40 @@ def sample_list_quantum_time_slots(): page_result = client.list_quantum_time_slots(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumTimeSlotsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumTimeSlotsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumTimeSlotsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumTimeSlotsRequest): + request = engine.ListQuantumTimeSlotsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_time_slots, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_time_slots + ] # Certain fields should be provided within the metadata header; # add these here. @@ -2044,31 +2619,37 @@ def sample_list_quantum_time_slots(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumTimeSlotsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. return response - async def __aenter__(self): + async def __aenter__(self) -> "QuantumEngineServiceAsyncClient": return self async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=importlib.metadata.version("google-cloud-quantum") - ) -except ModuleNotFoundError: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(cirq_google.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ __all__ = ("QuantumEngineServiceAsyncClient",) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/client.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/client.py index 9ad05f6eaf9..9622d484058 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/client.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,36 +12,50 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -# ruff: noqa: E501 - -from __future__ import annotations - -import importlib.metadata +# +import json +import logging as std_logging import os import re +import warnings from collections import OrderedDict -from typing import Iterable, Iterator, Sequence, TYPE_CHECKING - -from google.api_core import client_options as client_options_lib, gapic_v1, retry as retries +from http import HTTPStatus +from typing import Callable, cast, Iterable, Iterator, Optional, Sequence + +import google.protobuf +from google.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + retry as retries, +) +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.auth.transport import mtls from google.oauth2 import service_account +import cirq_google from cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service import pagers from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum from .transports.base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport from .transports.grpc import QuantumEngineServiceGrpcTransport from .transports.grpc_asyncio import QuantumEngineServiceGrpcAsyncIOTransport - -if TYPE_CHECKING: - from google.auth import credentials as ga_credentials +from .transports.rest import QuantumEngineServiceRestTransport try: - OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault + OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault | None except AttributeError: # pragma: NO COVER - OptionalRetry = retries.Retry | object # type: ignore + OptionalRetry = retries.Retry | object | None # type: ignore + +try: + from google.api_core import client_logging + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) class QuantumEngineServiceClientMeta(type): @@ -52,11 +66,14 @@ class QuantumEngineServiceClientMeta(type): objects. """ - _transport_registry = OrderedDict() # type: dict[str, type[QuantumEngineServiceTransport]] + _transport_registry: dict[str, type[QuantumEngineServiceTransport]] = OrderedDict() _transport_registry["grpc"] = QuantumEngineServiceGrpcTransport _transport_registry["grpc_asyncio"] = QuantumEngineServiceGrpcAsyncIOTransport + _transport_registry["rest"] = QuantumEngineServiceRestTransport - def get_transport_class(cls, label: str | None = None) -> type[QuantumEngineServiceTransport]: + def get_transport_class( + cls, label: Optional[str] = None + ) -> type[QuantumEngineServiceTransport]: """Returns an appropriate transport class. Args: @@ -97,7 +114,7 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) - _, mtls, sandbox, googledomain = m.groups() + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -106,9 +123,13 @@ def _get_default_mtls_endpoint(api_endpoint): return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = "quantum.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__(DEFAULT_ENDPOINT) # type: ignore + _DEFAULT_ENDPOINT_TEMPLATE = "quantum.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -159,7 +180,9 @@ def transport(self) -> QuantumEngineServiceTransport: @staticmethod def quantum_job_path(project: str, program: str, job: str) -> str: """Returns a fully-qualified quantum_job string.""" - return f"projects/{project}/programs/{program}/jobs/{job}" + return "projects/{project}/programs/{program}/jobs/{job}".format( + project=project, program=program, job=job + ) @staticmethod def parse_quantum_job_path(path: str) -> dict[str, str]: @@ -172,7 +195,9 @@ def parse_quantum_job_path(path: str) -> dict[str, str]: @staticmethod def quantum_processor_path(project_id: str, processor_id: str) -> str: """Returns a fully-qualified quantum_processor string.""" - return f"projects/{project_id}/processors/{processor_id}" + return "projects/{project_id}/processors/{processor_id}".format( + project_id=project_id, processor_id=processor_id + ) @staticmethod def parse_quantum_processor_path(path: str) -> dict[str, str]: @@ -180,10 +205,31 @@ def parse_quantum_processor_path(path: str) -> dict[str, str]: m = re.match(r"^projects/(?P.+?)/processors/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def quantum_processor_config_path( + project: str, processor: str, snapshot_id: str, quantum_processor_config: str + ) -> str: + """Returns a fully-qualified quantum_processor_config string.""" + return "projects/{project}/processors/{processor}/configSnapshots/{snapshot_id}/configs/{quantum_processor_config}".format( # noqa E501 + project=project, + processor=processor, + snapshot_id=snapshot_id, + quantum_processor_config=quantum_processor_config, + ) + + @staticmethod + def parse_quantum_processor_config_path(path: str) -> dict[str, str]: + """Parses a quantum_processor_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/processors/(?P.+?)/configSnapshots/(?P.+?)/configs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def quantum_program_path(project: str, program: str) -> str: """Returns a fully-qualified quantum_program string.""" - return f"projects/{project}/programs/{program}" + return "projects/{project}/programs/{program}".format(project=project, program=program) @staticmethod def parse_quantum_program_path(path: str) -> dict[str, str]: @@ -194,7 +240,11 @@ def parse_quantum_program_path(path: str) -> dict[str, str]: @staticmethod def quantum_reservation_path(project_id: str, processor_id: str, reservation_id: str) -> str: """Returns a fully-qualified quantum_reservation string.""" - return f"projects/{project_id}/processors/{processor_id}/reservations/{reservation_id}" + return ( + "projects/{project_id}/processors/{processor_id}/reservations/{reservation_id}".format( + project_id=project_id, processor_id=processor_id, reservation_id=reservation_id + ) + ) @staticmethod def parse_quantum_reservation_path(path: str) -> dict[str, str]: @@ -208,7 +258,7 @@ def parse_quantum_reservation_path(path: str) -> dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str) -> str: """Returns a fully-qualified billing_account string.""" - return f"billingAccounts/{billing_account}" + return "billingAccounts/{billing_account}".format(billing_account=billing_account) @staticmethod def parse_common_billing_account_path(path: str) -> dict[str, str]: @@ -219,7 +269,7 @@ def parse_common_billing_account_path(path: str) -> dict[str, str]: @staticmethod def common_folder_path(folder: str) -> str: """Returns a fully-qualified folder string.""" - return f"folders/{folder}" + return "folders/{folder}".format(folder=folder) @staticmethod def parse_common_folder_path(path: str) -> dict[str, str]: @@ -230,7 +280,7 @@ def parse_common_folder_path(path: str) -> dict[str, str]: @staticmethod def common_organization_path(organization: str) -> str: """Returns a fully-qualified organization string.""" - return f"organizations/{organization}" + return "organizations/{organization}".format(organization=organization) @staticmethod def parse_common_organization_path(path: str) -> dict[str, str]: @@ -241,7 +291,7 @@ def parse_common_organization_path(path: str) -> dict[str, str]: @staticmethod def common_project_path(project: str) -> str: """Returns a fully-qualified project string.""" - return f"projects/{project}" + return "projects/{project}".format(project=project) @staticmethod def parse_common_project_path(path: str) -> dict[str, str]: @@ -252,7 +302,7 @@ def parse_common_project_path(path: str) -> dict[str, str]: @staticmethod def common_location_path(project: str, location: str) -> str: """Returns a fully-qualified location string.""" - return f"projects/{project}/locations/{location}" + return "projects/{project}/locations/{location}".format(project=project, location=location) @staticmethod def parse_common_location_path(path: str) -> dict[str, str]: @@ -262,9 +312,9 @@ def parse_common_location_path(path: str) -> dict[str, str]: @classmethod def get_mtls_endpoint_and_cert_source( - cls, client_options: client_options_lib.ClientOptions | None = None + cls, client_options: Optional[client_options_lib.ClientOptions] = None ): - """Return the API endpoint and client cert source for mutual TLS. + """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the @@ -288,23 +338,33 @@ def get_mtls_endpoint_and_cert_source( in this method. Returns: - tuple[str, Callable[[], tuple[bytes, bytes]]]: returns the API endpoint and the + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the client cert source to use. Raises: google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ + + warnings.warn( + ( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property " + "instead." + ), + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_client_cert not in ("true", "false"): raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` " + "or `false`" ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or " + "`always`" ) # Figure out the client cert source to use. @@ -325,12 +385,171 @@ def get_mtls_endpoint_and_cert_source( return api_endpoint, client_cert_source + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or " + "`false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or " + "`always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other + parameters. Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = QuantumEngineServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = QuantumEngineServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = QuantumEngineServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client + options. + universe_domain_env (Optional[str]): The universe domain configured via the + "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = QuantumEngineServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors(self, error: core_exceptions.GoogleAPICallError) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + def __init__( self, *, - credentials: ga_credentials.Credentials | None = None, - transport: str | QuantumEngineServiceTransport | None = None, - client_options: client_options_lib.ClientOptions | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + str | QuantumEngineServiceTransport | Callable[..., QuantumEngineServiceTransport] + ] = None, + client_options: Optional[client_options_lib.ClientOptions | dict] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the quantum engine service client. @@ -341,25 +560,37 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (str | QuantumEngineServiceTransport): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: + transport (Optional[Union[str,QuantumEngineServiceTransport,Callable[..., QuantumEngineServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the QuantumEngineServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If + to provide a client certificate for mTLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. @@ -369,64 +600,133 @@ def __init__( Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( - client_options + """ # noqa E501 + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + QuantumEngineServiceClient._read_environment_variables() + ) + self._client_cert_source = QuantumEngineServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = QuantumEngineServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env ) + self._api_endpoint = None # updated below, depending on `transport` - api_key_value = getattr(client_options, "api_key", None) + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. - if isinstance(transport, QuantumEngineServiceTransport): + transport_provided = isinstance(transport, QuantumEngineServiceTransport) + if transport_provided: # transport is a QuantumEngineServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: + if credentials or self._client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, provide its credentials directly." ) - if client_options.scopes: + if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes directly." ) - self._transport = transport - else: + self._transport = cast(QuantumEngineServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or QuantumEngineServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: import google.auth._default if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): credentials = google.auth._default.get_api_key_credentials(api_key_value) - Transport = type(self).get_transport_class(transport) - self._transport = Transport( + transport_init: ( + type[QuantumEngineServiceTransport] | Callable[..., QuantumEngineServiceTransport] + ) = ( + QuantumEngineServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., QuantumEngineServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=self._client_options.api_audience, ) + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + ( + "Created client `cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient`." + ), + extra=( + { + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", # noqa E501 + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "credentialsType": None, + } + ), + ) + def create_quantum_program( self, - request: engine.CreateQuantumProgramRequest | dict | None = None, + request: Optional[engine.CreateQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_create_quantum_program(): @@ -444,23 +744,23 @@ def sample_create_quantum_program(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumProgramRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumProgramRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CreateQuantumProgramRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CreateQuantumProgramRequest): request = engine.CreateQuantumProgramRequest(request) @@ -474,6 +774,9 @@ def sample_create_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -482,16 +785,23 @@ def sample_create_quantum_program(): def get_quantum_program( self, - request: engine.GetQuantumProgramRequest | dict | None = None, + request: Optional[engine.GetQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_program(): @@ -509,23 +819,23 @@ def sample_get_quantum_program(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumProgramRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProgramRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumProgramRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumProgramRequest): request = engine.GetQuantumProgramRequest(request) @@ -539,6 +849,9 @@ def sample_get_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -547,16 +860,23 @@ def sample_get_quantum_program(): def list_quantum_programs( self, - request: engine.ListQuantumProgramsRequest | dict | None = None, + request: Optional[engine.ListQuantumProgramsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumProgramsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_programs(): @@ -575,27 +895,28 @@ def sample_list_quantum_programs(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProgramsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProgramsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumProgramsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumProgramsRequest): request = engine.ListQuantumProgramsRequest(request) @@ -609,13 +930,21 @@ def sample_list_quantum_programs(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumProgramsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -623,16 +952,23 @@ def sample_list_quantum_programs(): def delete_quantum_program( self, - request: engine.DeleteQuantumProgramRequest | dict | None = None, + request: Optional[engine.DeleteQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_delete_quantum_program(): @@ -647,19 +983,19 @@ def sample_delete_quantum_program(): client.delete_quantum_program(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumProgramRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumProgramRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.DeleteQuantumProgramRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.DeleteQuantumProgramRequest): request = engine.DeleteQuantumProgramRequest(request) @@ -673,21 +1009,31 @@ def sample_delete_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. rpc(request, retry=retry, timeout=timeout, metadata=metadata) def update_quantum_program( self, - request: engine.UpdateQuantumProgramRequest | dict | None = None, + request: Optional[engine.UpdateQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_update_quantum_program(): @@ -705,23 +1051,23 @@ def sample_update_quantum_program(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumProgramRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumProgramRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.UpdateQuantumProgramRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.UpdateQuantumProgramRequest): request = engine.UpdateQuantumProgramRequest(request) @@ -735,6 +1081,9 @@ def sample_update_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -743,16 +1092,23 @@ def sample_update_quantum_program(): def create_quantum_job( self, - request: engine.CreateQuantumJobRequest | dict | None = None, + request: Optional[engine.CreateQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_create_quantum_job(): @@ -770,23 +1126,23 @@ def sample_create_quantum_job(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CreateQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CreateQuantumJobRequest): request = engine.CreateQuantumJobRequest(request) @@ -800,6 +1156,9 @@ def sample_create_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -808,16 +1167,23 @@ def sample_create_quantum_job(): def get_quantum_job( self, - request: engine.GetQuantumJobRequest | dict | None = None, + request: Optional[engine.GetQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_job(): @@ -835,23 +1201,23 @@ def sample_get_quantum_job(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumJobRequest): request = engine.GetQuantumJobRequest(request) @@ -865,6 +1231,9 @@ def sample_get_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -873,16 +1242,23 @@ def sample_get_quantum_job(): def list_quantum_jobs( self, - request: engine.ListQuantumJobsRequest | dict | None = None, + request: Optional[engine.ListQuantumJobsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumJobsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_jobs(): @@ -901,27 +1277,28 @@ def sample_list_quantum_jobs(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobsPager: - + Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumJobsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumJobsRequest): request = engine.ListQuantumJobsRequest(request) @@ -935,13 +1312,21 @@ def sample_list_quantum_jobs(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumJobsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -949,16 +1334,23 @@ def sample_list_quantum_jobs(): def delete_quantum_job( self, - request: engine.DeleteQuantumJobRequest | dict | None = None, + request: Optional[engine.DeleteQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_delete_quantum_job(): @@ -973,19 +1365,19 @@ def sample_delete_quantum_job(): client.delete_quantum_job(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.DeleteQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.DeleteQuantumJobRequest): request = engine.DeleteQuantumJobRequest(request) @@ -999,21 +1391,31 @@ def sample_delete_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. rpc(request, retry=retry, timeout=timeout, metadata=metadata) def update_quantum_job( self, - request: engine.UpdateQuantumJobRequest | dict | None = None, + request: Optional[engine.UpdateQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_update_quantum_job(): @@ -1031,23 +1433,23 @@ def sample_update_quantum_job(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.UpdateQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.UpdateQuantumJobRequest): request = engine.UpdateQuantumJobRequest(request) @@ -1061,6 +1463,9 @@ def sample_update_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1069,16 +1474,23 @@ def sample_update_quantum_job(): def cancel_quantum_job( self, - request: engine.CancelQuantumJobRequest | dict | None = None, + request: Optional[engine.CancelQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_cancel_quantum_job(): @@ -1093,19 +1505,19 @@ def sample_cancel_quantum_job(): client.cancel_quantum_job(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.CancelQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CancelQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CancelQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CancelQuantumJobRequest): request = engine.CancelQuantumJobRequest(request) @@ -1119,21 +1531,31 @@ def sample_cancel_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. rpc(request, retry=retry, timeout=timeout, metadata=metadata) def list_quantum_job_events( self, - request: engine.ListQuantumJobEventsRequest | dict | None = None, + request: Optional[engine.ListQuantumJobEventsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumJobEventsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_job_events(): @@ -1152,27 +1574,28 @@ def sample_list_quantum_job_events(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobEventsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobEventsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumJobEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumJobEventsRequest): request = engine.ListQuantumJobEventsRequest(request) @@ -1186,13 +1609,21 @@ def sample_list_quantum_job_events(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumJobEventsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1200,16 +1631,23 @@ def sample_list_quantum_job_events(): def get_quantum_result( self, - request: engine.GetQuantumResultRequest | dict | None = None, + request: Optional[engine.GetQuantumResultRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumResult: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_result(): @@ -1227,23 +1665,23 @@ def sample_get_quantum_result(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumResult: + cirq_google.cloud.quantum_v1alpha1.types.QuantumResult: - """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumResultRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumResultRequest): request = engine.GetQuantumResultRequest(request) @@ -1257,6 +1695,9 @@ def sample_get_quantum_result(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1265,16 +1706,23 @@ def sample_get_quantum_result(): def list_quantum_processors( self, - request: engine.ListQuantumProcessorsRequest | dict | None = None, + request: Optional[engine.ListQuantumProcessorsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumProcessorsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_processors(): @@ -1293,27 +1741,28 @@ def sample_list_quantum_processors(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProcessorsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProcessorsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumProcessorsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumProcessorsRequest): request = engine.ListQuantumProcessorsRequest(request) @@ -1327,13 +1776,21 @@ def sample_list_quantum_processors(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumProcessorsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1341,16 +1798,23 @@ def sample_list_quantum_processors(): def get_quantum_processor( self, - request: engine.GetQuantumProcessorRequest | dict | None = None, + request: Optional[engine.GetQuantumProcessorRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProcessor: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_processor(): @@ -1368,23 +1832,23 @@ def sample_get_quantum_processor(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumProcessorRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProcessorRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProcessor: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumProcessorRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumProcessorRequest): request = engine.GetQuantumProcessorRequest(request) @@ -1398,6 +1862,105 @@ def sample_get_quantum_processor(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + + # Done; return the response. + return response + + def get_quantum_processor_config( + self, + request: Optional[engine.GetQuantumProcessorConfigRequest | dict] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProcessorConfig: + r"""- + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import quantum_v1alpha1 + + def sample_get_quantum_processor_config(): + # Create a client + client = quantum_v1alpha1.QuantumEngineServiceClient() + + # Initialize request argument(s) + request = quantum_v1alpha1.GetQuantumProcessorConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_quantum_processor_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProcessorConfigRequest, dict]): + The request object. - + name (str): + Required. - + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessorConfig: + - + """ # noqa E501 + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError( + 'If the `request` argument is set, then none of ' + 'the individual field arguments should be set.' + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumProcessorConfigRequest): + request = engine.GetQuantumProcessorConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_quantum_processor_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1406,16 +1969,23 @@ def sample_get_quantum_processor(): def list_quantum_calibrations( self, - request: engine.ListQuantumCalibrationsRequest | dict | None = None, + request: Optional[engine.ListQuantumCalibrationsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumCalibrationsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_calibrations(): @@ -1434,27 +2004,28 @@ def sample_list_quantum_calibrations(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumCalibrationsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumCalibrationsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumCalibrationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumCalibrationsRequest): request = engine.ListQuantumCalibrationsRequest(request) @@ -1468,13 +2039,21 @@ def sample_list_quantum_calibrations(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumCalibrationsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1482,16 +2061,23 @@ def sample_list_quantum_calibrations(): def get_quantum_calibration( self, - request: engine.GetQuantumCalibrationRequest | dict | None = None, + request: Optional[engine.GetQuantumCalibrationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumCalibration: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_calibration(): @@ -1509,23 +2095,23 @@ def sample_get_quantum_calibration(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumCalibrationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumCalibrationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumCalibration: + cirq_google.cloud.quantum_v1alpha1.types.QuantumCalibration: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumCalibrationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumCalibrationRequest): request = engine.GetQuantumCalibrationRequest(request) @@ -1539,6 +2125,9 @@ def sample_get_quantum_calibration(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1547,16 +2136,23 @@ def sample_get_quantum_calibration(): def create_quantum_reservation( self, - request: engine.CreateQuantumReservationRequest | dict | None = None, + request: Optional[engine.CreateQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_create_quantum_reservation(): @@ -1574,23 +2170,23 @@ def sample_create_quantum_reservation(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CreateQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CreateQuantumReservationRequest): request = engine.CreateQuantumReservationRequest(request) @@ -1604,6 +2200,9 @@ def sample_create_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1612,16 +2211,23 @@ def sample_create_quantum_reservation(): def cancel_quantum_reservation( self, - request: engine.CancelQuantumReservationRequest | dict | None = None, + request: Optional[engine.CancelQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_cancel_quantum_reservation(): @@ -1639,23 +2245,23 @@ def sample_cancel_quantum_reservation(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CancelQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CancelQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CancelQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CancelQuantumReservationRequest): request = engine.CancelQuantumReservationRequest(request) @@ -1669,6 +2275,9 @@ def sample_cancel_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1677,16 +2286,23 @@ def sample_cancel_quantum_reservation(): def delete_quantum_reservation( self, - request: engine.DeleteQuantumReservationRequest | dict | None = None, + request: Optional[engine.DeleteQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_delete_quantum_reservation(): @@ -1701,19 +2317,19 @@ def sample_delete_quantum_reservation(): client.delete_quantum_reservation(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.DeleteQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.DeleteQuantumReservationRequest): request = engine.DeleteQuantumReservationRequest(request) @@ -1727,21 +2343,31 @@ def sample_delete_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. rpc(request, retry=retry, timeout=timeout, metadata=metadata) def get_quantum_reservation( self, - request: engine.GetQuantumReservationRequest | dict | None = None, + request: Optional[engine.GetQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_reservation(): @@ -1759,23 +2385,23 @@ def sample_get_quantum_reservation(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumReservationRequest): request = engine.GetQuantumReservationRequest(request) @@ -1789,6 +2415,9 @@ def sample_get_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1797,16 +2426,23 @@ def sample_get_quantum_reservation(): def list_quantum_reservations( self, - request: engine.ListQuantumReservationsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_reservations(): @@ -1825,27 +2461,28 @@ def sample_list_quantum_reservations(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumReservationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumReservationsRequest): request = engine.ListQuantumReservationsRequest(request) @@ -1859,13 +2496,21 @@ def sample_list_quantum_reservations(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumReservationsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1873,16 +2518,23 @@ def sample_list_quantum_reservations(): def update_quantum_reservation( self, - request: engine.UpdateQuantumReservationRequest | dict | None = None, + request: Optional[engine.UpdateQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_update_quantum_reservation(): @@ -1900,23 +2552,23 @@ def sample_update_quantum_reservation(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.UpdateQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.UpdateQuantumReservationRequest): request = engine.UpdateQuantumReservationRequest(request) @@ -1930,6 +2582,9 @@ def sample_update_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1938,16 +2593,23 @@ def sample_update_quantum_reservation(): def quantum_run_stream( self, - requests: Iterator[engine.QuantumRunStreamRequest] | None = None, + requests: Optional[Iterator[engine.QuantumRunStreamRequest]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> Iterable[engine.QuantumRunStreamResponse]: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_quantum_run_stream(): @@ -1976,16 +2638,18 @@ def request_generator(): print(response) Args: - requests (Iterator[google.cloud.quantum_v1alpha1.types.QuantumRunStreamRequest]): + requests (Iterator[cirq_google.cloud.quantum_v1alpha1.types.QuantumRunStreamRequest]): The request object iterator. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - Iterable[google.cloud.quantum_v1alpha1.types.QuantumRunStreamResponse]: + Iterable[cirq_google.cloud.quantum_v1alpha1.types.QuantumRunStreamResponse]: - """ @@ -1993,6 +2657,9 @@ def request_generator(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.quantum_run_stream] + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata) @@ -2001,16 +2668,23 @@ def request_generator(): def list_quantum_reservation_grants( self, - request: engine.ListQuantumReservationGrantsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationGrantsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationGrantsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_reservation_grants(): @@ -2029,27 +2703,28 @@ def sample_list_quantum_reservation_grants(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationGrantsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationGrantsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumReservationGrantsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumReservationGrantsRequest): request = engine.ListQuantumReservationGrantsRequest(request) @@ -2063,13 +2738,21 @@ def sample_list_quantum_reservation_grants(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumReservationGrantsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -2077,16 +2760,23 @@ def sample_list_quantum_reservation_grants(): def reallocate_quantum_reservation_grant( self, - request: engine.ReallocateQuantumReservationGrantRequest | dict | None = None, + request: Optional[engine.ReallocateQuantumReservationGrantRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservationGrant: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_reallocate_quantum_reservation_grant(): @@ -2104,23 +2794,23 @@ def sample_reallocate_quantum_reservation_grant(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ReallocateQuantumReservationGrantRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ReallocateQuantumReservationGrantRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservationGrant: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationGrant: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ReallocateQuantumReservationGrantRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ReallocateQuantumReservationGrantRequest): request = engine.ReallocateQuantumReservationGrantRequest(request) @@ -2134,6 +2824,9 @@ def sample_reallocate_quantum_reservation_grant(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -2142,16 +2835,23 @@ def sample_reallocate_quantum_reservation_grant(): def list_quantum_reservation_budgets( self, - request: engine.ListQuantumReservationBudgetsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationBudgetsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationBudgetsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_reservation_budgets(): @@ -2170,27 +2870,28 @@ def sample_list_quantum_reservation_budgets(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationBudgetsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationBudgetsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumReservationBudgetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumReservationBudgetsRequest): request = engine.ListQuantumReservationBudgetsRequest(request) @@ -2204,13 +2905,21 @@ def sample_list_quantum_reservation_budgets(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumReservationBudgetsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -2218,16 +2927,23 @@ def sample_list_quantum_reservation_budgets(): def list_quantum_time_slots( self, - request: engine.ListQuantumTimeSlotsRequest | dict | None = None, + request: Optional[engine.ListQuantumTimeSlotsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumTimeSlotsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_time_slots(): @@ -2246,27 +2962,28 @@ def sample_list_quantum_time_slots(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumTimeSlotsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumTimeSlotsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumTimeSlotsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumTimeSlotsRequest): request = engine.ListQuantumTimeSlotsRequest(request) @@ -2280,22 +2997,30 @@ def sample_list_quantum_time_slots(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumTimeSlotsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. return response - def __enter__(self): + def __enter__(self) -> "QuantumEngineServiceClient": return self - def __exit__(self, type_, value, traceback): + def __exit__(self, typ, value, traceback): """Releases underlying transport's resources. .. warning:: @@ -2306,12 +3031,9 @@ def __exit__(self, type_, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=importlib.metadata.version("google-cloud-quantum") - ) -except ModuleNotFoundError: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=cirq_google.__version__) +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ __all__ = ("QuantumEngineServiceClient",) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/pagers.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/pagers.py index a2c2963fb46..e4350252fd7 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/pagers.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/pagers.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,10 +13,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import Any, AsyncIterator, Awaitable, Callable, Iterator, Sequence -from __future__ import annotations +from google.api_core import gapic_v1, retry as retries, retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Iterator, Sequence +try: + OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault | None + OptionalAsyncRetry = retries_async.AsyncRetry | gapic_v1.method._MethodDefault | None +except AttributeError: # pragma: NO COVER + OptionalRetry = retries.Retry | object | None # type: ignore + OptionalAsyncRetry = retries_async.AsyncRetry | object | None # type: ignore from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum @@ -25,7 +31,7 @@ class ListQuantumProgramsPager: """A pager for iterating through ``list_quantum_programs`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` object, and provides an ``__iter__`` method to iterate through its ``programs`` field. @@ -34,7 +40,7 @@ class ListQuantumProgramsPager: through the ``programs`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -45,23 +51,32 @@ def __init__( request: engine.ListQuantumProgramsRequest, response: engine.ListQuantumProgramsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumProgramsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -72,7 +87,9 @@ def pages(self) -> Iterator[engine.ListQuantumProgramsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumProgram]: @@ -80,14 +97,14 @@ def __iter__(self) -> Iterator[quantum.QuantumProgram]: yield from page.programs def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumProgramsAsyncPager: """A pager for iterating through ``list_quantum_programs`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` object, and provides an ``__aiter__`` method to iterate through its ``programs`` field. @@ -96,7 +113,7 @@ class ListQuantumProgramsAsyncPager: through the ``programs`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -107,23 +124,32 @@ def __init__( request: engine.ListQuantumProgramsRequest, response: engine.ListQuantumProgramsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumProgramsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -134,7 +160,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumProgramsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumProgram]: @@ -146,14 +174,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumJobsPager: """A pager for iterating through ``list_quantum_jobs`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` object, and provides an ``__iter__`` method to iterate through its ``jobs`` field. @@ -162,7 +190,7 @@ class ListQuantumJobsPager: through the ``jobs`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -173,23 +201,32 @@ def __init__( request: engine.ListQuantumJobsRequest, response: engine.ListQuantumJobsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumJobsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -200,7 +237,9 @@ def pages(self) -> Iterator[engine.ListQuantumJobsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumJob]: @@ -208,14 +247,14 @@ def __iter__(self) -> Iterator[quantum.QuantumJob]: yield from page.jobs def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumJobsAsyncPager: """A pager for iterating through ``list_quantum_jobs`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` object, and provides an ``__aiter__`` method to iterate through its ``jobs`` field. @@ -224,7 +263,7 @@ class ListQuantumJobsAsyncPager: through the ``jobs`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -235,23 +274,32 @@ def __init__( request: engine.ListQuantumJobsRequest, response: engine.ListQuantumJobsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumJobsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -262,7 +310,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumJobsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumJob]: @@ -274,14 +324,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumJobEventsPager: """A pager for iterating through ``list_quantum_job_events`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` object, and provides an ``__iter__`` method to iterate through its ``events`` field. @@ -290,7 +340,7 @@ class ListQuantumJobEventsPager: through the ``events`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -301,23 +351,32 @@ def __init__( request: engine.ListQuantumJobEventsRequest, response: engine.ListQuantumJobEventsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumJobEventsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -328,7 +387,9 @@ def pages(self) -> Iterator[engine.ListQuantumJobEventsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumJobEvent]: @@ -336,14 +397,14 @@ def __iter__(self) -> Iterator[quantum.QuantumJobEvent]: yield from page.events def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumJobEventsAsyncPager: """A pager for iterating through ``list_quantum_job_events`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` object, and provides an ``__aiter__`` method to iterate through its ``events`` field. @@ -352,7 +413,7 @@ class ListQuantumJobEventsAsyncPager: through the ``events`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -363,23 +424,32 @@ def __init__( request: engine.ListQuantumJobEventsRequest, response: engine.ListQuantumJobEventsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumJobEventsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -390,7 +460,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumJobEventsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumJobEvent]: @@ -402,14 +474,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumProcessorsPager: """A pager for iterating through ``list_quantum_processors`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` object, and provides an ``__iter__`` method to iterate through its ``processors`` field. @@ -418,7 +490,7 @@ class ListQuantumProcessorsPager: through the ``processors`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -429,23 +501,32 @@ def __init__( request: engine.ListQuantumProcessorsRequest, response: engine.ListQuantumProcessorsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumProcessorsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -456,7 +537,9 @@ def pages(self) -> Iterator[engine.ListQuantumProcessorsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumProcessor]: @@ -464,14 +547,14 @@ def __iter__(self) -> Iterator[quantum.QuantumProcessor]: yield from page.processors def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumProcessorsAsyncPager: """A pager for iterating through ``list_quantum_processors`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` object, and provides an ``__aiter__`` method to iterate through its ``processors`` field. @@ -480,7 +563,7 @@ class ListQuantumProcessorsAsyncPager: through the ``processors`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -491,23 +574,32 @@ def __init__( request: engine.ListQuantumProcessorsRequest, response: engine.ListQuantumProcessorsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumProcessorsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -518,7 +610,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumProcessorsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumProcessor]: @@ -530,14 +624,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumCalibrationsPager: """A pager for iterating through ``list_quantum_calibrations`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` object, and provides an ``__iter__`` method to iterate through its ``calibrations`` field. @@ -546,7 +640,7 @@ class ListQuantumCalibrationsPager: through the ``calibrations`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -557,23 +651,32 @@ def __init__( request: engine.ListQuantumCalibrationsRequest, response: engine.ListQuantumCalibrationsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumCalibrationsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -584,7 +687,9 @@ def pages(self) -> Iterator[engine.ListQuantumCalibrationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumCalibration]: @@ -592,14 +697,14 @@ def __iter__(self) -> Iterator[quantum.QuantumCalibration]: yield from page.calibrations def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumCalibrationsAsyncPager: """A pager for iterating through ``list_quantum_calibrations`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` object, and provides an ``__aiter__`` method to iterate through its ``calibrations`` field. @@ -608,7 +713,7 @@ class ListQuantumCalibrationsAsyncPager: through the ``calibrations`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -619,23 +724,32 @@ def __init__( request: engine.ListQuantumCalibrationsRequest, response: engine.ListQuantumCalibrationsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumCalibrationsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -646,7 +760,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumCalibrationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumCalibration]: @@ -658,14 +774,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationsPager: """A pager for iterating through ``list_quantum_reservations`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` object, and provides an ``__iter__`` method to iterate through its ``reservations`` field. @@ -674,7 +790,7 @@ class ListQuantumReservationsPager: through the ``reservations`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -685,23 +801,32 @@ def __init__( request: engine.ListQuantumReservationsRequest, response: engine.ListQuantumReservationsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumReservationsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -712,7 +837,9 @@ def pages(self) -> Iterator[engine.ListQuantumReservationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumReservation]: @@ -720,14 +847,14 @@ def __iter__(self) -> Iterator[quantum.QuantumReservation]: yield from page.reservations def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationsAsyncPager: """A pager for iterating through ``list_quantum_reservations`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` object, and provides an ``__aiter__`` method to iterate through its ``reservations`` field. @@ -736,7 +863,7 @@ class ListQuantumReservationsAsyncPager: through the ``reservations`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -747,23 +874,32 @@ def __init__( request: engine.ListQuantumReservationsRequest, response: engine.ListQuantumReservationsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumReservationsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -774,7 +910,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumReservationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumReservation]: @@ -786,25 +924,25 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationGrantsPager: """A pager for iterating through ``list_quantum_reservation_grants`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``reservation_grants`` field. + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` object, + and provides an ``__iter__`` method to iterate through its ``reservation_grants`` field. If there are more pages, the ``__iter__`` method will make additional ``ListQuantumReservationGrants`` requests and continue to iterate through the ``reservation_grants`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. + All the usual + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` + attributes are available on the pager. If multiple requests are made, only the most recent + response is retained, and thus used for attribute lookup. """ def __init__( @@ -813,23 +951,32 @@ def __init__( request: engine.ListQuantumReservationGrantsRequest, response: engine.ListQuantumReservationGrantsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 self._method = method self._request = engine.ListQuantumReservationGrantsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -840,7 +987,9 @@ def pages(self) -> Iterator[engine.ListQuantumReservationGrantsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumReservationGrant]: @@ -848,25 +997,25 @@ def __iter__(self) -> Iterator[quantum.QuantumReservationGrant]: yield from page.reservation_grants def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationGrantsAsyncPager: """A pager for iterating through ``list_quantum_reservation_grants`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``reservation_grants`` field. + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` object, + and provides an ``__aiter__`` method to iterate through its ``reservation_grants`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListQuantumReservationGrants`` requests and continue to iterate through the ``reservation_grants`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. + All the usual + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` + attributes are available on the pager. If multiple requests are made, only the most recent + response is retained, and thus used for attribute lookup. """ def __init__( @@ -875,23 +1024,32 @@ def __init__( request: engine.ListQuantumReservationGrantsRequest, response: engine.ListQuantumReservationGrantsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 self._method = method self._request = engine.ListQuantumReservationGrantsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -902,7 +1060,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumReservationGrantsRespon yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumReservationGrant]: @@ -914,25 +1074,25 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationBudgetsPager: """A pager for iterating through ``list_quantum_reservation_budgets`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``reservation_budgets`` field. + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` object, + and provides an ``__iter__`` method to iterate through its ``reservation_budgets`` field. If there are more pages, the ``__iter__`` method will make additional ``ListQuantumReservationBudgets`` requests and continue to iterate through the ``reservation_budgets`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. + All the usual + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` + attributes are available on the pager. If multiple requests are made, only the most recent + response is retained, and thus used for attribute lookup. """ def __init__( @@ -941,23 +1101,32 @@ def __init__( request: engine.ListQuantumReservationBudgetsRequest, response: engine.ListQuantumReservationBudgetsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 self._method = method self._request = engine.ListQuantumReservationBudgetsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -968,7 +1137,9 @@ def pages(self) -> Iterator[engine.ListQuantumReservationBudgetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumReservationBudget]: @@ -976,25 +1147,25 @@ def __iter__(self) -> Iterator[quantum.QuantumReservationBudget]: yield from page.reservation_budgets def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationBudgetsAsyncPager: """A pager for iterating through ``list_quantum_reservation_budgets`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``reservation_budgets`` field. + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` object, + and provides an ``__aiter__`` method to iterate through its ``reservation_budgets`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListQuantumReservationBudgets`` requests and continue to iterate through the ``reservation_budgets`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. + All the usual + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` + attributes are available on the pager. If multiple requests are made, only the most recent + response is retained, and thus used for attribute lookup. """ def __init__( @@ -1003,23 +1174,32 @@ def __init__( request: engine.ListQuantumReservationBudgetsRequest, response: engine.ListQuantumReservationBudgetsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 self._method = method self._request = engine.ListQuantumReservationBudgetsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -1030,7 +1210,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumReservationBudgetsRespo yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumReservationBudget]: @@ -1042,14 +1224,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumTimeSlotsPager: """A pager for iterating through ``list_quantum_time_slots`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` object, and provides an ``__iter__`` method to iterate through its ``time_slots`` field. @@ -1058,7 +1240,7 @@ class ListQuantumTimeSlotsPager: through the ``time_slots`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -1069,23 +1251,32 @@ def __init__( request: engine.ListQuantumTimeSlotsRequest, response: engine.ListQuantumTimeSlotsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumTimeSlotsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -1096,7 +1287,9 @@ def pages(self) -> Iterator[engine.ListQuantumTimeSlotsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumTimeSlot]: @@ -1104,14 +1297,14 @@ def __iter__(self) -> Iterator[quantum.QuantumTimeSlot]: yield from page.time_slots def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumTimeSlotsAsyncPager: """A pager for iterating through ``list_quantum_time_slots`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` object, and provides an ``__aiter__`` method to iterate through its ``time_slots`` field. @@ -1120,7 +1313,7 @@ class ListQuantumTimeSlotsAsyncPager: through the ``time_slots`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -1131,23 +1324,32 @@ def __init__( request: engine.ListQuantumTimeSlotsRequest, response: engine.ListQuantumTimeSlotsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumTimeSlotsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -1158,7 +1360,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumTimeSlotsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumTimeSlot]: @@ -1170,4 +1374,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/README.rst b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/README.rst new file mode 100755 index 00000000000..2e942691dec --- /dev/null +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`QuantumEngineServiceTransport` is the ABC for all transports. +- public child `QuantumEngineServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `QuantumEngineServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseQuantumEngineServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `QuantumEngineServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/__init__.py index f6edf4f3e46..b9c62c311c4 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -18,15 +18,20 @@ from .base import QuantumEngineServiceTransport from .grpc import QuantumEngineServiceGrpcTransport from .grpc_asyncio import QuantumEngineServiceGrpcAsyncIOTransport +from .rest import QuantumEngineServiceRestTransport +from .rest import QuantumEngineServiceRestInterceptor # Compile a registry of transports. -_transport_registry = OrderedDict() # type: dict[str, type[QuantumEngineServiceTransport]] +_transport_registry: dict[str, type[QuantumEngineServiceTransport]] = OrderedDict() _transport_registry['grpc'] = QuantumEngineServiceGrpcTransport _transport_registry['grpc_asyncio'] = QuantumEngineServiceGrpcAsyncIOTransport +_transport_registry['rest'] = QuantumEngineServiceRestTransport __all__ = ( 'QuantumEngineServiceTransport', 'QuantumEngineServiceGrpcTransport', 'QuantumEngineServiceGrpcAsyncIOTransport', + 'QuantumEngineServiceRestTransport', + 'QuantumEngineServiceRestInterceptor', ) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/base.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/base.py index ee1ebfc8bd8..33a416cec5f 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/base.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/base.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,32 +12,25 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -# ruff: noqa: E501 - -from __future__ import annotations - +# import abc -import importlib.metadata -from typing import Awaitable, Callable, Sequence, TYPE_CHECKING +from typing import Awaitable, Callable, Optional, Sequence import google.api_core import google.auth +import google.protobuf from google.api_core import exceptions as core_exceptions, gapic_v1 +from google.auth import credentials as ga_credentials from google.oauth2 import service_account +from google.protobuf import empty_pb2 -if TYPE_CHECKING: - from google.auth import credentials as ga_credentials - from google.protobuf import empty_pb2 +import cirq_google +from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum - from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=cirq_google.__version__) -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=importlib.metadata.version("google-cloud-quantum") - ) -except ModuleNotFoundError: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ class QuantumEngineServiceTransport(abc.ABC): @@ -51,19 +44,20 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - quota_project_id: str | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: bool | None = False, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. Args: host (Optional[str]): - The hostname to connect to. + The hostname to connect to (default: 'quantum.googleapis.com'). credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -83,15 +77,13 @@ def __init__( always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False # If no credentials are provided, then determine the appropriate # defaults. @@ -104,10 +96,14 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: + elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - # If the credentials are service account credentials, then always try to use self signed JWT. + # If the credentials are service account credentials, then always try to use self signed + # JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) @@ -118,6 +114,15 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -166,6 +171,9 @@ def _prep_wrapped_messages(self, client_info): self.get_quantum_processor: gapic_v1.method.wrap_method( self.get_quantum_processor, default_timeout=60.0, client_info=client_info ), + self.get_quantum_processor_config: gapic_v1.method.wrap_method( + self.get_quantum_processor_config, default_timeout=60.0, client_info=client_info + ), self.list_quantum_calibrations: gapic_v1.method.wrap_method( self.list_quantum_calibrations, default_timeout=60.0, client_info=client_info ), @@ -342,6 +350,15 @@ def get_quantum_processor( ]: raise NotImplementedError() + @property + def get_quantum_processor_config( + self, + ) -> Callable[ + [engine.GetQuantumProcessorConfigRequest], + quantum.QuantumProcessorConfig | Awaitable[quantum.QuantumProcessorConfig], + ]: + raise NotImplementedError() + @property def list_quantum_calibrations( self, @@ -460,5 +477,9 @@ def list_quantum_time_slots( ]: raise NotImplementedError() + @property + def kind(self) -> str: + raise NotImplementedError() + __all__ = ('QuantumEngineServiceTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc.py index 91ff63267f8..50d42b6c358 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,23 +13,86 @@ # See the License for the specific language governing permissions and # limitations under the License. # - -from __future__ import annotations - +import importlib.util +import logging as std_logging +import pickle import warnings -from typing import Callable, Sequence, TYPE_CHECKING +from typing import Callable, Optional, Sequence +import google.auth +import google.protobuf.message import grpc # type: ignore +import proto from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials from google.auth.transport.grpc import SslCredentials from google.protobuf import empty_pb2 +from google.protobuf.json_format import MessageToJson from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum from .base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport -if TYPE_CHECKING: - from google.auth import credentials as ga_credentials +CLIENT_LOGGING_SUPPORTED = importlib.util.find_spec("google.api_core.client_logging") is not None + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = {"payload": response_payload, "metadata": metadata, "status": "OK"} + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response class QuantumEngineServiceGrpcTransport(QuantumEngineServiceTransport): @@ -51,50 +114,54 @@ def __init__( self, *, host: str = 'quantum.googleapis.com', - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - channel: grpc.Channel | None = None, - api_mtls_endpoint: str | None = None, - client_cert_source: Callable[[], tuple[bytes, bytes]] | None = None, - ssl_channel_credentials: grpc.ChannelCredentials | None = None, - client_cert_source_for_mtls: Callable[[], tuple[bytes, bytes]] | None = None, - quota_project_id: str | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel | Callable[..., grpc.Channel]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: bool | None = False, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. Args: host (Optional[str]): - The hostname to connect to. + The hostname to connect to (default: 'quantum.googleapis.com'). credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], tuple[bytes, bytes]]]): + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], tuple[bytes, bytes]]]): + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -120,9 +187,10 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, grpc.Channel): # Ignore credentials if a channel was passed. credentials = None + self._ignore_credentials = True # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None @@ -157,10 +225,13 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, @@ -171,23 +242,25 @@ def __init__( ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ - ('grpc.max_send_message_length', 20 * 1024 * 1024), # 20MiB - ('grpc.max_receive_message_length', -1), # unlimited - ('grpc.max_metadata_length', 10 * 1024 * 1024), # 10MiB + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod def create_channel( cls, host: str = 'quantum.googleapis.com', - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - quota_project_id: str | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. @@ -251,7 +324,7 @@ def create_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_program' not in self._stubs: - self._stubs['create_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumProgram', request_serializer=engine.CreateQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -277,7 +350,7 @@ def get_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_program' not in self._stubs: - self._stubs['get_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProgram', request_serializer=engine.GetQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -303,7 +376,7 @@ def list_quantum_programs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_programs' not in self._stubs: - self._stubs['list_quantum_programs'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_programs'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumPrograms', request_serializer=engine.ListQuantumProgramsRequest.serialize, response_deserializer=engine.ListQuantumProgramsResponse.deserialize, @@ -329,7 +402,7 @@ def delete_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_program' not in self._stubs: - self._stubs['delete_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumProgram', request_serializer=engine.DeleteQuantumProgramRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -355,7 +428,7 @@ def update_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_program' not in self._stubs: - self._stubs['update_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumProgram', request_serializer=engine.UpdateQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -379,7 +452,7 @@ def create_quantum_job(self) -> Callable[[engine.CreateQuantumJobRequest], quant # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_job' not in self._stubs: - self._stubs['create_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumJob', request_serializer=engine.CreateQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -403,7 +476,7 @@ def get_quantum_job(self) -> Callable[[engine.GetQuantumJobRequest], quantum.Qua # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_job' not in self._stubs: - self._stubs['get_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumJob', request_serializer=engine.GetQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -429,7 +502,7 @@ def list_quantum_jobs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_jobs' not in self._stubs: - self._stubs['list_quantum_jobs'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_jobs'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobs', request_serializer=engine.ListQuantumJobsRequest.serialize, response_deserializer=engine.ListQuantumJobsResponse.deserialize, @@ -453,7 +526,7 @@ def delete_quantum_job(self) -> Callable[[engine.DeleteQuantumJobRequest], empty # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_job' not in self._stubs: - self._stubs['delete_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumJob', request_serializer=engine.DeleteQuantumJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -477,7 +550,7 @@ def update_quantum_job(self) -> Callable[[engine.UpdateQuantumJobRequest], quant # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_job' not in self._stubs: - self._stubs['update_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumJob', request_serializer=engine.UpdateQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -501,7 +574,7 @@ def cancel_quantum_job(self) -> Callable[[engine.CancelQuantumJobRequest], empty # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'cancel_quantum_job' not in self._stubs: - self._stubs['cancel_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['cancel_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumJob', request_serializer=engine.CancelQuantumJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -527,7 +600,7 @@ def list_quantum_job_events( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_job_events' not in self._stubs: - self._stubs['list_quantum_job_events'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_job_events'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobEvents', request_serializer=engine.ListQuantumJobEventsRequest.serialize, response_deserializer=engine.ListQuantumJobEventsResponse.deserialize, @@ -553,7 +626,7 @@ def get_quantum_result( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_result' not in self._stubs: - self._stubs['get_quantum_result'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_result'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumResult', request_serializer=engine.GetQuantumResultRequest.serialize, response_deserializer=quantum.QuantumResult.deserialize, @@ -579,7 +652,7 @@ def list_quantum_processors( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_processors' not in self._stubs: - self._stubs['list_quantum_processors'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_processors'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumProcessors', request_serializer=engine.ListQuantumProcessorsRequest.serialize, response_deserializer=engine.ListQuantumProcessorsResponse.deserialize, @@ -605,13 +678,39 @@ def get_quantum_processor( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_processor' not in self._stubs: - self._stubs['get_quantum_processor'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_processor'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProcessor', request_serializer=engine.GetQuantumProcessorRequest.serialize, response_deserializer=quantum.QuantumProcessor.deserialize, ) return self._stubs['get_quantum_processor'] + @property + def get_quantum_processor_config( + self, + ) -> Callable[[engine.GetQuantumProcessorConfigRequest], quantum.QuantumProcessorConfig]: + r"""Return a callable for the get quantum processor config method over gRPC. + + - + + Returns: + Callable[[~.GetQuantumProcessorConfigRequest], + ~.QuantumProcessorConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_quantum_processor_config' not in self._stubs: + self._stubs['get_quantum_processor_config'] = self._logged_channel.unary_unary( + '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProcessorConfig', + request_serializer=engine.GetQuantumProcessorConfigRequest.serialize, + response_deserializer=quantum.QuantumProcessorConfig.deserialize, + ) + return self._stubs['get_quantum_processor_config'] + @property def list_quantum_calibrations( self, @@ -631,7 +730,7 @@ def list_quantum_calibrations( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_calibrations' not in self._stubs: - self._stubs['list_quantum_calibrations'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_calibrations'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumCalibrations', request_serializer=engine.ListQuantumCalibrationsRequest.serialize, response_deserializer=engine.ListQuantumCalibrationsResponse.deserialize, @@ -657,7 +756,7 @@ def get_quantum_calibration( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_calibration' not in self._stubs: - self._stubs['get_quantum_calibration'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_calibration'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumCalibration', request_serializer=engine.GetQuantumCalibrationRequest.serialize, response_deserializer=quantum.QuantumCalibration.deserialize, @@ -683,7 +782,7 @@ def create_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_reservation' not in self._stubs: - self._stubs['create_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumReservation', request_serializer=engine.CreateQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -709,7 +808,7 @@ def cancel_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'cancel_quantum_reservation' not in self._stubs: - self._stubs['cancel_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['cancel_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumReservation', request_serializer=engine.CancelQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -735,7 +834,7 @@ def delete_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_reservation' not in self._stubs: - self._stubs['delete_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumReservation', request_serializer=engine.DeleteQuantumReservationRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -761,7 +860,7 @@ def get_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_reservation' not in self._stubs: - self._stubs['get_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumReservation', request_serializer=engine.GetQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -787,7 +886,7 @@ def list_quantum_reservations( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservations' not in self._stubs: - self._stubs['list_quantum_reservations'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservations'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservations', request_serializer=engine.ListQuantumReservationsRequest.serialize, response_deserializer=engine.ListQuantumReservationsResponse.deserialize, @@ -813,7 +912,7 @@ def update_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_reservation' not in self._stubs: - self._stubs['update_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumReservation', request_serializer=engine.UpdateQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -839,7 +938,7 @@ def quantum_run_stream( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'quantum_run_stream' not in self._stubs: - self._stubs['quantum_run_stream'] = self.grpc_channel.stream_stream( + self._stubs['quantum_run_stream'] = self._logged_channel.stream_stream( '/google.cloud.quantum.v1alpha1.QuantumEngineService/QuantumRunStream', request_serializer=engine.QuantumRunStreamRequest.serialize, response_deserializer=engine.QuantumRunStreamResponse.deserialize, @@ -868,7 +967,7 @@ def list_quantum_reservation_grants( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservation_grants' not in self._stubs: - self._stubs['list_quantum_reservation_grants'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservation_grants'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationGrants', request_serializer=engine.ListQuantumReservationGrantsRequest.serialize, response_deserializer=engine.ListQuantumReservationGrantsResponse.deserialize, @@ -897,7 +996,7 @@ def reallocate_quantum_reservation_grant( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'reallocate_quantum_reservation_grant' not in self._stubs: - self._stubs['reallocate_quantum_reservation_grant'] = self.grpc_channel.unary_unary( + self._stubs['reallocate_quantum_reservation_grant'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ReallocateQuantumReservationGrant', request_serializer=engine.ReallocateQuantumReservationGrantRequest.serialize, response_deserializer=quantum.QuantumReservationGrant.deserialize, @@ -926,7 +1025,7 @@ def list_quantum_reservation_budgets( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservation_budgets' not in self._stubs: - self._stubs['list_quantum_reservation_budgets'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservation_budgets'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationBudgets', request_serializer=engine.ListQuantumReservationBudgetsRequest.serialize, response_deserializer=engine.ListQuantumReservationBudgetsResponse.deserialize, @@ -952,7 +1051,7 @@ def list_quantum_time_slots( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_time_slots' not in self._stubs: - self._stubs['list_quantum_time_slots'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_time_slots'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumTimeSlots', request_serializer=engine.ListQuantumTimeSlotsRequest.serialize, response_deserializer=engine.ListQuantumTimeSlotsResponse.deserialize, @@ -960,7 +1059,11 @@ def list_quantum_time_slots( return self._stubs['list_quantum_time_slots'] def close(self): - self.grpc_channel.close() + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" __all__ = ('QuantumEngineServiceGrpcTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc_asyncio.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc_asyncio.py index 42fdf91e477..61e6cd3c935 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc_asyncio.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc_asyncio.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,24 +13,87 @@ # See the License for the specific language governing permissions and # limitations under the License. # - -from __future__ import annotations - +import importlib.util +import inspect +import logging as std_logging +import pickle import warnings -from typing import Awaitable, Callable, Sequence, TYPE_CHECKING +from typing import Awaitable, Callable, Optional, Sequence +import google.protobuf.message import grpc # type: ignore +import proto from google.api_core import gapic_v1, grpc_helpers_async +from google.auth import credentials as ga_credentials from google.auth.transport.grpc import SslCredentials from google.protobuf import empty_pb2 +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum from .base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport -if TYPE_CHECKING: - from google.auth import credentials as ga_credentials - from grpc.experimental import aio # type: ignore +CLIENT_LOGGING_SUPPORTED = importlib.util.find_spec("google.api_core.client_logging") is not None + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = {"payload": response_payload, "metadata": metadata, "status": "OK"} + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response class QuantumEngineServiceGrpcAsyncIOTransport(QuantumEngineServiceTransport): @@ -53,10 +116,10 @@ class QuantumEngineServiceGrpcAsyncIOTransport(QuantumEngineServiceTransport): def create_channel( cls, host: str = 'quantum.googleapis.com', - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - quota_project_id: str | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, **kwargs, ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. @@ -69,7 +132,6 @@ def create_channel( the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -96,51 +158,55 @@ def __init__( self, *, host: str = 'quantum.googleapis.com', - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - channel: aio.Channel | None = None, - api_mtls_endpoint: str | None = None, - client_cert_source: Callable[[], tuple[bytes, bytes]] | None = None, - ssl_channel_credentials: grpc.ChannelCredentials | None = None, - client_cert_source_for_mtls: Callable[[], tuple[bytes, bytes]] | None = None, - quota_project_id=None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel | Callable[..., aio.Channel]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: bool | None = False, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. Args: host (Optional[str]): - The hostname to connect to. + The hostname to connect to (default: 'quantum.googleapis.com'). credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], tuple[bytes, bytes]]]): + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], tuple[bytes, bytes]]]): + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -166,9 +232,10 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, aio.Channel): # Ignore credentials if a channel was passed. credentials = None + self._ignore_credentials = True # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None @@ -202,10 +269,13 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, @@ -216,13 +286,18 @@ def __init__( ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ - ('grpc.max_send_message_length', 20 * 1024 * 1024), # 20MiB - ('grpc.max_receive_message_length', -1), # unlimited - ('grpc.max_metadata_length', 10 * 1024 * 1024), # 10MiB + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @property @@ -254,7 +329,7 @@ def create_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_program' not in self._stubs: - self._stubs['create_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumProgram', request_serializer=engine.CreateQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -280,7 +355,7 @@ def get_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_program' not in self._stubs: - self._stubs['get_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProgram', request_serializer=engine.GetQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -308,7 +383,7 @@ def list_quantum_programs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_programs' not in self._stubs: - self._stubs['list_quantum_programs'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_programs'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumPrograms', request_serializer=engine.ListQuantumProgramsRequest.serialize, response_deserializer=engine.ListQuantumProgramsResponse.deserialize, @@ -334,7 +409,7 @@ def delete_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_program' not in self._stubs: - self._stubs['delete_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumProgram', request_serializer=engine.DeleteQuantumProgramRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -360,7 +435,7 @@ def update_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_program' not in self._stubs: - self._stubs['update_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumProgram', request_serializer=engine.UpdateQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -386,7 +461,7 @@ def create_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_job' not in self._stubs: - self._stubs['create_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumJob', request_serializer=engine.CreateQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -412,7 +487,7 @@ def get_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_job' not in self._stubs: - self._stubs['get_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumJob', request_serializer=engine.GetQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -438,7 +513,7 @@ def list_quantum_jobs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_jobs' not in self._stubs: - self._stubs['list_quantum_jobs'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_jobs'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobs', request_serializer=engine.ListQuantumJobsRequest.serialize, response_deserializer=engine.ListQuantumJobsResponse.deserialize, @@ -464,7 +539,7 @@ def delete_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_job' not in self._stubs: - self._stubs['delete_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumJob', request_serializer=engine.DeleteQuantumJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -490,7 +565,7 @@ def update_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_job' not in self._stubs: - self._stubs['update_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumJob', request_serializer=engine.UpdateQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -516,7 +591,7 @@ def cancel_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'cancel_quantum_job' not in self._stubs: - self._stubs['cancel_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['cancel_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumJob', request_serializer=engine.CancelQuantumJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -544,7 +619,7 @@ def list_quantum_job_events( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_job_events' not in self._stubs: - self._stubs['list_quantum_job_events'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_job_events'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobEvents', request_serializer=engine.ListQuantumJobEventsRequest.serialize, response_deserializer=engine.ListQuantumJobEventsResponse.deserialize, @@ -570,7 +645,7 @@ def get_quantum_result( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_result' not in self._stubs: - self._stubs['get_quantum_result'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_result'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumResult', request_serializer=engine.GetQuantumResultRequest.serialize, response_deserializer=quantum.QuantumResult.deserialize, @@ -598,7 +673,7 @@ def list_quantum_processors( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_processors' not in self._stubs: - self._stubs['list_quantum_processors'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_processors'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumProcessors', request_serializer=engine.ListQuantumProcessorsRequest.serialize, response_deserializer=engine.ListQuantumProcessorsResponse.deserialize, @@ -624,13 +699,41 @@ def get_quantum_processor( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_processor' not in self._stubs: - self._stubs['get_quantum_processor'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_processor'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProcessor', request_serializer=engine.GetQuantumProcessorRequest.serialize, response_deserializer=quantum.QuantumProcessor.deserialize, ) return self._stubs['get_quantum_processor'] + @property + def get_quantum_processor_config( + self, + ) -> Callable[ + [engine.GetQuantumProcessorConfigRequest], Awaitable[quantum.QuantumProcessorConfig] + ]: + r"""Return a callable for the get quantum processor config method over gRPC. + + - + + Returns: + Callable[[~.GetQuantumProcessorConfigRequest], + Awaitable[~.QuantumProcessorConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_quantum_processor_config' not in self._stubs: + self._stubs['get_quantum_processor_config'] = self._logged_channel.unary_unary( + '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProcessorConfig', + request_serializer=engine.GetQuantumProcessorConfigRequest.serialize, + response_deserializer=quantum.QuantumProcessorConfig.deserialize, + ) + return self._stubs['get_quantum_processor_config'] + @property def list_quantum_calibrations( self, @@ -652,7 +755,7 @@ def list_quantum_calibrations( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_calibrations' not in self._stubs: - self._stubs['list_quantum_calibrations'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_calibrations'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumCalibrations', request_serializer=engine.ListQuantumCalibrationsRequest.serialize, response_deserializer=engine.ListQuantumCalibrationsResponse.deserialize, @@ -678,7 +781,7 @@ def get_quantum_calibration( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_calibration' not in self._stubs: - self._stubs['get_quantum_calibration'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_calibration'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumCalibration', request_serializer=engine.GetQuantumCalibrationRequest.serialize, response_deserializer=quantum.QuantumCalibration.deserialize, @@ -704,7 +807,7 @@ def create_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_reservation' not in self._stubs: - self._stubs['create_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumReservation', request_serializer=engine.CreateQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -730,7 +833,7 @@ def cancel_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'cancel_quantum_reservation' not in self._stubs: - self._stubs['cancel_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['cancel_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumReservation', request_serializer=engine.CancelQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -756,7 +859,7 @@ def delete_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_reservation' not in self._stubs: - self._stubs['delete_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumReservation', request_serializer=engine.DeleteQuantumReservationRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -782,7 +885,7 @@ def get_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_reservation' not in self._stubs: - self._stubs['get_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumReservation', request_serializer=engine.GetQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -810,7 +913,7 @@ def list_quantum_reservations( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservations' not in self._stubs: - self._stubs['list_quantum_reservations'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservations'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservations', request_serializer=engine.ListQuantumReservationsRequest.serialize, response_deserializer=engine.ListQuantumReservationsResponse.deserialize, @@ -836,7 +939,7 @@ def update_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_reservation' not in self._stubs: - self._stubs['update_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumReservation', request_serializer=engine.UpdateQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -862,7 +965,7 @@ def quantum_run_stream( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'quantum_run_stream' not in self._stubs: - self._stubs['quantum_run_stream'] = self.grpc_channel.stream_stream( + self._stubs['quantum_run_stream'] = self._logged_channel.stream_stream( '/google.cloud.quantum.v1alpha1.QuantumEngineService/QuantumRunStream', request_serializer=engine.QuantumRunStreamRequest.serialize, response_deserializer=engine.QuantumRunStreamResponse.deserialize, @@ -892,7 +995,7 @@ def list_quantum_reservation_grants( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservation_grants' not in self._stubs: - self._stubs['list_quantum_reservation_grants'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservation_grants'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationGrants', request_serializer=engine.ListQuantumReservationGrantsRequest.serialize, response_deserializer=engine.ListQuantumReservationGrantsResponse.deserialize, @@ -922,7 +1025,7 @@ def reallocate_quantum_reservation_grant( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'reallocate_quantum_reservation_grant' not in self._stubs: - self._stubs['reallocate_quantum_reservation_grant'] = self.grpc_channel.unary_unary( + self._stubs['reallocate_quantum_reservation_grant'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ReallocateQuantumReservationGrant', request_serializer=engine.ReallocateQuantumReservationGrantRequest.serialize, response_deserializer=quantum.QuantumReservationGrant.deserialize, @@ -952,7 +1055,7 @@ def list_quantum_reservation_budgets( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservation_budgets' not in self._stubs: - self._stubs['list_quantum_reservation_budgets'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservation_budgets'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationBudgets', request_serializer=engine.ListQuantumReservationBudgetsRequest.serialize, response_deserializer=engine.ListQuantumReservationBudgetsResponse.deserialize, @@ -980,15 +1083,118 @@ def list_quantum_time_slots( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_time_slots' not in self._stubs: - self._stubs['list_quantum_time_slots'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_time_slots'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumTimeSlots', request_serializer=engine.ListQuantumTimeSlotsRequest.serialize, response_deserializer=engine.ListQuantumTimeSlotsResponse.deserialize, ) return self._stubs['list_quantum_time_slots'] + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" # noqa E501 + self._wrapped_methods = { + self.create_quantum_program: self._wrap_method( + self.create_quantum_program, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_program: self._wrap_method( + self.get_quantum_program, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_programs: self._wrap_method( + self.list_quantum_programs, default_timeout=60.0, client_info=client_info + ), + self.delete_quantum_program: self._wrap_method( + self.delete_quantum_program, default_timeout=60.0, client_info=client_info + ), + self.update_quantum_program: self._wrap_method( + self.update_quantum_program, default_timeout=60.0, client_info=client_info + ), + self.create_quantum_job: self._wrap_method( + self.create_quantum_job, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_job: self._wrap_method( + self.get_quantum_job, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_jobs: self._wrap_method( + self.list_quantum_jobs, default_timeout=60.0, client_info=client_info + ), + self.delete_quantum_job: self._wrap_method( + self.delete_quantum_job, default_timeout=60.0, client_info=client_info + ), + self.update_quantum_job: self._wrap_method( + self.update_quantum_job, default_timeout=60.0, client_info=client_info + ), + self.cancel_quantum_job: self._wrap_method( + self.cancel_quantum_job, default_timeout=None, client_info=client_info + ), + self.list_quantum_job_events: self._wrap_method( + self.list_quantum_job_events, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_result: self._wrap_method( + self.get_quantum_result, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_processors: self._wrap_method( + self.list_quantum_processors, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_processor: self._wrap_method( + self.get_quantum_processor, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_processor_config: self._wrap_method( + self.get_quantum_processor_config, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_calibrations: self._wrap_method( + self.list_quantum_calibrations, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_calibration: self._wrap_method( + self.get_quantum_calibration, default_timeout=60.0, client_info=client_info + ), + self.create_quantum_reservation: self._wrap_method( + self.create_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.cancel_quantum_reservation: self._wrap_method( + self.cancel_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.delete_quantum_reservation: self._wrap_method( + self.delete_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_reservation: self._wrap_method( + self.get_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_reservations: self._wrap_method( + self.list_quantum_reservations, default_timeout=60.0, client_info=client_info + ), + self.update_quantum_reservation: self._wrap_method( + self.update_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.quantum_run_stream: self._wrap_method( + self.quantum_run_stream, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_reservation_grants: self._wrap_method( + self.list_quantum_reservation_grants, default_timeout=60.0, client_info=client_info + ), + self.reallocate_quantum_reservation_grant: self._wrap_method( + self.reallocate_quantum_reservation_grant, + default_timeout=60.0, + client_info=client_info, + ), + self.list_quantum_reservation_budgets: self._wrap_method( + self.list_quantum_reservation_budgets, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_time_slots: self._wrap_method( + self.list_quantum_time_slots, default_timeout=60.0, client_info=client_info + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" __all__ = ('QuantumEngineServiceGrpcAsyncIOTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest.py new file mode 100755 index 00000000000..44c8ebdbb79 --- /dev/null +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest.py @@ -0,0 +1,5438 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import importlib.util +import logging +from typing import Callable, Optional, Sequence + +import google.protobuf +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + rest_helpers, + rest_streaming, + retry as retries, +) +from google.auth import credentials as ga_credentials +from google.auth.transport.requests import AuthorizedSession +from google.protobuf import empty_pb2, json_format +from requests import __version__ as requests_version + +from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseQuantumEngineServiceRestTransport + +try: + OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault | None +except AttributeError: # pragma: NO COVER + OptionalRetry = retries.Retry | object | None # type: ignore + +CLIENT_LOGGING_SUPPORTED = importlib.util.find_spec("google.api_core.client_logging") is not None + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class QuantumEngineServiceRestInterceptor: + """Interceptor for QuantumEngineService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the QuantumEngineServiceRestTransport. + + .. code-block:: python + class MyCustomQuantumEngineServiceInterceptor(QuantumEngineServiceRestInterceptor): + def pre_cancel_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_cancel_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_cancel_quantum_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_quantum_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_quantum_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_quantum_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_quantum_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_quantum_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_quantum_calibration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_calibration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_processor_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_processor_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_result(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_result(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_calibrations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_calibrations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_job_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_job_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_jobs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_jobs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_processors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_processors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_programs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_programs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_reservation_budgets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_reservation_budgets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_reservation_grants(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_reservation_grants(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_reservations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_reservations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_time_slots(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_time_slots(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reallocate_quantum_reservation_grant(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_reallocate_quantum_reservation_grant(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_quantum_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_quantum_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_quantum_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_quantum_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + transport = QuantumEngineServiceRestTransport( + interceptor=MyCustomQuantumEngineServiceInterceptor() + ) + client = QuantumEngineServiceClient(transport=transport) + + + """ + + def pre_cancel_quantum_job( + self, request: engine.CancelQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.CancelQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for cancel_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def pre_cancel_quantum_reservation( + self, + request: engine.CancelQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.CancelQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for cancel_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_cancel_quantum_reservation( + self, response: quantum.QuantumReservation + ) -> quantum.QuantumReservation: + """Post-rpc interceptor for cancel_quantum_reservation + + DEPRECATED. Please use the `post_cancel_quantum_reservation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_cancel_quantum_reservation` interceptor runs + before the `post_cancel_quantum_reservation_with_metadata` interceptor. + """ + return response + + def post_cancel_quantum_reservation_with_metadata( + self, response: quantum.QuantumReservation, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservation, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for cancel_quantum_reservation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_cancel_quantum_reservation_with_metadata` + interceptor in new development instead of the `post_cancel_quantum_reservation` interceptor. + When both interceptors are used, this `post_cancel_quantum_reservation_with_metadata` + interceptor runs after the `post_cancel_quantum_reservation` interceptor. The (possibly + modified) response returned by `post_cancel_quantum_reservation` will be passed to + `post_cancel_quantum_reservation_with_metadata`. + """ + return response, metadata + + def pre_create_quantum_job( + self, request: engine.CreateQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.CreateQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for create_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_create_quantum_job(self, response: quantum.QuantumJob) -> quantum.QuantumJob: + """Post-rpc interceptor for create_quantum_job + + DEPRECATED. Please use the `post_create_quantum_job_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_create_quantum_job` interceptor runs + before the `post_create_quantum_job_with_metadata` interceptor. + """ + return response + + def post_create_quantum_job_with_metadata( + self, response: quantum.QuantumJob, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumJob, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for create_quantum_job + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_create_quantum_job_with_metadata` + interceptor in new development instead of the `post_create_quantum_job` interceptor. + When both interceptors are used, this `post_create_quantum_job_with_metadata` interceptor + runs after the `post_create_quantum_job` interceptor. The (possibly modified) response + returned by `post_create_quantum_job` will be passed to + `post_create_quantum_job_with_metadata`. + """ + return response, metadata + + def pre_create_quantum_program( + self, + request: engine.CreateQuantumProgramRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.CreateQuantumProgramRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for create_quantum_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_create_quantum_program( + self, response: quantum.QuantumProgram + ) -> quantum.QuantumProgram: + """Post-rpc interceptor for create_quantum_program + + DEPRECATED. Please use the `post_create_quantum_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_create_quantum_program` interceptor runs + before the `post_create_quantum_program_with_metadata` interceptor. + """ + return response + + def post_create_quantum_program_with_metadata( + self, response: quantum.QuantumProgram, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProgram, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for create_quantum_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_create_quantum_program_with_metadata` + interceptor in new development instead of the `post_create_quantum_program` interceptor. + When both interceptors are used, this `post_create_quantum_program_with_metadata` + interceptor runs after the `post_create_quantum_program` interceptor. The (possibly + modified) response returned by `post_create_quantum_program` will be passed to + `post_create_quantum_program_with_metadata`. + """ + return response, metadata + + def pre_create_quantum_reservation( + self, + request: engine.CreateQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.CreateQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for create_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_create_quantum_reservation( + self, response: quantum.QuantumReservation + ) -> quantum.QuantumReservation: + """Post-rpc interceptor for create_quantum_reservation + + DEPRECATED. Please use the `post_create_quantum_reservation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_create_quantum_reservation` interceptor runs + before the `post_create_quantum_reservation_with_metadata` interceptor. + """ + return response + + def post_create_quantum_reservation_with_metadata( + self, response: quantum.QuantumReservation, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservation, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for create_quantum_reservation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_create_quantum_reservation_with_metadata` + interceptor in new development instead of the `post_create_quantum_reservation` interceptor. + When both interceptors are used, this `post_create_quantum_reservation_with_metadata` + interceptor runs after the `post_create_quantum_reservation` interceptor. The (possibly + modified) response returned by `post_create_quantum_reservation` will be passed to + `post_create_quantum_reservation_with_metadata`. + """ + return response, metadata + + def pre_delete_quantum_job( + self, request: engine.DeleteQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.DeleteQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for delete_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def pre_delete_quantum_program( + self, + request: engine.DeleteQuantumProgramRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.DeleteQuantumProgramRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for delete_quantum_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def pre_delete_quantum_reservation( + self, + request: engine.DeleteQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.DeleteQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for delete_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def pre_get_quantum_calibration( + self, + request: engine.GetQuantumCalibrationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.GetQuantumCalibrationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_calibration + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_calibration( + self, response: quantum.QuantumCalibration + ) -> quantum.QuantumCalibration: + """Post-rpc interceptor for get_quantum_calibration + + DEPRECATED. Please use the `post_get_quantum_calibration_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_calibration` interceptor runs + before the `post_get_quantum_calibration_with_metadata` interceptor. + """ + return response + + def post_get_quantum_calibration_with_metadata( + self, response: quantum.QuantumCalibration, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumCalibration, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_calibration + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_calibration_with_metadata` + interceptor in new development instead of the `post_get_quantum_calibration` interceptor. + When both interceptors are used, this `post_get_quantum_calibration_with_metadata` + interceptor runs after the `post_get_quantum_calibration` interceptor. The (possibly + modified) response returned by `post_get_quantum_calibration` will be passed to + `post_get_quantum_calibration_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_job( + self, request: engine.GetQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.GetQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_job(self, response: quantum.QuantumJob) -> quantum.QuantumJob: + """Post-rpc interceptor for get_quantum_job + + DEPRECATED. Please use the `post_get_quantum_job_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_job` interceptor runs + before the `post_get_quantum_job_with_metadata` interceptor. + """ + return response + + def post_get_quantum_job_with_metadata( + self, response: quantum.QuantumJob, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumJob, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_job + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_job_with_metadata` + interceptor in new development instead of the `post_get_quantum_job` interceptor. + When both interceptors are used, this `post_get_quantum_job_with_metadata` interceptor runs + after the `post_get_quantum_job` interceptor. The (possibly modified) response returned by + `post_get_quantum_job` will be passed to `post_get_quantum_job_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_processor( + self, + request: engine.GetQuantumProcessorRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.GetQuantumProcessorRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_processor( + self, response: quantum.QuantumProcessor + ) -> quantum.QuantumProcessor: + """Post-rpc interceptor for get_quantum_processor + + DEPRECATED. Please use the `post_get_quantum_processor_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_processor` interceptor runs + before the `post_get_quantum_processor_with_metadata` interceptor. + """ + return response + + def post_get_quantum_processor_with_metadata( + self, response: quantum.QuantumProcessor, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProcessor, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_processor + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_processor_with_metadata` + interceptor in new development instead of the `post_get_quantum_processor` interceptor. + When both interceptors are used, this `post_get_quantum_processor_with_metadata` + interceptor runs after the `post_get_quantum_processor` interceptor. The (possibly + modified) response returned by `post_get_quantum_processor` will be passed to + `post_get_quantum_processor_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_processor_config( + self, + request: engine.GetQuantumProcessorConfigRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.GetQuantumProcessorConfigRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_processor_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_processor_config( + self, response: quantum.QuantumProcessorConfig + ) -> quantum.QuantumProcessorConfig: + """Post-rpc interceptor for get_quantum_processor_config + + DEPRECATED. Please use the `post_get_quantum_processor_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_processor_config` interceptor runs + before the `post_get_quantum_processor_config_with_metadata` interceptor. + """ + return response + + def post_get_quantum_processor_config_with_metadata( + self, response: quantum.QuantumProcessorConfig, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProcessorConfig, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_processor_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_processor_config_with_metadata` + interceptor in new development instead of the `post_get_quantum_processor_config` + interceptor. When both interceptors are used, this + `post_get_quantum_processor_config_with_metadata` interceptor runs after the + `post_get_quantum_processor_config` interceptor. The (possibly modified) response returned + by `post_get_quantum_processor_config` will be passed to + `post_get_quantum_processor_config_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_program( + self, request: engine.GetQuantumProgramRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.GetQuantumProgramRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_program(self, response: quantum.QuantumProgram) -> quantum.QuantumProgram: + """Post-rpc interceptor for get_quantum_program + + DEPRECATED. Please use the `post_get_quantum_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_program` interceptor runs + before the `post_get_quantum_program_with_metadata` interceptor. + """ + return response + + def post_get_quantum_program_with_metadata( + self, response: quantum.QuantumProgram, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProgram, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_program_with_metadata` + interceptor in new development instead of the `post_get_quantum_program` interceptor. + When both interceptors are used, this `post_get_quantum_program_with_metadata` interceptor + runs after the `post_get_quantum_program` interceptor. The (possibly modified) response + returned by `post_get_quantum_program` will be passed to + `post_get_quantum_program_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_reservation( + self, + request: engine.GetQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.GetQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_reservation( + self, response: quantum.QuantumReservation + ) -> quantum.QuantumReservation: + """Post-rpc interceptor for get_quantum_reservation + + DEPRECATED. Please use the `post_get_quantum_reservation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_reservation` interceptor runs + before the `post_get_quantum_reservation_with_metadata` interceptor. + """ + return response + + def post_get_quantum_reservation_with_metadata( + self, response: quantum.QuantumReservation, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservation, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_reservation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_reservation_with_metadata` + interceptor in new development instead of the `post_get_quantum_reservation` interceptor. + When both interceptors are used, this `post_get_quantum_reservation_with_metadata` + interceptor runs after the `post_get_quantum_reservation` interceptor. The (possibly + modified) response returned by `post_get_quantum_reservation` will be passed to + `post_get_quantum_reservation_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_result( + self, request: engine.GetQuantumResultRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.GetQuantumResultRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_result + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_result(self, response: quantum.QuantumResult) -> quantum.QuantumResult: + """Post-rpc interceptor for get_quantum_result + + DEPRECATED. Please use the `post_get_quantum_result_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_result` interceptor runs + before the `post_get_quantum_result_with_metadata` interceptor. + """ + return response + + def post_get_quantum_result_with_metadata( + self, response: quantum.QuantumResult, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumResult, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_result + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_result_with_metadata` + interceptor in new development instead of the `post_get_quantum_result` interceptor. + When both interceptors are used, this `post_get_quantum_result_with_metadata` interceptor + runs after the `post_get_quantum_result` interceptor. The (possibly modified) response + returned by `post_get_quantum_result` will be passed to + `post_get_quantum_result_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_calibrations( + self, + request: engine.ListQuantumCalibrationsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumCalibrationsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_calibrations + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_calibrations( + self, response: engine.ListQuantumCalibrationsResponse + ) -> engine.ListQuantumCalibrationsResponse: + """Post-rpc interceptor for list_quantum_calibrations + + DEPRECATED. Please use the `post_list_quantum_calibrations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_calibrations` interceptor runs + before the `post_list_quantum_calibrations_with_metadata` interceptor. + """ + return response + + def post_list_quantum_calibrations_with_metadata( + self, + response: engine.ListQuantumCalibrationsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumCalibrationsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_calibrations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_calibrations_with_metadata` + interceptor in new development instead of the `post_list_quantum_calibrations` interceptor. + When both interceptors are used, this `post_list_quantum_calibrations_with_metadata` + interceptor runs after the `post_list_quantum_calibrations` interceptor. The (possibly + modified) response returned by `post_list_quantum_calibrations` will be passed to + `post_list_quantum_calibrations_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_job_events( + self, + request: engine.ListQuantumJobEventsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumJobEventsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_job_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_job_events( + self, response: engine.ListQuantumJobEventsResponse + ) -> engine.ListQuantumJobEventsResponse: + """Post-rpc interceptor for list_quantum_job_events + + DEPRECATED. Please use the `post_list_quantum_job_events_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_job_events` interceptor runs + before the `post_list_quantum_job_events_with_metadata` interceptor. + """ + return response + + def post_list_quantum_job_events_with_metadata( + self, + response: engine.ListQuantumJobEventsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumJobEventsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_job_events + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_job_events_with_metadata` + interceptor in new development instead of the `post_list_quantum_job_events` interceptor. + When both interceptors are used, this `post_list_quantum_job_events_with_metadata` + interceptor runs after the `post_list_quantum_job_events` interceptor. The (possibly + modified) response returned by `post_list_quantum_job_events` will be passed to + `post_list_quantum_job_events_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_jobs( + self, request: engine.ListQuantumJobsRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.ListQuantumJobsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_jobs + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_jobs( + self, response: engine.ListQuantumJobsResponse + ) -> engine.ListQuantumJobsResponse: + """Post-rpc interceptor for list_quantum_jobs + + DEPRECATED. Please use the `post_list_quantum_jobs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_jobs` interceptor runs + before the `post_list_quantum_jobs_with_metadata` interceptor. + """ + return response + + def post_list_quantum_jobs_with_metadata( + self, response: engine.ListQuantumJobsResponse, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.ListQuantumJobsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_jobs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_jobs_with_metadata` + interceptor in new development instead of the `post_list_quantum_jobs` interceptor. + When both interceptors are used, this `post_list_quantum_jobs_with_metadata` interceptor + runs after the `post_list_quantum_jobs` interceptor. The (possibly modified) response + returned by `post_list_quantum_jobs` will be passed to + `post_list_quantum_jobs_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_processors( + self, + request: engine.ListQuantumProcessorsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumProcessorsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_processors + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_processors( + self, response: engine.ListQuantumProcessorsResponse + ) -> engine.ListQuantumProcessorsResponse: + """Post-rpc interceptor for list_quantum_processors + + DEPRECATED. Please use the `post_list_quantum_processors_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_processors` interceptor runs + before the `post_list_quantum_processors_with_metadata` interceptor. + """ + return response + + def post_list_quantum_processors_with_metadata( + self, + response: engine.ListQuantumProcessorsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumProcessorsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_processors + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_processors_with_metadata` + interceptor in new development instead of the `post_list_quantum_processors` interceptor. + When both interceptors are used, this `post_list_quantum_processors_with_metadata` + interceptor runs after the `post_list_quantum_processors` interceptor. The (possibly + modified) response returned by `post_list_quantum_processors` will be passed to + `post_list_quantum_processors_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_programs( + self, + request: engine.ListQuantumProgramsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumProgramsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_programs + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_programs( + self, response: engine.ListQuantumProgramsResponse + ) -> engine.ListQuantumProgramsResponse: + """Post-rpc interceptor for list_quantum_programs + + DEPRECATED. Please use the `post_list_quantum_programs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_programs` interceptor runs + before the `post_list_quantum_programs_with_metadata` interceptor. + """ + return response + + def post_list_quantum_programs_with_metadata( + self, + response: engine.ListQuantumProgramsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumProgramsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_programs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_programs_with_metadata` + interceptor in new development instead of the `post_list_quantum_programs` interceptor. + When both interceptors are used, this `post_list_quantum_programs_with_metadata` interceptor + runs after the `post_list_quantum_programs` interceptor. The (possibly modified) response + returned by `post_list_quantum_programs` will be passed to + `post_list_quantum_programs_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_reservation_budgets( + self, + request: engine.ListQuantumReservationBudgetsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationBudgetsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_reservation_budgets + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_reservation_budgets( + self, response: engine.ListQuantumReservationBudgetsResponse + ) -> engine.ListQuantumReservationBudgetsResponse: + """Post-rpc interceptor for list_quantum_reservation_budgets + + DEPRECATED. Please use the `post_list_quantum_reservation_budgets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_reservation_budgets` interceptor runs + before the `post_list_quantum_reservation_budgets_with_metadata` interceptor. + """ + return response + + def post_list_quantum_reservation_budgets_with_metadata( + self, + response: engine.ListQuantumReservationBudgetsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationBudgetsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_reservation_budgets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_reservation_budgets_with_metadata` + interceptor in new development instead of the `post_list_quantum_reservation_budgets` + interceptor. When both interceptors are used, this + `post_list_quantum_reservation_budgets_with_metadata` interceptor runs after the + `post_list_quantum_reservation_budgets` interceptor. The (possibly modified) response + returned by `post_list_quantum_reservation_budgets` will be passed to + `post_list_quantum_reservation_budgets_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_reservation_grants( + self, + request: engine.ListQuantumReservationGrantsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationGrantsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_reservation_grants + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_reservation_grants( + self, response: engine.ListQuantumReservationGrantsResponse + ) -> engine.ListQuantumReservationGrantsResponse: + """Post-rpc interceptor for list_quantum_reservation_grants + + DEPRECATED. Please use the `post_list_quantum_reservation_grants_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_reservation_grants` interceptor runs + before the `post_list_quantum_reservation_grants_with_metadata` interceptor. + """ + return response + + def post_list_quantum_reservation_grants_with_metadata( + self, + response: engine.ListQuantumReservationGrantsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationGrantsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_reservation_grants + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_reservation_grants_with_metadata` + interceptor in new development instead of the `post_list_quantum_reservation_grants` + interceptor. When both interceptors are used, this + `post_list_quantum_reservation_grants_with_metadata` interceptor runs after the + `post_list_quantum_reservation_grants` interceptor. The (possibly modified) response + returned by `post_list_quantum_reservation_grants` will be passed to + `post_list_quantum_reservation_grants_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_reservations( + self, + request: engine.ListQuantumReservationsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_reservations + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_reservations( + self, response: engine.ListQuantumReservationsResponse + ) -> engine.ListQuantumReservationsResponse: + """Post-rpc interceptor for list_quantum_reservations + + DEPRECATED. Please use the `post_list_quantum_reservations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_reservations` interceptor runs + before the `post_list_quantum_reservations_with_metadata` interceptor. + """ + return response + + def post_list_quantum_reservations_with_metadata( + self, + response: engine.ListQuantumReservationsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_reservations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_reservations_with_metadata` + interceptor in new development instead of the `post_list_quantum_reservations` interceptor. + When both interceptors are used, this `post_list_quantum_reservations_with_metadata` + interceptor runs after the `post_list_quantum_reservations` interceptor. The (possibly + modified) response returned by `post_list_quantum_reservations` will be passed to + `post_list_quantum_reservations_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_time_slots( + self, + request: engine.ListQuantumTimeSlotsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumTimeSlotsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_time_slots + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_time_slots( + self, response: engine.ListQuantumTimeSlotsResponse + ) -> engine.ListQuantumTimeSlotsResponse: + """Post-rpc interceptor for list_quantum_time_slots + + DEPRECATED. Please use the `post_list_quantum_time_slots_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_time_slots` interceptor runs + before the `post_list_quantum_time_slots_with_metadata` interceptor. + """ + return response + + def post_list_quantum_time_slots_with_metadata( + self, + response: engine.ListQuantumTimeSlotsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumTimeSlotsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_time_slots + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_time_slots_with_metadata` + interceptor in new development instead of the `post_list_quantum_time_slots` interceptor. + When both interceptors are used, this `post_list_quantum_time_slots_with_metadata` + interceptor runs after the `post_list_quantum_time_slots` interceptor. The (possibly + modified) response returned by `post_list_quantum_time_slots` will be passed to + `post_list_quantum_time_slots_with_metadata`. + """ + return response, metadata + + def pre_reallocate_quantum_reservation_grant( + self, + request: engine.ReallocateQuantumReservationGrantRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ReallocateQuantumReservationGrantRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for reallocate_quantum_reservation_grant + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_reallocate_quantum_reservation_grant( + self, response: quantum.QuantumReservationGrant + ) -> quantum.QuantumReservationGrant: + """Post-rpc interceptor for reallocate_quantum_reservation_grant + + DEPRECATED. Please use the `post_reallocate_quantum_reservation_grant_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_reallocate_quantum_reservation_grant` interceptor + runs before the `post_reallocate_quantum_reservation_grant_with_metadata` interceptor. + """ + return response + + def post_reallocate_quantum_reservation_grant_with_metadata( + self, response: quantum.QuantumReservationGrant, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservationGrant, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for reallocate_quantum_reservation_grant + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_reallocate_quantum_reservation_grant_with_metadata` + interceptor in new development instead of the `post_reallocate_quantum_reservation_grant` + interceptor. When both interceptors are used, this + `post_reallocate_quantum_reservation_grant_with_metadata` interceptor runs after the + `post_reallocate_quantum_reservation_grant` interceptor. The (possibly modified) response + returned by `post_reallocate_quantum_reservation_grant` will be passed to + `post_reallocate_quantum_reservation_grant_with_metadata`. + """ + return response, metadata + + def pre_update_quantum_job( + self, request: engine.UpdateQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.UpdateQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for update_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_update_quantum_job(self, response: quantum.QuantumJob) -> quantum.QuantumJob: + """Post-rpc interceptor for update_quantum_job + + DEPRECATED. Please use the `post_update_quantum_job_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_update_quantum_job` interceptor runs + before the `post_update_quantum_job_with_metadata` interceptor. + """ + return response + + def post_update_quantum_job_with_metadata( + self, response: quantum.QuantumJob, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumJob, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for update_quantum_job + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_update_quantum_job_with_metadata` + interceptor in new development instead of the `post_update_quantum_job` interceptor. + When both interceptors are used, this `post_update_quantum_job_with_metadata` interceptor + runs after the `post_update_quantum_job` interceptor. The (possibly modified) response + returned by `post_update_quantum_job` will be passed to + `post_update_quantum_job_with_metadata`. + """ + return response, metadata + + def pre_update_quantum_program( + self, + request: engine.UpdateQuantumProgramRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.UpdateQuantumProgramRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for update_quantum_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_update_quantum_program( + self, response: quantum.QuantumProgram + ) -> quantum.QuantumProgram: + """Post-rpc interceptor for update_quantum_program + + DEPRECATED. Please use the `post_update_quantum_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_update_quantum_program` interceptor runs + before the `post_update_quantum_program_with_metadata` interceptor. + """ + return response + + def post_update_quantum_program_with_metadata( + self, response: quantum.QuantumProgram, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProgram, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for update_quantum_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_update_quantum_program_with_metadata` + interceptor in new development instead of the `post_update_quantum_program` interceptor. + When both interceptors are used, this `post_update_quantum_program_with_metadata` + interceptor runs after the `post_update_quantum_program` interceptor. The (possibly + modified) response returned by `post_update_quantum_program` will be passed to + `post_update_quantum_program_with_metadata`. + """ + return response, metadata + + def pre_update_quantum_reservation( + self, + request: engine.UpdateQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.UpdateQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for update_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_update_quantum_reservation( + self, response: quantum.QuantumReservation + ) -> quantum.QuantumReservation: + """Post-rpc interceptor for update_quantum_reservation + + DEPRECATED. Please use the `post_update_quantum_reservation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_update_quantum_reservation` interceptor runs + before the `post_update_quantum_reservation_with_metadata` interceptor. + """ + return response + + def post_update_quantum_reservation_with_metadata( + self, response: quantum.QuantumReservation, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservation, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for update_quantum_reservation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_update_quantum_reservation_with_metadata` + interceptor in new development instead of the `post_update_quantum_reservation` interceptor. + When both interceptors are used, this `post_update_quantum_reservation_with_metadata` + interceptor runs after the `post_update_quantum_reservation` interceptor. The (possibly + modified) response returned by `post_update_quantum_reservation` will be passed to + `post_update_quantum_reservation_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class QuantumEngineServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: QuantumEngineServiceRestInterceptor + + +class QuantumEngineServiceRestTransport(_BaseQuantumEngineServiceRestTransport): + """REST backend synchronous transport for QuantumEngineService. + + - + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = 'quantum.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[QuantumEngineServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'quantum.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession(self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or QuantumEngineServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CancelQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CancelQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CancelQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ): + r"""Call the cancel quantum job method over HTTP. + + Args: + request (~.engine.CancelQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_quantum_job(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = ( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CancelQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CancelQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CancelQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _CancelQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CancelQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CancelQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservation: + r"""Call the cancel quantum + reservation method over HTTP. + + Args: + request (~.engine.CancelQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservation: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation._get_request_body_json( # noqa E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation._get_query_params_json( # noqa E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CancelQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CancelQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CancelQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservation() + pb_resp = quantum.QuantumReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_cancel_quantum_reservation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_cancel_quantum_reservation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.cancel_quantum_reservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CancelQuantumReservation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CreateQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CreateQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumJob: + r"""Call the create quantum job method over HTTP. + + Args: + request (~.engine.CreateQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumJob: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_quantum_job(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CreateQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CreateQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumJob() + pb_resp = quantum.QuantumJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_quantum_job(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_quantum_job_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumJob.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.create_quantum_job" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumJob", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateQuantumProgram( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CreateQuantumProgram") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CreateQuantumProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProgram: + r"""Call the create quantum program method over HTTP. + + Args: + request (~.engine.CreateQuantumProgramRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProgram: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_quantum_program(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram._get_request_body_json( # noqa E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram._get_query_params_json( # noqa E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CreateQuantumProgram" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CreateQuantumProgram._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProgram() + pb_resp = quantum.QuantumProgram.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_quantum_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_quantum_program_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProgram.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.create_quantum_program", + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CreateQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CreateQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservation: + r"""Call the create quantum + reservation method over HTTP. + + Args: + request (~.engine.CreateQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservation: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation._get_request_body_json( # noqa E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation._get_query_params_json( # noqa E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CreateQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CreateQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservation() + pb_resp = quantum.QuantumReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_quantum_reservation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_quantum_reservation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.create_quantum_reservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumReservation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.DeleteQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.DeleteQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ): + r"""Call the delete quantum job method over HTTP. + + Args: + request (~.engine.DeleteQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_quantum_job(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumJob._get_transcoded_request( # noqa E501 + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.DeleteQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "DeleteQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._DeleteQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteQuantumProgram( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumProgram, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.DeleteQuantumProgram") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.DeleteQuantumProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ): + r"""Call the delete quantum program method over HTTP. + + Args: + request (~.engine.DeleteQuantumProgramRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumProgram._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_quantum_program(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumProgram._get_transcoded_request( # noqa E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumProgram._get_query_params_json( # noqa E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.DeleteQuantumProgram" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "DeleteQuantumProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._DeleteQuantumProgram._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.DeleteQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.DeleteQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ): + r"""Call the delete quantum + reservation method over HTTP. + + Args: + request (~.engine.DeleteQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumReservation._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumReservation._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.DeleteQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "DeleteQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._DeleteQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetQuantumCalibration( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumCalibration, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumCalibration") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumCalibrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumCalibration: + r"""Call the get quantum calibration method over HTTP. + + Args: + request (~.engine.GetQuantumCalibrationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumCalibration: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumCalibration._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_calibration(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumCalibration._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumCalibration._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumCalibration" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumCalibration", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumCalibration._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumCalibration() + pb_resp = quantum.QuantumCalibration.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_calibration(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_calibration_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumCalibration.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_calibration" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumCalibration", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumJob: + r"""Call the get quantum job method over HTTP. + + Args: + request (~.engine.GetQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumJob: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_job(request, metadata) + transcoded_request = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumJob._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumJob() + pb_resp = quantum.QuantumJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_job(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_job_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumJob.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_job" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumJob", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumProcessor( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessor, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumProcessor") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumProcessorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProcessor: + r"""Call the get quantum processor method over HTTP. + + Args: + request (~.engine.GetQuantumProcessorRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProcessor: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessor._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_processor(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessor._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessor._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumProcessor" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProcessor", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumProcessor._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProcessor() + pb_resp = quantum.QuantumProcessor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_processor(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_processor_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProcessor.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_processor" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProcessor", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumProcessorConfig( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumProcessorConfig") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumProcessorConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProcessorConfig: + r"""Call the get quantum processor + config method over HTTP. + + Args: + request (~.engine.GetQuantumProcessorConfigRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProcessorConfig: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_processor_config( + request, metadata + ) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumProcessorConfig" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProcessorConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumProcessorConfig._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProcessorConfig() + pb_resp = quantum.QuantumProcessorConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_processor_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_processor_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProcessorConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_processor_config" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProcessorConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumProgram( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProgram, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumProgram") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProgram: + r"""Call the get quantum program method over HTTP. + + Args: + request (~.engine.GetQuantumProgramRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProgram: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProgram._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_program(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProgram._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProgram._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumProgram" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumProgram._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProgram() + pb_resp = quantum.QuantumProgram.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_program_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProgram.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_program" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservation: + r"""Call the get quantum reservation method over HTTP. + + Args: + request (~.engine.GetQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservation: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumReservation._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumReservation._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservation() + pb_resp = quantum.QuantumReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_reservation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_reservation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_reservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumReservation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumResult( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumResult, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumResult") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumResultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumResult: + r"""Call the get quantum result method over HTTP. + + Args: + request (~.engine.GetQuantumResultRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumResult: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumResult._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_result(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumResult._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumResult._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumResult" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumResult", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumResult._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumResult() + pb_resp = quantum.QuantumResult.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_result(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_result_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumResult.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_result" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumResult", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumCalibrations( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumCalibrations, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumCalibrations") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumCalibrationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumCalibrationsResponse: + r"""Call the list quantum calibrations method over HTTP. + + Args: + request (~.engine.ListQuantumCalibrationsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumCalibrationsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumCalibrations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_calibrations(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumCalibrations._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumCalibrations._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumCalibrations" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumCalibrations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumCalibrations._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumCalibrationsResponse() + pb_resp = engine.ListQuantumCalibrationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_calibrations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_calibrations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumCalibrationsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_calibrations" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumCalibrations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumJobEvents( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobEvents, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumJobEvents") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumJobEventsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumJobEventsResponse: + r"""Call the list quantum job events method over HTTP. + + Args: + request (~.engine.ListQuantumJobEventsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumJobEventsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobEvents._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_job_events(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobEvents._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobEvents._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumJobEvents" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumJobEvents", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumJobEvents._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumJobEventsResponse() + pb_resp = engine.ListQuantumJobEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_job_events(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_job_events_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumJobEventsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_job_events" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumJobEvents", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumJobs( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobs, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumJobs") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumJobsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumJobsResponse: + r"""Call the list quantum jobs method over HTTP. + + Args: + request (~.engine.ListQuantumJobsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumJobsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobs._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_jobs(request, metadata) + transcoded_request = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobs._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobs._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumJobs" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumJobs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumJobs._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumJobsResponse() + pb_resp = engine.ListQuantumJobsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_jobs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_jobs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumJobsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_jobs" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumJobs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumProcessors( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumProcessors, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumProcessors") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumProcessorsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumProcessorsResponse: + r"""Call the list quantum processors method over HTTP. + + Args: + request (~.engine.ListQuantumProcessorsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumProcessorsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumProcessors._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_processors(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumProcessors._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumProcessors._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumProcessors" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumProcessors", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumProcessors._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumProcessorsResponse() + pb_resp = engine.ListQuantumProcessorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_processors(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_processors_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumProcessorsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_processors" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumProcessors", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumPrograms( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumPrograms, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumPrograms") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumProgramsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumProgramsResponse: + r"""Call the list quantum programs method over HTTP. + + Args: + request (~.engine.ListQuantumProgramsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumProgramsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumPrograms._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_programs(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumPrograms._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumPrograms._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumPrograms" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumPrograms", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumPrograms._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumProgramsResponse() + pb_resp = engine.ListQuantumProgramsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_programs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_programs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumProgramsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_programs" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumPrograms", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumReservationBudgets( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationBudgets, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumReservationBudgets") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumReservationBudgetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumReservationBudgetsResponse: + r"""Call the list quantum reservation + budgets method over HTTP. + + Args: + request (~.engine.ListQuantumReservationBudgetsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumReservationBudgetsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationBudgets._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_reservation_budgets( + request, metadata + ) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationBudgets._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationBudgets._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumReservationBudgets" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservationBudgets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + QuantumEngineServiceRestTransport._ListQuantumReservationBudgets._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumReservationBudgetsResponse() + pb_resp = engine.ListQuantumReservationBudgetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_reservation_budgets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_reservation_budgets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumReservationBudgetsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_reservation_budgets" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservationBudgets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumReservationGrants( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationGrants, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumReservationGrants") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumReservationGrantsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumReservationGrantsResponse: + r"""Call the list quantum reservation + grants method over HTTP. + + Args: + request (~.engine.ListQuantumReservationGrantsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumReservationGrantsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationGrants._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_reservation_grants( + request, metadata + ) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationGrants._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationGrants._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumReservationGrants" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservationGrants", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + QuantumEngineServiceRestTransport._ListQuantumReservationGrants._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumReservationGrantsResponse() + pb_resp = engine.ListQuantumReservationGrantsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_reservation_grants(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_reservation_grants_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumReservationGrantsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_reservation_grants" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservationGrants", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumReservations( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservations, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumReservations") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumReservationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumReservationsResponse: + r"""Call the list quantum reservations method over HTTP. + + Args: + request (~.engine.ListQuantumReservationsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumReservationsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_reservations(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservations._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservations._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumReservations" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumReservations._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumReservationsResponse() + pb_resp = engine.ListQuantumReservationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_reservations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_reservations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumReservationsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_reservations" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumTimeSlots( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumTimeSlots, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumTimeSlots") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumTimeSlotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumTimeSlotsResponse: + r"""Call the list quantum time slots method over HTTP. + + Args: + request (~.engine.ListQuantumTimeSlotsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumTimeSlotsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumTimeSlots._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_time_slots(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumTimeSlots._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumTimeSlots._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumTimeSlots" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumTimeSlots", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumTimeSlots._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumTimeSlotsResponse() + pb_resp = engine.ListQuantumTimeSlotsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_time_slots(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_time_slots_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumTimeSlotsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_time_slots" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumTimeSlots", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _QuantumRunStream( + _BaseQuantumEngineServiceRestTransport._BaseQuantumRunStream, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.QuantumRunStream") + + def __call__( + self, + request: engine.QuantumRunStreamRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method QuantumRunStream is not available over REST transport" + ) + + class _ReallocateQuantumReservationGrant( + _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ReallocateQuantumReservationGrant") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.ReallocateQuantumReservationGrantRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservationGrant: + r"""Call the reallocate quantum + reservation grant method over HTTP. + + Args: + request (~.engine.ReallocateQuantumReservationGrantRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservationGrant: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant._get_http_options() + ) + + request, metadata = self._interceptor.pre_reallocate_quantum_reservation_grant( + request, metadata + ) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant._get_transcoded_request( # noqa: E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant._get_request_body_json( # noqa: E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ReallocateQuantumReservationGrant" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ReallocateQuantumReservationGrant", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + QuantumEngineServiceRestTransport._ReallocateQuantumReservationGrant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservationGrant() + pb_resp = quantum.QuantumReservationGrant.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_reallocate_quantum_reservation_grant(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_reallocate_quantum_reservation_grant_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservationGrant.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.reallocate_quantum_reservation_grant" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ReallocateQuantumReservationGrant", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.UpdateQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.UpdateQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumJob: + r"""Call the update quantum job method over HTTP. + + Args: + request (~.engine.UpdateQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumJob: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_quantum_job(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob._get_transcoded_request( # noqa: E501 + http_options, request + ) + + body = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.UpdateQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._UpdateQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumJob() + pb_resp = quantum.QuantumJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_quantum_job(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_quantum_job_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumJob.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.update_quantum_job" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumJob", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateQuantumProgram( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.UpdateQuantumProgram") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.UpdateQuantumProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProgram: + r"""Call the update quantum program method over HTTP. + + Args: + request (~.engine.UpdateQuantumProgramRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProgram: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_quantum_program(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram._get_transcoded_request( # noqa: E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram._get_request_body_json( # noqa: E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.UpdateQuantumProgram" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._UpdateQuantumProgram._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProgram() + pb_resp = quantum.QuantumProgram.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_quantum_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_quantum_program_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProgram.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.update_quantum_program" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.UpdateQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.UpdateQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservation: + r"""Call the update quantum + reservation method over HTTP. + + Args: + request (~.engine.UpdateQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservation: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation._get_transcoded_request( # noqa: E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation._get_request_body_json( # noqa: E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.UpdateQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._UpdateQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservation() + pb_resp = quantum.QuantumReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_quantum_reservation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_quantum_reservation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.update_quantum_reservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumReservation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def cancel_quantum_job(self) -> Callable[[engine.CancelQuantumJobRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CancelQuantumJob(self._session, self._host, self._interceptor) + + @property + def cancel_quantum_reservation( + self, + ) -> Callable[[engine.CancelQuantumReservationRequest], quantum.QuantumReservation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CancelQuantumReservation(self._session, self._host, self._interceptor) + + @property + def create_quantum_job(self) -> Callable[[engine.CreateQuantumJobRequest], quantum.QuantumJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CreateQuantumJob(self._session, self._host, self._interceptor) + + @property + def create_quantum_program( + self, + ) -> Callable[[engine.CreateQuantumProgramRequest], quantum.QuantumProgram]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CreateQuantumProgram(self._session, self._host, self._interceptor) + + @property + def create_quantum_reservation( + self, + ) -> Callable[[engine.CreateQuantumReservationRequest], quantum.QuantumReservation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CreateQuantumReservation(self._session, self._host, self._interceptor) + + @property + def delete_quantum_job(self) -> Callable[[engine.DeleteQuantumJobRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._DeleteQuantumJob(self._session, self._host, self._interceptor) + + @property + def delete_quantum_program( + self, + ) -> Callable[[engine.DeleteQuantumProgramRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._DeleteQuantumProgram(self._session, self._host, self._interceptor) + + @property + def delete_quantum_reservation( + self, + ) -> Callable[[engine.DeleteQuantumReservationRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._DeleteQuantumReservation(self._session, self._host, self._interceptor) + + @property + def get_quantum_calibration( + self, + ) -> Callable[[engine.GetQuantumCalibrationRequest], quantum.QuantumCalibration]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumCalibration(self._session, self._host, self._interceptor) + + @property + def get_quantum_job(self) -> Callable[[engine.GetQuantumJobRequest], quantum.QuantumJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumJob(self._session, self._host, self._interceptor) + + @property + def get_quantum_processor( + self, + ) -> Callable[[engine.GetQuantumProcessorRequest], quantum.QuantumProcessor]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumProcessor(self._session, self._host, self._interceptor) + + @property + def get_quantum_processor_config( + self, + ) -> Callable[[engine.GetQuantumProcessorConfigRequest], quantum.QuantumProcessorConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumProcessorConfig(self._session, self._host, self._interceptor) + + @property + def get_quantum_program( + self, + ) -> Callable[[engine.GetQuantumProgramRequest], quantum.QuantumProgram]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumProgram(self._session, self._host, self._interceptor) + + @property + def get_quantum_reservation( + self, + ) -> Callable[[engine.GetQuantumReservationRequest], quantum.QuantumReservation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumReservation(self._session, self._host, self._interceptor) + + @property + def get_quantum_result( + self, + ) -> Callable[[engine.GetQuantumResultRequest], quantum.QuantumResult]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumResult(self._session, self._host, self._interceptor) + + @property + def list_quantum_calibrations( + self, + ) -> Callable[[engine.ListQuantumCalibrationsRequest], engine.ListQuantumCalibrationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumCalibrations(self._session, self._host, self._interceptor) + + @property + def list_quantum_job_events( + self, + ) -> Callable[[engine.ListQuantumJobEventsRequest], engine.ListQuantumJobEventsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumJobEvents(self._session, self._host, self._interceptor) + + @property + def list_quantum_jobs( + self, + ) -> Callable[[engine.ListQuantumJobsRequest], engine.ListQuantumJobsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumJobs(self._session, self._host, self._interceptor) + + @property + def list_quantum_processors( + self, + ) -> Callable[[engine.ListQuantumProcessorsRequest], engine.ListQuantumProcessorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumProcessors(self._session, self._host, self._interceptor) + + @property + def list_quantum_programs( + self, + ) -> Callable[[engine.ListQuantumProgramsRequest], engine.ListQuantumProgramsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumPrograms(self._session, self._host, self._interceptor) + + @property + def list_quantum_reservation_budgets( + self, + ) -> Callable[ + [engine.ListQuantumReservationBudgetsRequest], engine.ListQuantumReservationBudgetsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumReservationBudgets(self._session, self._host, self._interceptor) + + @property + def list_quantum_reservation_grants( + self, + ) -> Callable[ + [engine.ListQuantumReservationGrantsRequest], engine.ListQuantumReservationGrantsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumReservationGrants(self._session, self._host, self._interceptor) + + @property + def list_quantum_reservations( + self, + ) -> Callable[[engine.ListQuantumReservationsRequest], engine.ListQuantumReservationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumReservations(self._session, self._host, self._interceptor) + + @property + def list_quantum_time_slots( + self, + ) -> Callable[[engine.ListQuantumTimeSlotsRequest], engine.ListQuantumTimeSlotsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumTimeSlots(self._session, self._host, self._interceptor) + + @property + def quantum_run_stream( + self, + ) -> Callable[[engine.QuantumRunStreamRequest], engine.QuantumRunStreamResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._QuantumRunStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def reallocate_quantum_reservation_grant( + self, + ) -> Callable[ + [engine.ReallocateQuantumReservationGrantRequest], quantum.QuantumReservationGrant + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ReallocateQuantumReservationGrant(self._session, self._host, self._interceptor) + + @property + def update_quantum_job(self) -> Callable[[engine.UpdateQuantumJobRequest], quantum.QuantumJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._UpdateQuantumJob(self._session, self._host, self._interceptor) + + @property + def update_quantum_program( + self, + ) -> Callable[[engine.UpdateQuantumProgramRequest], quantum.QuantumProgram]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._UpdateQuantumProgram(self._session, self._host, self._interceptor) + + @property + def update_quantum_reservation( + self, + ) -> Callable[[engine.UpdateQuantumReservationRequest], quantum.QuantumReservation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._UpdateQuantumReservation(self._session, self._host, self._interceptor) + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ('QuantumEngineServiceRestTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest_base.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest_base.py new file mode 100755 index 00000000000..907ac527d5b --- /dev/null +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest_base.py @@ -0,0 +1,1019 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import re +from typing import Any, Optional + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from cirq_google.cloud.quantum_v1alpha1.types import engine + +from .base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport + + +class _BaseQuantumEngineServiceRestTransport(QuantumEngineServiceTransport): + """Base REST backend transport for QuantumEngineService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = 'quantum.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'quantum.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCancelQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/programs/*/jobs/*}:cancel', + 'body': '*', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CancelQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/processors/*/reservations/*}:cancel', + 'body': '*', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CancelQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/programs/*}/jobs', + 'body': 'quantum_job', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CreateQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateQuantumProgram: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*}/programs', + 'body': 'quantum_program', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CreateQuantumProgramRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/processors/*}/reservations', + 'body': 'quantum_reservation', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CreateQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'delete', 'uri': '/v1alpha1/{name=projects/*/programs/*/jobs/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.DeleteQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteQuantumProgram: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'delete', 'uri': '/v1alpha1/{name=projects/*/programs/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.DeleteQuantumProgramRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/processors/*/reservations/*}', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.DeleteQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumCalibration: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/processors/*/calibrations/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumCalibrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/programs/*/jobs/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumProcessor: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/processors/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumProcessorConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/processors/*/configSnapshots/*/configs/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/processors/*/configAutomationRuns/*/configs/*}', # noqa E501 + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumProcessorConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + query_params.update( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumProgram: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/programs/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumProgramRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/processors/*/reservations/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumResult: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/programs/*/jobs/*}/result'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumResultRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumCalibrations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/processors/*}/calibrations'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumCalibrationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumJobEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/programs/*/jobs/*}/events'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumJobEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumJobs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/programs/*}/jobs'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumJobsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumProcessors: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*}/processors'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumProcessorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumPrograms: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*}/programs'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumProgramsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumReservationBudgets: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*}/reservationBudgets'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumReservationBudgetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumReservationGrants: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*}/reservationGrant'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumReservationGrantsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumReservations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/processors/*}/reservations'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumReservationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumTimeSlots: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/processors/*}/timeSlots'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumTimeSlotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseQuantumRunStream: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseReallocateQuantumReservationGrant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/reservationGrant/*}:reallocate', + 'body': '*', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ReallocateQuantumReservationGrantRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'patch', + 'uri': '/v1alpha1/{name=projects/*/programs/*/jobs/*}', + 'body': 'quantum_job', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.UpdateQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateQuantumProgram: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'patch', + 'uri': '/v1alpha1/{name=projects/*/programs/*}', + 'body': 'quantum_program', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.UpdateQuantumProgramRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options() -> list[dict[str, str]]: + http_options: list[dict[str, str]] = [ + { + 'method': 'patch', + 'uri': '/v1alpha1/{name=projects/*/processors/*/reservations/*}', + 'body': 'quantum_reservation', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.UpdateQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ('_BaseQuantumEngineServiceRestTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/__init__.py index d298e09478b..22bdca165e4 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ DeleteQuantumReservationRequest, GetQuantumCalibrationRequest, GetQuantumJobRequest, + GetQuantumProcessorConfigRequest, GetQuantumProcessorRequest, GetQuantumProgramRequest, GetQuantumReservationRequest, @@ -66,6 +67,7 @@ QuantumJob, QuantumJobEvent, QuantumProcessor, + QuantumProcessorConfig, QuantumProgram, QuantumReservation, QuantumReservationBudget, @@ -87,6 +89,7 @@ 'DeleteQuantumReservationRequest', 'GetQuantumCalibrationRequest', 'GetQuantumJobRequest', + 'GetQuantumProcessorConfigRequest', 'GetQuantumProcessorRequest', 'GetQuantumProgramRequest', 'GetQuantumReservationRequest', @@ -116,6 +119,7 @@ 'UpdateQuantumJobRequest', 'UpdateQuantumProgramRequest', 'UpdateQuantumReservationRequest', + 'DeviceConfigKey', 'DeviceConfigSelector', 'ExecutionStatus', 'GcsLocation', @@ -125,6 +129,7 @@ 'QuantumJob', 'QuantumJobEvent', 'QuantumProcessor', + 'QuantumProcessorConfig', 'QuantumProgram', 'QuantumReservation', 'QuantumReservationBudget', @@ -132,5 +137,4 @@ 'QuantumResult', 'QuantumTimeSlot', 'SchedulingConfig', - 'DeviceConfigKey', ) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/engine.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/engine.py index 91a316e16cf..a289e296ffc 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/engine.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/engine.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,11 +12,11 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -# ruff: noqa: E501 - +# from __future__ import annotations +from typing import MutableSequence + import proto from google.protobuf import duration_pb2, field_mask_pb2 @@ -44,6 +44,7 @@ 'ListQuantumProcessorsRequest', 'ListQuantumProcessorsResponse', 'GetQuantumProcessorRequest', + 'GetQuantumProcessorConfigRequest', 'ListQuantumCalibrationsRequest', 'ListQuantumCalibrationsResponse', 'GetQuantumCalibrationRequest', @@ -75,15 +76,17 @@ class CreateQuantumJobRequest(proto.Message): Attributes: parent (str): - - quantum_job (google.cloud.quantum_v1alpha1.types.QuantumJob): + quantum_job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - overwrite_existing_run_context (bool): - """ - parent = proto.Field(proto.STRING, number=1) - quantum_job = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumJob) - overwrite_existing_run_context = proto.Field(proto.BOOL, number=3) + parent: str = proto.Field(proto.STRING, number=1) + quantum_job: quantum.QuantumJob = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumJob + ) + overwrite_existing_run_context: bool = proto.Field(proto.BOOL, number=3) class GetQuantumJobRequest(proto.Message): @@ -96,8 +99,8 @@ class GetQuantumJobRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - return_run_context = proto.Field(proto.BOOL, number=2) + name: str = proto.Field(proto.STRING, number=1) + return_run_context: bool = proto.Field(proto.BOOL, number=2) class ListQuantumJobsRequest(proto.Message): @@ -114,17 +117,17 @@ class ListQuantumJobsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumJobsResponse(proto.Message): r"""- Attributes: - jobs (Sequence[google.cloud.quantum_v1alpha1.types.QuantumJob]): + jobs (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumJob]): - next_page_token (str): - @@ -134,8 +137,10 @@ class ListQuantumJobsResponse(proto.Message): def raw_page(self): return self - jobs = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumJob) - next_page_token = proto.Field(proto.STRING, number=2) + jobs: MutableSequence[quantum.QuantumJob] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumJob + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class DeleteQuantumJobRequest(proto.Message): @@ -146,7 +151,7 @@ class DeleteQuantumJobRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class UpdateQuantumJobRequest(proto.Message): @@ -155,15 +160,19 @@ class UpdateQuantumJobRequest(proto.Message): Attributes: name (str): - - quantum_job (google.cloud.quantum_v1alpha1.types.QuantumJob): + quantum_job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - update_mask (google.protobuf.field_mask_pb2.FieldMask): - """ - name = proto.Field(proto.STRING, number=1) - quantum_job = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumJob) - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask) + name: str = proto.Field(proto.STRING, number=1) + quantum_job: quantum.QuantumJob = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumJob + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask + ) class CancelQuantumJobRequest(proto.Message): @@ -174,7 +183,7 @@ class CancelQuantumJobRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class ListQuantumJobEventsRequest(proto.Message): @@ -189,16 +198,16 @@ class ListQuantumJobEventsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) class ListQuantumJobEventsResponse(proto.Message): r"""- Attributes: - events (Sequence[google.cloud.quantum_v1alpha1.types.QuantumJobEvent]): + events (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumJobEvent]): - next_page_token (str): - @@ -208,8 +217,10 @@ class ListQuantumJobEventsResponse(proto.Message): def raw_page(self): return self - events = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumJobEvent) - next_page_token = proto.Field(proto.STRING, number=2) + events: MutableSequence[quantum.QuantumJobEvent] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumJobEvent + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class GetQuantumResultRequest(proto.Message): @@ -220,7 +231,7 @@ class GetQuantumResultRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) + parent: str = proto.Field(proto.STRING, number=1) class CreateQuantumProgramRequest(proto.Message): @@ -229,15 +240,17 @@ class CreateQuantumProgramRequest(proto.Message): Attributes: parent (str): - - quantum_program (google.cloud.quantum_v1alpha1.types.QuantumProgram): + quantum_program (cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram): - overwrite_existing_source_code (bool): - """ - parent = proto.Field(proto.STRING, number=1) - quantum_program = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumProgram) - overwrite_existing_source_code = proto.Field(proto.BOOL, number=3) + parent: str = proto.Field(proto.STRING, number=1) + quantum_program: quantum.QuantumProgram = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumProgram + ) + overwrite_existing_source_code: bool = proto.Field(proto.BOOL, number=3) class GetQuantumProgramRequest(proto.Message): @@ -250,8 +263,8 @@ class GetQuantumProgramRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - return_code = proto.Field(proto.BOOL, number=2) + name: str = proto.Field(proto.STRING, number=1) + return_code: bool = proto.Field(proto.BOOL, number=2) class ListQuantumProgramsRequest(proto.Message): @@ -268,17 +281,17 @@ class ListQuantumProgramsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumProgramsResponse(proto.Message): r"""- Attributes: - programs (Sequence[google.cloud.quantum_v1alpha1.types.QuantumProgram]): + programs (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram]): - next_page_token (str): - @@ -288,8 +301,10 @@ class ListQuantumProgramsResponse(proto.Message): def raw_page(self): return self - programs = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumProgram) - next_page_token = proto.Field(proto.STRING, number=2) + programs: MutableSequence[quantum.QuantumProgram] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumProgram + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class DeleteQuantumProgramRequest(proto.Message): @@ -302,8 +317,8 @@ class DeleteQuantumProgramRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - delete_jobs = proto.Field(proto.BOOL, number=2) + name: str = proto.Field(proto.STRING, number=1) + delete_jobs: bool = proto.Field(proto.BOOL, number=2) class UpdateQuantumProgramRequest(proto.Message): @@ -312,15 +327,19 @@ class UpdateQuantumProgramRequest(proto.Message): Attributes: name (str): - - quantum_program (google.cloud.quantum_v1alpha1.types.QuantumProgram): + quantum_program (cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram): - update_mask (google.protobuf.field_mask_pb2.FieldMask): - """ - name = proto.Field(proto.STRING, number=1) - quantum_program = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumProgram) - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask) + name: str = proto.Field(proto.STRING, number=1) + quantum_program: quantum.QuantumProgram = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumProgram + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask + ) class ListQuantumProcessorsRequest(proto.Message): @@ -337,17 +356,17 @@ class ListQuantumProcessorsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumProcessorsResponse(proto.Message): r"""- Attributes: - processors (Sequence[google.cloud.quantum_v1alpha1.types.QuantumProcessor]): + processors (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor]): - next_page_token (str): - @@ -357,8 +376,10 @@ class ListQuantumProcessorsResponse(proto.Message): def raw_page(self): return self - processors = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumProcessor) - next_page_token = proto.Field(proto.STRING, number=2) + processors: MutableSequence[quantum.QuantumProcessor] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumProcessor + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class GetQuantumProcessorRequest(proto.Message): @@ -369,7 +390,18 @@ class GetQuantumProcessorRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) + + +class GetQuantumProcessorConfigRequest(proto.Message): + r"""- + + Attributes: + name (str): + Required. - + """ + + name: str = proto.Field(proto.STRING, number=1) class ListQuantumCalibrationsRequest(proto.Message): @@ -378,7 +410,7 @@ class ListQuantumCalibrationsRequest(proto.Message): Attributes: parent (str): - - view (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest.QuantumCalibrationView): + view (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest.QuantumCalibrationView): - page_size (int): - @@ -386,27 +418,36 @@ class ListQuantumCalibrationsRequest(proto.Message): - filter (str): - - """ + """ # noqa E501 class QuantumCalibrationView(proto.Enum): - r"""-""" + r"""- + + Values: + QUANTUM_CALIBRATION_VIEW_UNSPECIFIED (0): + - + BASIC (1): + - + FULL (2): + - + """ QUANTUM_CALIBRATION_VIEW_UNSPECIFIED = 0 BASIC = 1 FULL = 2 - parent = proto.Field(proto.STRING, number=1) - view = proto.Field(proto.ENUM, number=5, enum=QuantumCalibrationView) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + view: QuantumCalibrationView = proto.Field(proto.ENUM, number=5, enum=QuantumCalibrationView) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumCalibrationsResponse(proto.Message): r"""- Attributes: - calibrations (Sequence[google.cloud.quantum_v1alpha1.types.QuantumCalibration]): + calibrations (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumCalibration]): - next_page_token (str): - @@ -416,8 +457,10 @@ class ListQuantumCalibrationsResponse(proto.Message): def raw_page(self): return self - calibrations = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumCalibration) - next_page_token = proto.Field(proto.STRING, number=2) + calibrations: MutableSequence[quantum.QuantumCalibration] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumCalibration + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class GetQuantumCalibrationRequest(proto.Message): @@ -428,7 +471,7 @@ class GetQuantumCalibrationRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class CreateQuantumReservationRequest(proto.Message): @@ -437,12 +480,14 @@ class CreateQuantumReservationRequest(proto.Message): Attributes: parent (str): - - quantum_reservation (google.cloud.quantum_v1alpha1.types.QuantumReservation): + quantum_reservation (cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation): - """ - parent = proto.Field(proto.STRING, number=1) - quantum_reservation = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumReservation) + parent: str = proto.Field(proto.STRING, number=1) + quantum_reservation: quantum.QuantumReservation = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumReservation + ) class CancelQuantumReservationRequest(proto.Message): @@ -453,7 +498,7 @@ class CancelQuantumReservationRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class DeleteQuantumReservationRequest(proto.Message): @@ -464,7 +509,7 @@ class DeleteQuantumReservationRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class GetQuantumReservationRequest(proto.Message): @@ -475,7 +520,7 @@ class GetQuantumReservationRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class ListQuantumReservationsRequest(proto.Message): @@ -492,17 +537,17 @@ class ListQuantumReservationsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumReservationsResponse(proto.Message): r"""- Attributes: - reservations (Sequence[google.cloud.quantum_v1alpha1.types.QuantumReservation]): + reservations (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation]): - next_page_token (str): - @@ -512,8 +557,10 @@ class ListQuantumReservationsResponse(proto.Message): def raw_page(self): return self - reservations = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumReservation) - next_page_token = proto.Field(proto.STRING, number=2) + reservations: MutableSequence[quantum.QuantumReservation] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumReservation + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class UpdateQuantumReservationRequest(proto.Message): @@ -522,15 +569,19 @@ class UpdateQuantumReservationRequest(proto.Message): Attributes: name (str): - - quantum_reservation (google.cloud.quantum_v1alpha1.types.QuantumReservation): + quantum_reservation (cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation): - update_mask (google.protobuf.field_mask_pb2.FieldMask): - """ - name = proto.Field(proto.STRING, number=1) - quantum_reservation = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumReservation) - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask) + name: str = proto.Field(proto.STRING, number=1) + quantum_reservation: quantum.QuantumReservation = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumReservation + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask + ) class QuantumRunStreamRequest(proto.Message): @@ -548,29 +599,29 @@ class QuantumRunStreamRequest(proto.Message): - parent (str): - - create_quantum_program_and_job (google.cloud.quantum_v1alpha1.types.CreateQuantumProgramAndJobRequest): + create_quantum_program_and_job (cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumProgramAndJobRequest): - This field is a member of `oneof`_ ``request``. - create_quantum_job (google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest): + create_quantum_job (cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest): - This field is a member of `oneof`_ ``request``. - get_quantum_result (google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest): + get_quantum_result (cirq_google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest): - This field is a member of `oneof`_ ``request``. - """ + """ # noqa E501 - message_id = proto.Field(proto.STRING, number=1) - parent = proto.Field(proto.STRING, number=2) - create_quantum_program_and_job = proto.Field( + message_id: str = proto.Field(proto.STRING, number=1) + parent: str = proto.Field(proto.STRING, number=2) + create_quantum_program_and_job: CreateQuantumProgramAndJobRequest = proto.Field( proto.MESSAGE, number=3, oneof='request', message='CreateQuantumProgramAndJobRequest' ) - create_quantum_job = proto.Field( + create_quantum_job: CreateQuantumJobRequest = proto.Field( proto.MESSAGE, number=4, oneof='request', message='CreateQuantumJobRequest' ) - get_quantum_result = proto.Field( + get_quantum_result: GetQuantumResultRequest = proto.Field( proto.MESSAGE, number=5, oneof='request', message='GetQuantumResultRequest' ) @@ -581,15 +632,19 @@ class CreateQuantumProgramAndJobRequest(proto.Message): Attributes: parent (str): - - quantum_program (google.cloud.quantum_v1alpha1.types.QuantumProgram): + quantum_program (cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram): - - quantum_job (google.cloud.quantum_v1alpha1.types.QuantumJob): + quantum_job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - """ - parent = proto.Field(proto.STRING, number=1) - quantum_program = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumProgram) - quantum_job = proto.Field(proto.MESSAGE, number=3, message=quantum.QuantumJob) + parent: str = proto.Field(proto.STRING, number=1) + quantum_program: quantum.QuantumProgram = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumProgram + ) + quantum_job: quantum.QuantumJob = proto.Field( + proto.MESSAGE, number=3, message=quantum.QuantumJob + ) class QuantumRunStreamResponse(proto.Message): @@ -605,38 +660,67 @@ class QuantumRunStreamResponse(proto.Message): Attributes: message_id (str): - - error (google.cloud.quantum_v1alpha1.types.StreamError): + error (cirq_google.cloud.quantum_v1alpha1.types.StreamError): - This field is a member of `oneof`_ ``response``. - job (google.cloud.quantum_v1alpha1.types.QuantumJob): + job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - This field is a member of `oneof`_ ``response``. - result (google.cloud.quantum_v1alpha1.types.QuantumResult): + result (cirq_google.cloud.quantum_v1alpha1.types.QuantumResult): - This field is a member of `oneof`_ ``response``. """ - message_id = proto.Field(proto.STRING, number=1) - error = proto.Field(proto.MESSAGE, number=2, oneof='response', message='StreamError') - job = proto.Field(proto.MESSAGE, number=3, oneof='response', message=quantum.QuantumJob) - result = proto.Field(proto.MESSAGE, number=4, oneof='response', message=quantum.QuantumResult) + message_id: str = proto.Field(proto.STRING, number=1) + error: StreamError = proto.Field( + proto.MESSAGE, number=2, oneof='response', message='StreamError' + ) + job: quantum.QuantumJob = proto.Field( + proto.MESSAGE, number=3, oneof='response', message=quantum.QuantumJob + ) + result: quantum.QuantumResult = proto.Field( + proto.MESSAGE, number=4, oneof='response', message=quantum.QuantumResult + ) class StreamError(proto.Message): r"""- Attributes: - code (google.cloud.quantum_v1alpha1.types.StreamError.Code): + code (cirq_google.cloud.quantum_v1alpha1.types.StreamError.Code): - message (str): - """ class Code(proto.Enum): - r"""-""" + r"""- + + Values: + CODE_UNSPECIFIED (0): + - + INTERNAL (1): + - + INVALID_ARGUMENT (2): + - + PERMISSION_DENIED (3): + - + PROGRAM_ALREADY_EXISTS (4): + - + JOB_ALREADY_EXISTS (5): + - + PROGRAM_DOES_NOT_EXIST (6): + - + JOB_DOES_NOT_EXIST (7): + - + PROCESSOR_DOES_NOT_EXIST (8): + - + INVALID_PROCESSOR_FOR_JOB (9): + - + """ CODE_UNSPECIFIED = 0 INTERNAL = 1 @@ -649,8 +733,8 @@ class Code(proto.Enum): PROCESSOR_DOES_NOT_EXIST = 8 INVALID_PROCESSOR_FOR_JOB = 9 - code = proto.Field(proto.ENUM, number=1, enum=Code) - message = proto.Field(proto.STRING, number=2) + code: Code = proto.Field(proto.ENUM, number=1, enum=Code) + message: str = proto.Field(proto.STRING, number=2) class ListQuantumReservationGrantsRequest(proto.Message): @@ -667,30 +751,30 @@ class ListQuantumReservationGrantsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumReservationGrantsResponse(proto.Message): r"""- Attributes: - reservation_grants (Sequence[google.cloud.quantum_v1alpha1.types.QuantumReservationGrant]): + reservation_grants (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationGrant]): - next_page_token (str): - - """ + """ # noqa E501 @property def raw_page(self): return self - reservation_grants = proto.RepeatedField( + reservation_grants: MutableSequence[quantum.QuantumReservationGrant] = proto.RepeatedField( proto.MESSAGE, number=1, message=quantum.QuantumReservationGrant ) - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token: str = proto.Field(proto.STRING, number=2) class ReallocateQuantumReservationGrantRequest(proto.Message): @@ -707,10 +791,12 @@ class ReallocateQuantumReservationGrantRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - source_project_id = proto.Field(proto.STRING, number=2) - target_project_id = proto.Field(proto.STRING, number=3) - duration = proto.Field(proto.MESSAGE, number=4, message=duration_pb2.Duration) + name: str = proto.Field(proto.STRING, number=1) + source_project_id: str = proto.Field(proto.STRING, number=2) + target_project_id: str = proto.Field(proto.STRING, number=3) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=4, message=duration_pb2.Duration + ) class ListQuantumReservationBudgetsRequest(proto.Message): @@ -727,30 +813,30 @@ class ListQuantumReservationBudgetsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumReservationBudgetsResponse(proto.Message): r"""- Attributes: - reservation_budgets (Sequence[google.cloud.quantum_v1alpha1.types.QuantumReservationBudget]): + reservation_budgets (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationBudget]): - next_page_token (str): - - """ + """ # noqa E501 @property def raw_page(self): return self - reservation_budgets = proto.RepeatedField( + reservation_budgets: MutableSequence[quantum.QuantumReservationBudget] = proto.RepeatedField( proto.MESSAGE, number=1, message=quantum.QuantumReservationBudget ) - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token: str = proto.Field(proto.STRING, number=2) class ListQuantumTimeSlotsRequest(proto.Message): @@ -767,17 +853,17 @@ class ListQuantumTimeSlotsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumTimeSlotsResponse(proto.Message): r"""- Attributes: - time_slots (Sequence[google.cloud.quantum_v1alpha1.types.QuantumTimeSlot]): + time_slots (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot]): - next_page_token (str): - @@ -787,8 +873,10 @@ class ListQuantumTimeSlotsResponse(proto.Message): def raw_page(self): return self - time_slots = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumTimeSlot) - next_page_token = proto.Field(proto.STRING, number=2) + time_slots: MutableSequence[quantum.QuantumTimeSlot] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumTimeSlot + ) + next_page_token: str = proto.Field(proto.STRING, number=2) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/quantum.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/quantum.py index 5749ead9fc4..3f2da574c50 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/quantum.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/quantum.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from __future__ import annotations import proto @@ -26,19 +25,20 @@ 'QuantumJob', 'SchedulingConfig', 'ExecutionStatus', + 'DeviceConfigSelector', + 'DeviceConfigKey', 'OutputConfig', 'GcsLocation', 'InlineData', 'QuantumJobEvent', 'QuantumResult', 'QuantumProcessor', + 'QuantumProcessorConfig', 'QuantumCalibration', 'QuantumReservationGrant', 'QuantumReservationBudget', 'QuantumTimeSlot', 'QuantumReservation', - 'DeviceConfigSelector', - 'DeviceConfigKey', }, ) @@ -60,17 +60,17 @@ class QuantumProgram(proto.Message): - update_time (google.protobuf.timestamp_pb2.Timestamp): - - labels (Sequence[google.cloud.quantum_v1alpha1.types.QuantumProgram.LabelsEntry]): + labels (dict[str, str]): - label_fingerprint (str): - description (str): - - gcs_code_location (google.cloud.quantum_v1alpha1.types.GcsLocation): + gcs_code_location (cirq_google.cloud.quantum_v1alpha1.types.GcsLocation): - This field is a member of `oneof`_ ``code_location``. - code_inline_data (google.cloud.quantum_v1alpha1.types.InlineData): + code_inline_data (cirq_google.cloud.quantum_v1alpha1.types.InlineData): - This field is a member of `oneof`_ ``code_location``. @@ -78,19 +78,23 @@ class QuantumProgram(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - labels = proto.MapField(proto.STRING, proto.STRING, number=4) - label_fingerprint = proto.Field(proto.STRING, number=5) - description = proto.Field(proto.STRING, number=6) - gcs_code_location = proto.Field( + name: str = proto.Field(proto.STRING, number=1) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + labels: dict[str, str] = proto.MapField(proto.STRING, proto.STRING, number=4) + label_fingerprint: str = proto.Field(proto.STRING, number=5) + description: str = proto.Field(proto.STRING, number=6) + gcs_code_location: GcsLocation = proto.Field( proto.MESSAGE, number=7, oneof='code_location', message='GcsLocation' ) - code_inline_data = proto.Field( + code_inline_data: InlineData = proto.Field( proto.MESSAGE, number=9, oneof='code_location', message='InlineData' ) - code = proto.Field(proto.MESSAGE, number=8, message=any_pb2.Any) + code: any_pb2.Any = proto.Field(proto.MESSAGE, number=8, message=any_pb2.Any) class QuantumJob(proto.Message): @@ -110,23 +114,23 @@ class QuantumJob(proto.Message): - update_time (google.protobuf.timestamp_pb2.Timestamp): - - labels (Sequence[google.cloud.quantum_v1alpha1.types.QuantumJob.LabelsEntry]): + labels (dict[str, str]): - label_fingerprint (str): - description (str): - - scheduling_config (google.cloud.quantum_v1alpha1.types.SchedulingConfig): + scheduling_config (cirq_google.cloud.quantum_v1alpha1.types.SchedulingConfig): - - output_config (google.cloud.quantum_v1alpha1.types.OutputConfig): + output_config (cirq_google.cloud.quantum_v1alpha1.types.OutputConfig): - - execution_status (google.cloud.quantum_v1alpha1.types.ExecutionStatus): + execution_status (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus): - - gcs_run_context_location (google.cloud.quantum_v1alpha1.types.GcsLocation): + gcs_run_context_location (cirq_google.cloud.quantum_v1alpha1.types.GcsLocation): - This field is a member of `oneof`_ ``run_context_location``. - run_context_inline_data (google.cloud.quantum_v1alpha1.types.InlineData): + run_context_inline_data (cirq_google.cloud.quantum_v1alpha1.types.InlineData): - This field is a member of `oneof`_ ``run_context_location``. @@ -134,68 +138,30 @@ class QuantumJob(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - labels = proto.MapField(proto.STRING, proto.STRING, number=4) - label_fingerprint = proto.Field(proto.STRING, number=5) - description = proto.Field(proto.STRING, number=6) - scheduling_config = proto.Field(proto.MESSAGE, number=7, message='SchedulingConfig') - output_config = proto.Field(proto.MESSAGE, number=8, message='OutputConfig') - execution_status = proto.Field(proto.MESSAGE, number=9, message='ExecutionStatus') - gcs_run_context_location = proto.Field( + name: str = proto.Field(proto.STRING, number=1) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + labels: dict[str, str] = proto.MapField(proto.STRING, proto.STRING, number=4) + label_fingerprint: str = proto.Field(proto.STRING, number=5) + description: str = proto.Field(proto.STRING, number=6) + scheduling_config: SchedulingConfig = proto.Field( + proto.MESSAGE, number=7, message='SchedulingConfig' + ) + output_config: OutputConfig = proto.Field(proto.MESSAGE, number=8, message='OutputConfig') + execution_status: ExecutionStatus = proto.Field( + proto.MESSAGE, number=9, message='ExecutionStatus' + ) + gcs_run_context_location: GcsLocation = proto.Field( proto.MESSAGE, number=10, oneof='run_context_location', message='GcsLocation' ) - run_context_inline_data = proto.Field( + run_context_inline_data: InlineData = proto.Field( proto.MESSAGE, number=12, oneof='run_context_location', message='InlineData' ) - run_context = proto.Field(proto.MESSAGE, number=11, message=any_pb2.Any) - - -class DeviceConfigSelector(proto.Message): - r"""- - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - Attributes: - run_name (str): - - - This field is a member of `oneof`_ ``top_level_identifier``. - snapshot_id (str): - - - This field is a member of `oneof`_ ``top_level_identifier``. - config_alias (str): - - - """ - - run_name: str = proto.Field(proto.STRING, number=1, oneof='top_level_identifier') - snapshot_id: str = proto.Field(proto.STRING, number=3, oneof='top_level_identifier') - config_alias: str = proto.Field(proto.STRING, number=2) - - -class DeviceConfigKey(proto.Message): - r"""- - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - Attributes: - run (str): - - - This field is a member of `oneof`_ ``top_level_identifier``. - snapshot_id (str): - - - This field is a member of `oneof`_ ``top_level_identifier``. - config_alias (str): - - - """ - - run: str = proto.Field(proto.STRING, number=1, oneof='top_level_identifier') - snapshot_id: str = proto.Field(proto.STRING, number=3, oneof='top_level_identifier') - config_alias: str = proto.Field(proto.STRING, number=2) + run_context: any_pb2.Any = proto.Field(proto.MESSAGE, number=11, message=any_pb2.Any) class SchedulingConfig(proto.Message): @@ -204,51 +170,76 @@ class SchedulingConfig(proto.Message): Attributes: target_route (str): - - processor_selector (google.cloud.quantum_v1alpha1.types.SchedulingConfig.ProcessorSelector): + processor_selector (cirq_google.cloud.quantum_v1alpha1.types.SchedulingConfig.ProcessorSelector): - priority (int): - - """ + """ # noqa E501 class ProcessorSelector(proto.Message): r"""- + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: - processor_names (Sequence[str]): + processor_names (list[str]): - processor (str): - - device_config_selector ((google.cloud.quantum_v1alpha1.types.DeviceConfigSelector): + device_config_selector (cirq_google.cloud.quantum_v1alpha1.types.DeviceConfigSelector): - + + This field is a member of `oneof`_ ``_device_config_selector``. """ - processor_names = proto.RepeatedField(proto.STRING, number=1) - processor = proto.Field(proto.STRING, number=2) - device_config_selector = proto.Field(proto.MESSAGE, number=3, message=DeviceConfigSelector) + processor_names: list[str] = proto.RepeatedField(proto.STRING, number=1) + processor: str = proto.Field(proto.STRING, number=2) + device_config_selector: DeviceConfigSelector = proto.Field( + proto.MESSAGE, number=3, optional=True, message='DeviceConfigSelector' + ) - target_route = proto.Field(proto.STRING, number=1) - processor_selector = proto.Field(proto.MESSAGE, number=3, message=ProcessorSelector) - priority = proto.Field(proto.INT32, number=2) + target_route: str = proto.Field(proto.STRING, number=1) + processor_selector: ProcessorSelector = proto.Field( + proto.MESSAGE, number=3, message=ProcessorSelector + ) + priority: int = proto.Field(proto.INT32, number=2) class ExecutionStatus(proto.Message): r"""- Attributes: - state (google.cloud.quantum_v1alpha1.types.ExecutionStatus.State): + state (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus.State): - processor_name (str): - calibration_name (str): - - failure (google.cloud.quantum_v1alpha1.types.ExecutionStatus.Failure): + failure (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus.Failure): - - timing (google.cloud.quantum_v1alpha1.types.ExecutionStatus.Timing): + timing (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus.Timing): - """ class State(proto.Enum): - r"""-""" + r"""- + + Values: + STATE_UNSPECIFIED (0): + - + READY (1): + - + RUNNING (2): + - + CANCELLING (3): + - + CANCELLED (4): + - + SUCCESS (5): + - + FAILURE (6): + - + """ STATE_UNSPECIFIED = 0 READY = 1 @@ -262,14 +253,45 @@ class Failure(proto.Message): r"""- Attributes: - error_code (google.cloud.quantum_v1alpha1.types.ExecutionStatus.Failure.Code): + error_code (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus.Failure.Code): - error_message (str): - """ class Code(proto.Enum): - r"""-""" + r"""- + + Values: + CODE_UNSPECIFIED (0): + - + SYSTEM_ERROR (1): + - + INVALID_PROGRAM (2): + - + INVALID_RUN_CONTEXT (3): + - + READ_PROGRAM_NOT_FOUND_IN_GCS (4): + - + READ_PROGRAM_PERMISSION_DENIED (5): + - + READ_PROGRAM_UNKNOWN_ERROR (6): + - + READ_RUN_CONTEXT_NOT_FOUND_IN_GCS (7): + - + READ_RUN_CONTEXT_PERMISSION_DENIED (8): + - + READ_RUN_CONTEXT_UNKNOWN_ERROR (9): + - + WRITE_RESULT_ALREADY_EXISTS_IN_GCS (10): + - + WRITE_RESULT_GCS_PERMISSION_DENIED (11): + - + SCHEDULING_EXPIRED (14): + - + FAILED_PRECONDITION (15): + - + """ CODE_UNSPECIFIED = 0 SYSTEM_ERROR = 1 @@ -286,8 +308,10 @@ class Code(proto.Enum): SCHEDULING_EXPIRED = 14 FAILED_PRECONDITION = 15 - error_code = proto.Field(proto.ENUM, number=1, enum='ExecutionStatus.Failure.Code') - error_message = proto.Field(proto.STRING, number=2) + error_code: ExecutionStatus.Failure.Code = proto.Field( + proto.ENUM, number=1, enum='ExecutionStatus.Failure.Code' + ) + error_message: str = proto.Field(proto.STRING, number=2) class Timing(proto.Message): r"""- @@ -299,14 +323,74 @@ class Timing(proto.Message): - """ - started_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp) - completed_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) + started_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp + ) + completed_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + + state: State = proto.Field(proto.ENUM, number=1, enum=State) + processor_name: str = proto.Field(proto.STRING, number=3) + calibration_name: str = proto.Field(proto.STRING, number=4) + failure: Failure = proto.Field(proto.MESSAGE, number=5, message=Failure) + timing: Timing = proto.Field(proto.MESSAGE, number=6, message=Timing) + + +class DeviceConfigSelector(proto.Message): + r"""- + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + run_name (str): + - + + This field is a member of `oneof`_ ``top_level_identifier``. + snapshot_id (str): + - + + This field is a member of `oneof`_ ``top_level_identifier``. + config_alias (str): + - + """ - state = proto.Field(proto.ENUM, number=1, enum=State) - processor_name = proto.Field(proto.STRING, number=3) - calibration_name = proto.Field(proto.STRING, number=4) - failure = proto.Field(proto.MESSAGE, number=5, message=Failure) - timing = proto.Field(proto.MESSAGE, number=6, message=Timing) + run_name: str = proto.Field(proto.STRING, number=1, oneof='top_level_identifier') + snapshot_id: str = proto.Field(proto.STRING, number=3, oneof='top_level_identifier') + config_alias: str = proto.Field(proto.STRING, number=2) + + +class DeviceConfigKey(proto.Message): + r"""- + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + run (str): + - + + This field is a member of `oneof`_ ``top_level_identifier``. + snapshot_id (str): + - + + This field is a member of `oneof`_ ``top_level_identifier``. + config_alias (str): + - + """ + + run: str = proto.Field(proto.STRING, number=1, oneof='top_level_identifier') + snapshot_id: str = proto.Field(proto.STRING, number=3, oneof='top_level_identifier') + config_alias: str = proto.Field(proto.STRING, number=2) class OutputConfig(proto.Message): @@ -315,7 +399,7 @@ class OutputConfig(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - gcs_results_location (google.cloud.quantum_v1alpha1.types.GcsLocation): + gcs_results_location (cirq_google.cloud.quantum_v1alpha1.types.GcsLocation): - This field is a member of `oneof`_ ``output_destination``. @@ -323,10 +407,10 @@ class OutputConfig(proto.Message): - """ - gcs_results_location = proto.Field( + gcs_results_location: GcsLocation = proto.Field( proto.MESSAGE, number=1, oneof='output_destination', message='GcsLocation' ) - overwrite_existing = proto.Field(proto.BOOL, number=2) + overwrite_existing: bool = proto.Field(proto.BOOL, number=2) class GcsLocation(proto.Message): @@ -339,8 +423,8 @@ class GcsLocation(proto.Message): - """ - uri = proto.Field(proto.STRING, number=1) - type_url = proto.Field(proto.STRING, number=2) + uri: str = proto.Field(proto.STRING, number=1) + type_url: str = proto.Field(proto.STRING, number=2) class InlineData(proto.Message): @@ -351,7 +435,7 @@ class InlineData(proto.Message): - """ - type_url = proto.Field(proto.STRING, number=1) + type_url: str = proto.Field(proto.STRING, number=1) class QuantumJobEvent(proto.Message): @@ -360,15 +444,19 @@ class QuantumJobEvent(proto.Message): Attributes: event_time (google.protobuf.timestamp_pb2.Timestamp): - - job (google.cloud.quantum_v1alpha1.types.QuantumJob): + job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - modified_field_mask (google.protobuf.field_mask_pb2.FieldMask): - """ - event_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp) - job = proto.Field(proto.MESSAGE, number=2, message='QuantumJob') - modified_field_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp + ) + job: QuantumJob = proto.Field(proto.MESSAGE, number=2, message='QuantumJob') + modified_field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask + ) class QuantumResult(proto.Message): @@ -381,8 +469,8 @@ class QuantumResult(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - result = proto.Field(proto.MESSAGE, number=2, message=any_pb2.Any) + parent: str = proto.Field(proto.STRING, number=1) + result: any_pb2.Any = proto.Field(proto.MESSAGE, number=2, message=any_pb2.Any) class QuantumProcessor(proto.Message): @@ -391,13 +479,13 @@ class QuantumProcessor(proto.Message): Attributes: name (str): - - health (google.cloud.quantum_v1alpha1.types.QuantumProcessor.Health): + health (cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor.Health): - expected_down_time (google.protobuf.timestamp_pb2.Timestamp): - expected_recovery_time (google.protobuf.timestamp_pb2.Timestamp): - - supported_languages (Sequence[str]): + supported_languages (list[str]): - device_spec (google.protobuf.any_pb2.Any): - @@ -407,17 +495,29 @@ class QuantumProcessor(proto.Message): - current_calibration (str): Output only. - - active_time_slot (google.cloud.quantum_v1alpha1.types.QuantumTimeSlot): + active_time_slot (cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot): Output only. - - activity_stats (google.cloud.quantum_v1alpha1.types.QuantumProcessor.ActivityStats): + activity_stats (cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor.ActivityStats): - - default_device_config_key (google.cloud.quantum_v1alpha1.types.DeviceConfigKey): + default_device_config_key (cirq_google.cloud.quantum_v1alpha1.types.DeviceConfigKey): - - """ class Health(proto.Enum): - r"""-""" + r"""- + + Values: + HEALTH_UNSPECIFIED (0): + - + OK (1): + - + DOWN (2): + - + INACTIVE (4): + - + UNAVAILABLE (3): + - + """ HEALTH_UNSPECIFIED = 0 OK = 1 @@ -435,21 +535,50 @@ class ActivityStats(proto.Message): - """ - active_users_count = proto.Field(proto.INT64, number=1) - active_jobs_count = proto.Field(proto.INT64, number=2) + active_users_count: int = proto.Field(proto.INT64, number=1) + active_jobs_count: int = proto.Field(proto.INT64, number=2) + + name: str = proto.Field(proto.STRING, number=1) + health: Health = proto.Field(proto.ENUM, number=3, enum=Health) + expected_down_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp + ) + expected_recovery_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp + ) + supported_languages: list[str] = proto.RepeatedField(proto.STRING, number=5) + device_spec: any_pb2.Any = proto.Field(proto.MESSAGE, number=6, message=any_pb2.Any) + schedule_horizon: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=8, message=duration_pb2.Duration + ) + schedule_frozen_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=9, message=duration_pb2.Duration + ) + current_calibration: str = proto.Field(proto.STRING, number=10) + active_time_slot: QuantumTimeSlot = proto.Field( + proto.MESSAGE, number=11, message='QuantumTimeSlot' + ) + activity_stats: ActivityStats = proto.Field(proto.MESSAGE, number=12, message=ActivityStats) + default_device_config_key: DeviceConfigKey = proto.Field( + proto.MESSAGE, number=13, message='DeviceConfigKey' + ) + - name = proto.Field(proto.STRING, number=1) - health = proto.Field(proto.ENUM, number=3, enum=Health) - expected_down_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp) - expected_recovery_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp) - supported_languages = proto.RepeatedField(proto.STRING, number=5) - device_spec = proto.Field(proto.MESSAGE, number=6, message=any_pb2.Any) - schedule_horizon = proto.Field(proto.MESSAGE, number=8, message=duration_pb2.Duration) - schedule_frozen_period = proto.Field(proto.MESSAGE, number=9, message=duration_pb2.Duration) - current_calibration = proto.Field(proto.STRING, number=10) - active_time_slot = proto.Field(proto.MESSAGE, number=11, message='QuantumTimeSlot') - activity_stats = proto.Field(proto.MESSAGE, number=12, message=ActivityStats) - default_device_config_key = proto.Field(proto.MESSAGE, number=13, message='DeviceConfigKey') +class QuantumProcessorConfig(proto.Message): + r"""- + + Attributes: + name (str): + Identifier. - + device_specification (google.protobuf.any_pb2.Any): + - + characterization (google.protobuf.any_pb2.Any): + - + """ + + name: str = proto.Field(proto.STRING, number=1) + device_specification: any_pb2.Any = proto.Field(proto.MESSAGE, number=2, message=any_pb2.Any) + characterization: any_pb2.Any = proto.Field(proto.MESSAGE, number=3, message=any_pb2.Any) class QuantumCalibration(proto.Message): @@ -464,9 +593,11 @@ class QuantumCalibration(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - timestamp = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - data = proto.Field(proto.MESSAGE, number=3, message=any_pb2.Any) + name: str = proto.Field(proto.STRING, number=1) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + data: any_pb2.Any = proto.Field(proto.MESSAGE, number=3, message=any_pb2.Any) class QuantumReservationGrant(proto.Message): @@ -475,7 +606,7 @@ class QuantumReservationGrant(proto.Message): Attributes: name (str): - - processor_names (Sequence[str]): + processor_names (list[str]): - effective_time (google.protobuf.timestamp_pb2.Timestamp): - @@ -485,7 +616,7 @@ class QuantumReservationGrant(proto.Message): - available_duration (google.protobuf.duration_pb2.Duration): - - budgets (Sequence[google.cloud.quantum_v1alpha1.types.QuantumReservationGrant.Budget]): + budgets (list[cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationGrant.Budget]): - """ @@ -501,17 +632,29 @@ class Budget(proto.Message): - """ - project_id = proto.Field(proto.STRING, number=1) - granted_duration = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration) - available_duration = proto.Field(proto.MESSAGE, number=3, message=duration_pb2.Duration) - - name = proto.Field(proto.STRING, number=1) - processor_names = proto.RepeatedField(proto.STRING, number=2) - effective_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - expire_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp) - granted_duration = proto.Field(proto.MESSAGE, number=5, message=duration_pb2.Duration) - available_duration = proto.Field(proto.MESSAGE, number=6, message=duration_pb2.Duration) - budgets = proto.RepeatedField(proto.MESSAGE, number=7, message=Budget) + project_id: str = proto.Field(proto.STRING, number=1) + granted_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=2, message=duration_pb2.Duration + ) + available_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=3, message=duration_pb2.Duration + ) + + name: str = proto.Field(proto.STRING, number=1) + processor_names: list[str] = proto.RepeatedField(proto.STRING, number=2) + effective_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp + ) + granted_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration + ) + available_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=6, message=duration_pb2.Duration + ) + budgets: list[Budget] = proto.RepeatedField(proto.MESSAGE, number=7, message=Budget) class QuantumReservationBudget(proto.Message): @@ -520,7 +663,7 @@ class QuantumReservationBudget(proto.Message): Attributes: name (str): - - processor_names (Sequence[str]): + processor_names (list[str]): - effective_time (google.protobuf.timestamp_pb2.Timestamp): - @@ -532,12 +675,20 @@ class QuantumReservationBudget(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - processor_names = proto.RepeatedField(proto.STRING, number=2) - effective_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - expire_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp) - granted_duration = proto.Field(proto.MESSAGE, number=5, message=duration_pb2.Duration) - available_duration = proto.Field(proto.MESSAGE, number=6, message=duration_pb2.Duration) + name: str = proto.Field(proto.STRING, number=1) + processor_names: list[str] = proto.RepeatedField(proto.STRING, number=2) + effective_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp + ) + granted_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration + ) + available_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=6, message=duration_pb2.Duration + ) class QuantumTimeSlot(proto.Message): @@ -557,20 +708,33 @@ class QuantumTimeSlot(proto.Message): - end_time (google.protobuf.timestamp_pb2.Timestamp): - - time_slot_type (google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.TimeSlotType): + time_slot_type (cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.TimeSlotType): - - reservation_config (google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.ReservationConfig): + reservation_config (cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.ReservationConfig): - This field is a member of `oneof`_ ``type_config``. - maintenance_config (google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.MaintenanceConfig): + maintenance_config (cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.MaintenanceConfig): - This field is a member of `oneof`_ ``type_config``. - """ + """ # noqa E501 class TimeSlotType(proto.Enum): - r"""-""" + r"""- + + Values: + TIME_SLOT_TYPE_UNSPECIFIED (0): + - + MAINTENANCE (1): + - + OPEN_SWIM (2): + - + RESERVATION (3): + - + UNALLOCATED (4): + - + """ TIME_SLOT_TYPE_UNSPECIFIED = 0 MAINTENANCE = 1 @@ -586,13 +750,13 @@ class ReservationConfig(proto.Message): - project_id (str): - - whitelisted_users (Sequence[str]): + allowlisted_users (list[str]): - """ - reservation = proto.Field(proto.STRING, number=3) - project_id = proto.Field(proto.STRING, number=1) - whitelisted_users = proto.RepeatedField(proto.STRING, number=2) + reservation: str = proto.Field(proto.STRING, number=3) + project_id: str = proto.Field(proto.STRING, number=1) + allowlisted_users: list[str] = proto.RepeatedField(proto.STRING, number=2) class MaintenanceConfig(proto.Message): r"""- @@ -604,17 +768,21 @@ class MaintenanceConfig(proto.Message): - """ - title = proto.Field(proto.STRING, number=1) - description = proto.Field(proto.STRING, number=2) + title: str = proto.Field(proto.STRING, number=1) + description: str = proto.Field(proto.STRING, number=2) - processor_name = proto.Field(proto.STRING, number=1) - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - time_slot_type = proto.Field(proto.ENUM, number=5, enum=TimeSlotType) - reservation_config = proto.Field( + processor_name: str = proto.Field(proto.STRING, number=1) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + time_slot_type: TimeSlotType = proto.Field(proto.ENUM, number=5, enum=TimeSlotType) + reservation_config: ReservationConfig = proto.Field( proto.MESSAGE, number=6, oneof='type_config', message=ReservationConfig ) - maintenance_config = proto.Field( + maintenance_config: MaintenanceConfig = proto.Field( proto.MESSAGE, number=7, oneof='type_config', message=MaintenanceConfig ) @@ -631,15 +799,21 @@ class QuantumReservation(proto.Message): - cancelled_time (google.protobuf.timestamp_pb2.Timestamp): - - whitelisted_users (Sequence[str]): + allowlisted_users (list[str]): - """ - name = proto.Field(proto.STRING, number=1) - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - cancelled_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp) - whitelisted_users = proto.RepeatedField(proto.STRING, number=5) + name: str = proto.Field(proto.STRING, number=1) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + cancelled_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp + ) + allowlisted_users: list[str] = proto.RepeatedField(proto.STRING, number=5) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/cirq-google/cirq_google/engine/abstract_local_processor.py b/cirq-google/cirq_google/engine/abstract_local_processor.py index 6b76ecba8ab..b4501d65bee 100644 --- a/cirq-google/cirq_google/engine/abstract_local_processor.py +++ b/cirq-google/cirq_google/engine/abstract_local_processor.py @@ -16,10 +16,11 @@ import abc import datetime -from typing import overload, TYPE_CHECKING +from typing import Any, overload, TYPE_CHECKING from google.protobuf.timestamp_pb2 import Timestamp +from cirq import _compat from cirq_google.cloud import quantum from cirq_google.engine.abstract_processor import AbstractProcessor @@ -47,6 +48,13 @@ def _to_timestamp(union_time: None | datetime.datetime | datetime.timedelta) -> return None +def _fix_deprecated_allowlisted_users_args( + args: tuple[Any, ...], kwargs: dict[str, Any] +) -> tuple[tuple[Any, ...], dict[str, Any]]: + kwargs['allowlisted_users'] = kwargs.pop('whitelisted_users') + return args, kwargs + + class AbstractLocalProcessor(AbstractProcessor): """Partial implementation of AbstractProcessor using in-memory objects. @@ -234,18 +242,25 @@ def _is_available(self, time_slot: quantum.QuantumTimeSlot) -> bool: return False return True + @_compat.deprecated_parameter( + deadline='v1.7', + fix='Change whitelisted_users to allowlisted_users.', + parameter_desc='whitelisted_users', + match=lambda args, kwargs: 'whitelisted_users' in kwargs, + rewrite=_fix_deprecated_allowlisted_users_args, + ) def create_reservation( self, start_time: datetime.datetime, end_time: datetime.datetime, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ) -> quantum.QuantumReservation: """Creates a reservation on this processor. Args: start_time: the starting date/time of the reservation. end_time: the ending date/time of the reservation. - whitelisted_users: a list of emails that are allowed + allowlisted_users: a list of emails that are allowed to send programs during this reservation (in addition to users with permission "quantum.reservations.use" on the project). @@ -259,7 +274,7 @@ def create_reservation( name=reservation_id, start_time=Timestamp(seconds=int(start_time.timestamp())), end_time=Timestamp(seconds=int(end_time.timestamp())), - whitelisted_users=whitelisted_users, + allowlisted_users=allowlisted_users, ) time_slot = self._reservation_to_time_slot(new_reservation) if not self._is_available(time_slot): @@ -281,12 +296,19 @@ def get_reservation(self, reservation_id: str) -> quantum.QuantumReservation | N else: return None + @_compat.deprecated_parameter( + deadline='v1.7', + fix='Change whitelisted_users to allowlisted_users.', + parameter_desc='whitelisted_users', + match=lambda args, kwargs: 'whitelisted_users' in kwargs, + rewrite=_fix_deprecated_allowlisted_users_args, + ) def update_reservation( self, reservation_id: str, start_time: datetime.datetime | None = None, end_time: datetime.datetime | None = None, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ) -> None: """Updates a reservation with new information. @@ -300,7 +322,7 @@ def update_reservation( starting time is left unchanged. end_time: New ending time of the reservation. If unspecified, ending time is left unchanged. - whitelisted_users: The new list of whitelisted users to allow on + allowlisted_users: The new list of allowlisted users to allow on the reservation. If unspecified, the users are left unchanged. Raises: @@ -316,9 +338,9 @@ def update_reservation( self._reservations[reservation_id].end_time = datetime.datetime.fromtimestamp( _to_timestamp(end_time) ) - if whitelisted_users is not None: - del self._reservations[reservation_id].whitelisted_users[:] - self._reservations[reservation_id].whitelisted_users.extend(whitelisted_users) + if allowlisted_users is not None: + del self._reservations[reservation_id].allowlisted_users[:] + self._reservations[reservation_id].allowlisted_users.extend(allowlisted_users) def list_reservations( self, diff --git a/cirq-google/cirq_google/engine/abstract_local_processor_test.py b/cirq-google/cirq_google/engine/abstract_local_processor_test.py index cbaf6f1057b..890c435d7ec 100644 --- a/cirq-google/cirq_google/engine/abstract_local_processor_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_processor_test.py @@ -19,6 +19,7 @@ import pytest from google.protobuf.timestamp_pb2 import Timestamp +import cirq from cirq_google.cloud import quantum from cirq_google.engine.abstract_local_processor import AbstractLocalProcessor @@ -96,11 +97,11 @@ def test_reservations(): # Create Reservation reservation = p.create_reservation( - start_time=start_reservation, end_time=end_reservation, whitelisted_users=users + start_time=start_reservation, end_time=end_reservation, allowlisted_users=users ) assert reservation.start_time.timestamp() == int(start_reservation.timestamp()) assert reservation.end_time.timestamp() == int(end_reservation.timestamp()) - assert reservation.whitelisted_users == users + assert reservation.allowlisted_users == users # Get Reservation assert p.get_reservation(reservation.name) == reservation @@ -116,12 +117,22 @@ def test_reservations(): reservation = p.get_reservation(reservation.name) assert reservation.start_time.timestamp() == int(start_reservation.timestamp()) users = ['gooduser@test.com', 'otheruser@prod.com'] - p.update_reservation(reservation_id=reservation.name, whitelisted_users=users) + p.update_reservation(reservation_id=reservation.name, allowlisted_users=users) reservation = p.get_reservation(reservation.name) - assert reservation.whitelisted_users == users + assert reservation.allowlisted_users == users with pytest.raises(ValueError, match='does not exist'): - p.update_reservation(reservation_id='invalid', whitelisted_users=users) + p.update_reservation(reservation_id='invalid', allowlisted_users=users) + + day = datetime.timedelta(hours=24) + with cirq.testing.assert_deprecated('Change whitelisted_users', deadline='v1.7'): + _ = p.create_reservation( + start_time=start_reservation + day, + end_time=end_reservation + day, + whitelisted_users=users, + ) + with cirq.testing.assert_deprecated('Change whitelisted_users', deadline='v1.7'): + p.update_reservation(reservation_id=reservation.name, whitelisted_users=users) def test_list_reservations(): @@ -131,13 +142,13 @@ def test_list_reservations(): users = ['abc@def.com'] reservation1 = p.create_reservation( - start_time=now - hour, end_time=now, whitelisted_users=users + start_time=now - hour, end_time=now, allowlisted_users=users ) reservation2 = p.create_reservation( - start_time=now, end_time=now + hour, whitelisted_users=users + start_time=now, end_time=now + hour, allowlisted_users=users ) reservation3 = p.create_reservation( - start_time=now + hour, end_time=now + 2 * hour, whitelisted_users=users + start_time=now + hour, end_time=now + 2 * hour, allowlisted_users=users ) assert p.list_reservations(now - 2 * hour, now + 3 * hour) == [ diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index de34bb248ca..64cfe92f986 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -284,14 +284,14 @@ def create_reservation( self, start_time: datetime.datetime, end_time: datetime.datetime, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ) -> quantum.QuantumReservation: """Creates a reservation on this processor. Args: start_time: the starting date/time of the reservation. end_time: the ending date/time of the reservation. - whitelisted_users: a list of emails that are allowed + allowlisted_users: a list of emails that are allowed to send programs during this reservation (in addition to users with permission "quantum.reservations.use" on the project). """ @@ -310,7 +310,7 @@ def update_reservation( reservation_id: str, start_time: datetime.datetime | None = None, end_time: datetime.datetime | None = None, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Updates a reservation with new information. diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index f67de08e440..3405d5a4640 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -18,7 +18,7 @@ import sys import warnings from functools import cached_property -from typing import AsyncIterable, Awaitable, Callable, TypeVar +from typing import Any, AsyncIterable, Awaitable, Callable, TypeVar import duet import proto @@ -26,6 +26,7 @@ from google.protobuf import any_pb2, field_mask_pb2 from google.protobuf.timestamp_pb2 import Timestamp +from cirq import _compat from cirq_google.cloud import quantum from cirq_google.engine import stream_manager from cirq_google.engine.asyncio_executor import AsyncioExecutor @@ -34,6 +35,13 @@ _R = TypeVar('_R') +def _fix_deprecated_allowlisted_users_args( + args: tuple[Any, ...], kwargs: dict[str, Any] +) -> tuple[tuple[Any, ...], dict[str, Any]]: + kwargs['allowlisted_users'] = kwargs.pop('whitelisted_users') + return args, kwargs + + class EngineException(Exception): def __init__(self, message): # Call the base class constructor with the parameters it needs @@ -945,13 +953,20 @@ async def get_current_calibration_async( get_current_calibration = duet.sync(get_current_calibration_async) + @_compat.deprecated_parameter( + deadline='v1.7', + fix='Change whitelisted_users to allowlisted_users.', + parameter_desc='whitelisted_users', + match=lambda args, kwargs: 'whitelisted_users' in kwargs, + rewrite=_fix_deprecated_allowlisted_users_args, + ) async def create_reservation_async( self, project_id: str, processor_id: str, start: datetime.datetime, end: datetime.datetime, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Creates a quantum reservation and returns the created object. @@ -962,7 +977,7 @@ async def create_reservation_async( or None if the engine should generate an id start: the starting time of the reservation as a datetime object end: the ending time of the reservation as a datetime object - whitelisted_users: a list of emails that can use the reservation. + allowlisted_users: a list of emails that can use the reservation. """ parent = _processor_name_from_ids(project_id, processor_id) reservation = quantum.QuantumReservation( @@ -970,14 +985,14 @@ async def create_reservation_async( start_time=Timestamp(seconds=int(start.timestamp())), end_time=Timestamp(seconds=int(end.timestamp())), ) - if whitelisted_users: - reservation.whitelisted_users.extend(whitelisted_users) + if allowlisted_users: + reservation.allowlisted_users.extend(allowlisted_users) request = quantum.CreateQuantumReservationRequest( parent=parent, quantum_reservation=reservation ) return await self._send_request_async(self.grpc_client.create_quantum_reservation, request) - create_reservation = duet.sync(create_reservation_async) + create_reservation = duet.sync(create_reservation_async) # type: ignore[misc] async def cancel_reservation_async( self, project_id: str, processor_id: str, reservation_id: str @@ -1083,6 +1098,13 @@ async def list_reservations_async( list_reservations = duet.sync(list_reservations_async) + @_compat.deprecated_parameter( + deadline='v1.7', + fix='Change whitelisted_users to allowlisted_users.', + parameter_desc='whitelisted_users', + match=lambda args, kwargs: 'whitelisted_users' in kwargs, + rewrite=_fix_deprecated_allowlisted_users_args, + ) async def update_reservation_async( self, project_id: str, @@ -1090,12 +1112,12 @@ async def update_reservation_async( reservation_id: str, start: datetime.datetime | None = None, end: datetime.datetime | None = None, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Updates a quantum reservation. This will update a quantum reservation's starting time, ending time, - and list of whitelisted users. If any field is not filled, it will + and list of allowlisted users. If any field is not filled, it will not be updated. Args: @@ -1104,8 +1126,8 @@ async def update_reservation_async( reservation_id: Unique ID of the reservation in the parent project, start: the new starting time of the reservation as a datetime object end: the new ending time of the reservation as a datetime object - whitelisted_users: a list of emails that can use the reservation. - The empty list, [], will clear the whitelisted_users while None + allowlisted_users: a list of emails that can use the reservation. + The empty list, [], will clear the allowlisted_users while None will leave the value unchanged. """ name = ( @@ -1122,9 +1144,9 @@ async def update_reservation_async( if end: reservation.end_time = end paths.append('end_time') - if whitelisted_users is not None: - reservation.whitelisted_users.extend(whitelisted_users) - paths.append('whitelisted_users') + if allowlisted_users is not None: + reservation.allowlisted_users.extend(allowlisted_users) + paths.append('allowlisted_users') request = quantum.UpdateQuantumReservationRequest( name=name, @@ -1133,7 +1155,7 @@ async def update_reservation_async( ) return await self._send_request_async(self.grpc_client.update_quantum_reservation, request) - update_reservation = duet.sync(update_reservation_async) + update_reservation = duet.sync(update_reservation_async) # type: ignore[misc] async def list_time_slots_async( self, project_id: str, processor_id: str, filter_str: str = '' diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index ac77a4112da..9ca4eaf1ddc 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -28,6 +28,7 @@ from google.protobuf.field_mask_pb2 import FieldMask from google.protobuf.timestamp_pb2 import Timestamp +import cirq.testing import cirq_google.engine.stream_manager as engine_stream_manager from cirq_google.cloud import quantum from cirq_google.engine.engine_client import EngineClient, EngineException @@ -1530,7 +1531,7 @@ def test_create_reservation(client_constructor, default_engine_client): name='projects/proj/processors/processor0/reservations/papar-party-44', start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=users, + allowlisted_users=users, ) grpc_client.create_quantum_reservation.return_value = result @@ -1545,6 +1546,10 @@ def test_create_reservation(client_constructor, default_engine_client): parent='projects/proj/processors/processor0', quantum_reservation=result ) ) + with cirq.testing.assert_deprecated('Change whitelisted_users', deadline='v1.7'): + _ = default_engine_client.create_reservation( + 'proj', 'processor0', start, end, whitelisted_users=users + ) @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) @@ -1555,7 +1560,7 @@ def test_cancel_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) grpc_client.cancel_quantum_reservation.return_value = result @@ -1575,7 +1580,7 @@ def test_delete_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) grpc_client.delete_quantum_reservation.return_value = result @@ -1595,7 +1600,7 @@ def test_get_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) grpc_client.get_quantum_reservation.return_value = result @@ -1635,13 +1640,13 @@ def test_list_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ), quantum.QuantumReservation( name=name, start_time=Timestamp(seconds=1200000000), end_time=Timestamp(seconds=1200002000), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ), ] grpc_client.list_quantum_reservations.return_value = Pager(results) @@ -1657,7 +1662,7 @@ def test_update_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000001000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) grpc_client.update_quantum_reservation.return_value = result @@ -1668,7 +1673,7 @@ def test_update_reservation(client_constructor, default_engine_client): 'papar-party-44', start=datetime.datetime.fromtimestamp(1000001000), end=datetime.datetime.fromtimestamp(1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) == result ) @@ -1676,21 +1681,30 @@ def test_update_reservation(client_constructor, default_engine_client): quantum.UpdateQuantumReservationRequest( name=name, quantum_reservation=result, - update_mask=FieldMask(paths=['start_time', 'end_time', 'whitelisted_users']), + update_mask=FieldMask(paths=['start_time', 'end_time', 'allowlisted_users']), ) ) + with cirq.testing.assert_deprecated('Change whitelisted_users', deadline='v1.7'): + _ = default_engine_client.update_reservation( + 'proj', + 'processor0', + 'papar-party-44', + start=datetime.datetime.fromtimestamp(1000001000), + end=datetime.datetime.fromtimestamp(1000002000), + whitelisted_users=['jeff@google.com'], + ) @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) def test_update_reservation_remove_all_users(client_constructor, default_engine_client): grpc_client = _setup_client_mock(client_constructor) name = 'projects/proj/processors/processor0/reservations/papar-party-44' - result = quantum.QuantumReservation(name=name, whitelisted_users=[]) + result = quantum.QuantumReservation(name=name, allowlisted_users=[]) grpc_client.update_quantum_reservation.return_value = result assert ( default_engine_client.update_reservation( - 'proj', 'processor0', 'papar-party-44', whitelisted_users=[] + 'proj', 'processor0', 'papar-party-44', allowlisted_users=[] ) == result ) @@ -1698,7 +1712,7 @@ def test_update_reservation_remove_all_users(client_constructor, default_engine_ quantum.UpdateQuantumReservationRequest( name=name, quantum_reservation=result, - update_mask=FieldMask(paths=['whitelisted_users']), + update_mask=FieldMask(paths=['allowlisted_users']), ) ) diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 22a2a2c85d0..b23abc7a311 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -15,8 +15,9 @@ from __future__ import annotations import datetime -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING +from cirq import _compat from cirq_google.api import v2 from cirq_google.devices import grid_device from cirq_google.engine import abstract_processor, calibration, processor_sampler, util @@ -41,6 +42,13 @@ def _date_to_timestamp(union_time: datetime.datetime | datetime.date | int | Non return None +def _fix_deprecated_allowlisted_users_args( + args: tuple[Any, ...], kwargs: dict[str, Any] +) -> tuple[tuple[Any, ...], dict[str, Any]]: + kwargs['allowlisted_users'] = kwargs.pop('whitelisted_users') + return args, kwargs + + class EngineProcessor(abstract_processor.AbstractProcessor): """A processor available via the Quantum Engine API. @@ -320,23 +328,30 @@ def get_current_calibration(self) -> calibration.Calibration | None: else: return None + @_compat.deprecated_parameter( + deadline='v1.7', + fix='Change whitelisted_users to allowlisted_users.', + parameter_desc='whitelisted_users', + match=lambda args, kwargs: 'whitelisted_users' in kwargs, + rewrite=_fix_deprecated_allowlisted_users_args, + ) def create_reservation( self, start_time: datetime.datetime, end_time: datetime.datetime, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Creates a reservation on this processor. Args: start_time: the starting date/time of the reservation. end_time: the ending date/time of the reservation. - whitelisted_users: a list of emails that are allowed + allowlisted_users: a list of emails that are allowed to send programs during this reservation (in addition to users with permission "quantum.reservations.use" on the project). """ response = self.context.client.create_reservation( - self.project_id, self.processor_id, start_time, end_time, whitelisted_users + self.project_id, self.processor_id, start_time, end_time, allowlisted_users ) return response @@ -388,12 +403,19 @@ def get_reservation(self, reservation_id: str) -> quantum.QuantumReservation | N self.project_id, self.processor_id, reservation_id ) + @_compat.deprecated_parameter( + deadline='v1.7', + fix='Change whitelisted_users to allowlisted_users.', + parameter_desc='whitelisted_users', + match=lambda args, kwargs: 'whitelisted_users' in kwargs, + rewrite=_fix_deprecated_allowlisted_users_args, + ) def update_reservation( self, reservation_id: str, start_time: datetime.datetime | None = None, end_time: datetime.datetime | None = None, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Updates a reservation with new information. @@ -407,7 +429,7 @@ def update_reservation( reservation_id, start=start_time, end=end_time, - whitelisted_users=whitelisted_users, + allowlisted_users=allowlisted_users, ) def list_reservations( diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 79f03c56516..dee637b5e25 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -465,7 +465,7 @@ def test_create_reservation(create_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) create_reservation.return_value = result processor = cg.EngineProcessor('proj', 'p0', EngineContext()) @@ -481,6 +481,12 @@ def test_create_reservation(create_reservation): datetime.datetime.fromtimestamp(1000003600), ['dstrain@google.com'], ) + with cirq.testing.assert_deprecated('Change whitelisted_users', deadline='v1.7'): + _ = processor.create_reservation( + datetime.datetime.fromtimestamp(1000000000), + datetime.datetime.fromtimestamp(1000003600), + whitelisted_users=['dstrain@google.com'], + ) @mock.patch('cirq_google.engine.engine_client.EngineClient.delete_reservation_async') @@ -490,7 +496,7 @@ def test_delete_reservation(delete_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) delete_reservation.return_value = result processor = cg.EngineProcessor('proj', 'p0', EngineContext()) @@ -505,7 +511,7 @@ def test_cancel_reservation(cancel_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) cancel_reservation.return_value = result processor = cg.EngineProcessor('proj', 'p0', EngineContext()) @@ -522,7 +528,7 @@ def test_remove_reservation_delete(delete_reservation, get_reservation): name=name, start_time=Timestamp(seconds=now + 20000), end_time=Timestamp(seconds=now + 23610), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) get_reservation.return_value = result delete_reservation.return_value = result @@ -545,7 +551,7 @@ def test_remove_reservation_cancel(cancel_reservation, get_reservation): name=name, start_time=Timestamp(seconds=now + 10), end_time=Timestamp(seconds=now + 3610), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) get_reservation.return_value = result cancel_reservation.return_value = result @@ -581,7 +587,7 @@ def test_remove_reservation_failures(get_reservation, get_processor): name=name, start_time=Timestamp(seconds=now + 10), end_time=Timestamp(seconds=now + 3610), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) get_reservation.return_value = result get_processor.return_value = None @@ -604,7 +610,7 @@ def test_get_reservation(get_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) get_reservation.return_value = result processor = cg.EngineProcessor('proj', 'p0', EngineContext()) @@ -619,7 +625,7 @@ def test_update_reservation(update_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) start = datetime.datetime.fromtimestamp(1000000000) end = datetime.datetime.fromtimestamp(1000003600) @@ -627,8 +633,12 @@ def test_update_reservation(update_reservation): processor = cg.EngineProcessor('proj', 'p0', EngineContext()) assert processor.update_reservation('rid', start, end, ['dstrain@google.com']) == result update_reservation.assert_called_once_with( - 'proj', 'p0', 'rid', start=start, end=end, whitelisted_users=['dstrain@google.com'] + 'proj', 'p0', 'rid', start=start, end=end, allowlisted_users=['dstrain@google.com'] ) + with cirq.testing.assert_deprecated('Change whitelisted_users', deadline='v1.7'): + _ = processor.update_reservation( + 'rid', start, end, whitelisted_users=['dstrain@google.com'] + ) @mock.patch('cirq_google.engine.engine_client.EngineClient.list_reservations_async') @@ -639,13 +649,13 @@ def test_list_reservation(list_reservations): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ), quantum.QuantumReservation( name=name + '2', start_time=Timestamp(seconds=1000003600), end_time=Timestamp(seconds=1000007200), - whitelisted_users=['wcourtney@google.com'], + allowlisted_users=['wcourtney@google.com'], ), ] list_reservations.return_value = results diff --git a/dev_tools/notebooks/isolated_notebook_test.py b/dev_tools/notebooks/isolated_notebook_test.py index cfecaff9593..578389ca19f 100644 --- a/dev_tools/notebooks/isolated_notebook_test.py +++ b/dev_tools/notebooks/isolated_notebook_test.py @@ -67,6 +67,8 @@ # temporary: need to fix QVM metrics and device spec 'docs/tutorials/google/spin_echoes.ipynb', 'docs/tutorials/google/visualizing_calibration_metrics.ipynb', + # temporary: allow name changes of keyword arguments in quantum engine interfaces to stabilize + 'docs/simulate/virtual_engine_interface.ipynb', ] SKIP_NOTEBOOKS += [ # notebooks that import the examples module which is not installed with cirq diff --git a/docs/google/concepts.ipynb b/docs/google/concepts.ipynb index 2fd286aa311..a259b053438 100644 --- a/docs/google/concepts.ipynb +++ b/docs/google/concepts.ipynb @@ -269,7 +269,7 @@ "\n", "* OPEN_SWIM: Anyone with processor access may run jobs. There may be additional restrictions per processor that restrict large jobs.\n", "* MAINTENANCE: restrictions behave the same as during open swim, but there are no guarantees about the availability of the processor or quality of jobs run during this period.\n", - "* RESERVATION: The processor is reserved for restricted use by a user or set of users. Reservations are rooted under a project and editors of that project may run jobs during that project's reservations while using any project they wish. Additional users may also be whitelisted to specific reservations.\n", + "* RESERVATION: The processor is reserved for restricted use by a user or set of users. Reservations are rooted under a project and editors of that project may run jobs during that project's reservations while using any project they wish. Additional users may also be allowlisted to specific reservations.\n", "* UNALLOCATED: The processor has not been scheduled for any purpose. A reservation may be made during this time. If nothing is scheduled during this block, it will default to behaving as open swim.\n", "\n", "During non-reservation times, jobs are restricted to run for at most 5 minutes and may have no more than 1,500,000 total shots on the processor.\n", diff --git a/docs/simulate/virtual_engine_interface.ipynb b/docs/simulate/virtual_engine_interface.ipynb index 9872d7873d7..a77bb3028f0 100644 --- a/docs/simulate/virtual_engine_interface.ipynb +++ b/docs/simulate/virtual_engine_interface.ipynb @@ -94,13 +94,14 @@ "source": [ "try:\n", " import cirq\n", + " import cirq_google\n", "except ImportError:\n", " print(\"installing cirq...\")\n", - " !pip install --quiet cirq\n", + " !pip install --quiet cirq~=1.0.dev cirq-google~=1.0.dev\n", " print(\"installed cirq.\")\n", " import cirq\n", + " import cirq_google\n", "\n", - "import cirq_google\n", "import sympy" ] }, @@ -286,7 +287,7 @@ " weber.create_reservation(\n", " start_time=now + 2 * hour,\n", " end_time=now + 3 * hour,\n", - " whitelisted_users=['mysterious_fake_user@nonexistentwebsite.domain'],\n", + " allowlisted_users=['mysterious_fake_user@nonexistentwebsite.domain'],\n", " )\n", "except ValueError as e:\n", " # If you re-run this cell, it will note that you already have a reservation\n",