Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/pubsub_v1/services/subscriber/transports/rest.py: 33%
620 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:03 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:03 +0000
1# -*- coding: utf-8 -*-
2# Copyright 2022 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
17from google.auth.transport.requests import AuthorizedSession # type: ignore
18import json # type: ignore
19import grpc # type: ignore
20from google.auth.transport.grpc import SslCredentials # type: ignore
21from google.auth import credentials as ga_credentials # type: ignore
22from google.api_core import exceptions as core_exceptions
23from google.api_core import retry as retries
24from google.api_core import rest_helpers
25from google.api_core import rest_streaming
26from google.api_core import path_template
27from google.api_core import gapic_v1
29from google.protobuf import json_format
30from google.iam.v1 import iam_policy_pb2 # type: ignore
31from google.iam.v1 import policy_pb2 # type: ignore
32from requests import __version__ as requests_version
33import dataclasses
34import re
35from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
36import warnings
38try:
39 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
40except AttributeError: # pragma: NO COVER
41 OptionalRetry = Union[retries.Retry, object] # type: ignore
44from google.iam.v1 import iam_policy_pb2 # type: ignore
45from google.iam.v1 import policy_pb2 # type: ignore
46from google.protobuf import empty_pb2 # type: ignore
47from google.pubsub_v1.types import pubsub
49from .base import SubscriberTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
52DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
53 gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
54 grpc_version=None,
55 rest_version=requests_version,
56)
59class SubscriberRestInterceptor:
60 """Interceptor for Subscriber.
62 Interceptors are used to manipulate requests, request metadata, and responses
63 in arbitrary ways.
64 Example use cases include:
65 * Logging
66 * Verifying requests according to service or custom semantics
67 * Stripping extraneous information from responses
69 These use cases and more can be enabled by injecting an
70 instance of a custom subclass when constructing the SubscriberRestTransport.
72 .. code-block:: python
73 class MyCustomSubscriberInterceptor(SubscriberRestInterceptor):
74 def pre_acknowledge(self, request, metadata):
75 logging.log(f"Received request: {request}")
76 return request, metadata
78 def pre_create_snapshot(self, request, metadata):
79 logging.log(f"Received request: {request}")
80 return request, metadata
82 def post_create_snapshot(self, response):
83 logging.log(f"Received response: {response}")
84 return response
86 def pre_create_subscription(self, request, metadata):
87 logging.log(f"Received request: {request}")
88 return request, metadata
90 def post_create_subscription(self, response):
91 logging.log(f"Received response: {response}")
92 return response
94 def pre_delete_snapshot(self, request, metadata):
95 logging.log(f"Received request: {request}")
96 return request, metadata
98 def pre_delete_subscription(self, request, metadata):
99 logging.log(f"Received request: {request}")
100 return request, metadata
102 def pre_get_snapshot(self, request, metadata):
103 logging.log(f"Received request: {request}")
104 return request, metadata
106 def post_get_snapshot(self, response):
107 logging.log(f"Received response: {response}")
108 return response
110 def pre_get_subscription(self, request, metadata):
111 logging.log(f"Received request: {request}")
112 return request, metadata
114 def post_get_subscription(self, response):
115 logging.log(f"Received response: {response}")
116 return response
118 def pre_list_snapshots(self, request, metadata):
119 logging.log(f"Received request: {request}")
120 return request, metadata
122 def post_list_snapshots(self, response):
123 logging.log(f"Received response: {response}")
124 return response
126 def pre_list_subscriptions(self, request, metadata):
127 logging.log(f"Received request: {request}")
128 return request, metadata
130 def post_list_subscriptions(self, response):
131 logging.log(f"Received response: {response}")
132 return response
134 def pre_modify_ack_deadline(self, request, metadata):
135 logging.log(f"Received request: {request}")
136 return request, metadata
138 def pre_modify_push_config(self, request, metadata):
139 logging.log(f"Received request: {request}")
140 return request, metadata
142 def pre_pull(self, request, metadata):
143 logging.log(f"Received request: {request}")
144 return request, metadata
146 def post_pull(self, response):
147 logging.log(f"Received response: {response}")
148 return response
150 def pre_seek(self, request, metadata):
151 logging.log(f"Received request: {request}")
152 return request, metadata
154 def post_seek(self, response):
155 logging.log(f"Received response: {response}")
156 return response
158 def pre_update_snapshot(self, request, metadata):
159 logging.log(f"Received request: {request}")
160 return request, metadata
162 def post_update_snapshot(self, response):
163 logging.log(f"Received response: {response}")
164 return response
166 def pre_update_subscription(self, request, metadata):
167 logging.log(f"Received request: {request}")
168 return request, metadata
170 def post_update_subscription(self, response):
171 logging.log(f"Received response: {response}")
172 return response
174 transport = SubscriberRestTransport(interceptor=MyCustomSubscriberInterceptor())
175 client = SubscriberClient(transport=transport)
178 """
180 def pre_acknowledge(
181 self, request: pubsub.AcknowledgeRequest, metadata: Sequence[Tuple[str, str]]
182 ) -> Tuple[pubsub.AcknowledgeRequest, Sequence[Tuple[str, str]]]:
183 """Pre-rpc interceptor for acknowledge
185 Override in a subclass to manipulate the request or metadata
186 before they are sent to the Subscriber server.
187 """
188 return request, metadata
190 def pre_create_snapshot(
191 self, request: pubsub.CreateSnapshotRequest, metadata: Sequence[Tuple[str, str]]
192 ) -> Tuple[pubsub.CreateSnapshotRequest, Sequence[Tuple[str, str]]]:
193 """Pre-rpc interceptor for create_snapshot
195 Override in a subclass to manipulate the request or metadata
196 before they are sent to the Subscriber server.
197 """
198 return request, metadata
200 def post_create_snapshot(self, response: pubsub.Snapshot) -> pubsub.Snapshot:
201 """Post-rpc interceptor for create_snapshot
203 Override in a subclass to manipulate the response
204 after it is returned by the Subscriber server but before
205 it is returned to user code.
206 """
207 return response
209 def pre_create_subscription(
210 self, request: pubsub.Subscription, metadata: Sequence[Tuple[str, str]]
211 ) -> Tuple[pubsub.Subscription, Sequence[Tuple[str, str]]]:
212 """Pre-rpc interceptor for create_subscription
214 Override in a subclass to manipulate the request or metadata
215 before they are sent to the Subscriber server.
216 """
217 return request, metadata
219 def post_create_subscription(
220 self, response: pubsub.Subscription
221 ) -> pubsub.Subscription:
222 """Post-rpc interceptor for create_subscription
224 Override in a subclass to manipulate the response
225 after it is returned by the Subscriber server but before
226 it is returned to user code.
227 """
228 return response
230 def pre_delete_snapshot(
231 self, request: pubsub.DeleteSnapshotRequest, metadata: Sequence[Tuple[str, str]]
232 ) -> Tuple[pubsub.DeleteSnapshotRequest, Sequence[Tuple[str, str]]]:
233 """Pre-rpc interceptor for delete_snapshot
235 Override in a subclass to manipulate the request or metadata
236 before they are sent to the Subscriber server.
237 """
238 return request, metadata
240 def pre_delete_subscription(
241 self,
242 request: pubsub.DeleteSubscriptionRequest,
243 metadata: Sequence[Tuple[str, str]],
244 ) -> Tuple[pubsub.DeleteSubscriptionRequest, Sequence[Tuple[str, str]]]:
245 """Pre-rpc interceptor for delete_subscription
247 Override in a subclass to manipulate the request or metadata
248 before they are sent to the Subscriber server.
249 """
250 return request, metadata
252 def pre_get_snapshot(
253 self, request: pubsub.GetSnapshotRequest, metadata: Sequence[Tuple[str, str]]
254 ) -> Tuple[pubsub.GetSnapshotRequest, Sequence[Tuple[str, str]]]:
255 """Pre-rpc interceptor for get_snapshot
257 Override in a subclass to manipulate the request or metadata
258 before they are sent to the Subscriber server.
259 """
260 return request, metadata
262 def post_get_snapshot(self, response: pubsub.Snapshot) -> pubsub.Snapshot:
263 """Post-rpc interceptor for get_snapshot
265 Override in a subclass to manipulate the response
266 after it is returned by the Subscriber server but before
267 it is returned to user code.
268 """
269 return response
271 def pre_get_subscription(
272 self,
273 request: pubsub.GetSubscriptionRequest,
274 metadata: Sequence[Tuple[str, str]],
275 ) -> Tuple[pubsub.GetSubscriptionRequest, Sequence[Tuple[str, str]]]:
276 """Pre-rpc interceptor for get_subscription
278 Override in a subclass to manipulate the request or metadata
279 before they are sent to the Subscriber server.
280 """
281 return request, metadata
283 def post_get_subscription(
284 self, response: pubsub.Subscription
285 ) -> pubsub.Subscription:
286 """Post-rpc interceptor for get_subscription
288 Override in a subclass to manipulate the response
289 after it is returned by the Subscriber server but before
290 it is returned to user code.
291 """
292 return response
294 def pre_list_snapshots(
295 self, request: pubsub.ListSnapshotsRequest, metadata: Sequence[Tuple[str, str]]
296 ) -> Tuple[pubsub.ListSnapshotsRequest, Sequence[Tuple[str, str]]]:
297 """Pre-rpc interceptor for list_snapshots
299 Override in a subclass to manipulate the request or metadata
300 before they are sent to the Subscriber server.
301 """
302 return request, metadata
304 def post_list_snapshots(
305 self, response: pubsub.ListSnapshotsResponse
306 ) -> pubsub.ListSnapshotsResponse:
307 """Post-rpc interceptor for list_snapshots
309 Override in a subclass to manipulate the response
310 after it is returned by the Subscriber server but before
311 it is returned to user code.
312 """
313 return response
315 def pre_list_subscriptions(
316 self,
317 request: pubsub.ListSubscriptionsRequest,
318 metadata: Sequence[Tuple[str, str]],
319 ) -> Tuple[pubsub.ListSubscriptionsRequest, Sequence[Tuple[str, str]]]:
320 """Pre-rpc interceptor for list_subscriptions
322 Override in a subclass to manipulate the request or metadata
323 before they are sent to the Subscriber server.
324 """
325 return request, metadata
327 def post_list_subscriptions(
328 self, response: pubsub.ListSubscriptionsResponse
329 ) -> pubsub.ListSubscriptionsResponse:
330 """Post-rpc interceptor for list_subscriptions
332 Override in a subclass to manipulate the response
333 after it is returned by the Subscriber server but before
334 it is returned to user code.
335 """
336 return response
338 def pre_modify_ack_deadline(
339 self,
340 request: pubsub.ModifyAckDeadlineRequest,
341 metadata: Sequence[Tuple[str, str]],
342 ) -> Tuple[pubsub.ModifyAckDeadlineRequest, Sequence[Tuple[str, str]]]:
343 """Pre-rpc interceptor for modify_ack_deadline
345 Override in a subclass to manipulate the request or metadata
346 before they are sent to the Subscriber server.
347 """
348 return request, metadata
350 def pre_modify_push_config(
351 self,
352 request: pubsub.ModifyPushConfigRequest,
353 metadata: Sequence[Tuple[str, str]],
354 ) -> Tuple[pubsub.ModifyPushConfigRequest, Sequence[Tuple[str, str]]]:
355 """Pre-rpc interceptor for modify_push_config
357 Override in a subclass to manipulate the request or metadata
358 before they are sent to the Subscriber server.
359 """
360 return request, metadata
362 def pre_pull(
363 self, request: pubsub.PullRequest, metadata: Sequence[Tuple[str, str]]
364 ) -> Tuple[pubsub.PullRequest, Sequence[Tuple[str, str]]]:
365 """Pre-rpc interceptor for pull
367 Override in a subclass to manipulate the request or metadata
368 before they are sent to the Subscriber server.
369 """
370 return request, metadata
372 def post_pull(self, response: pubsub.PullResponse) -> pubsub.PullResponse:
373 """Post-rpc interceptor for pull
375 Override in a subclass to manipulate the response
376 after it is returned by the Subscriber server but before
377 it is returned to user code.
378 """
379 return response
381 def pre_seek(
382 self, request: pubsub.SeekRequest, metadata: Sequence[Tuple[str, str]]
383 ) -> Tuple[pubsub.SeekRequest, Sequence[Tuple[str, str]]]:
384 """Pre-rpc interceptor for seek
386 Override in a subclass to manipulate the request or metadata
387 before they are sent to the Subscriber server.
388 """
389 return request, metadata
391 def post_seek(self, response: pubsub.SeekResponse) -> pubsub.SeekResponse:
392 """Post-rpc interceptor for seek
394 Override in a subclass to manipulate the response
395 after it is returned by the Subscriber server but before
396 it is returned to user code.
397 """
398 return response
400 def pre_update_snapshot(
401 self, request: pubsub.UpdateSnapshotRequest, metadata: Sequence[Tuple[str, str]]
402 ) -> Tuple[pubsub.UpdateSnapshotRequest, Sequence[Tuple[str, str]]]:
403 """Pre-rpc interceptor for update_snapshot
405 Override in a subclass to manipulate the request or metadata
406 before they are sent to the Subscriber server.
407 """
408 return request, metadata
410 def post_update_snapshot(self, response: pubsub.Snapshot) -> pubsub.Snapshot:
411 """Post-rpc interceptor for update_snapshot
413 Override in a subclass to manipulate the response
414 after it is returned by the Subscriber server but before
415 it is returned to user code.
416 """
417 return response
419 def pre_update_subscription(
420 self,
421 request: pubsub.UpdateSubscriptionRequest,
422 metadata: Sequence[Tuple[str, str]],
423 ) -> Tuple[pubsub.UpdateSubscriptionRequest, Sequence[Tuple[str, str]]]:
424 """Pre-rpc interceptor for update_subscription
426 Override in a subclass to manipulate the request or metadata
427 before they are sent to the Subscriber server.
428 """
429 return request, metadata
431 def post_update_subscription(
432 self, response: pubsub.Subscription
433 ) -> pubsub.Subscription:
434 """Post-rpc interceptor for update_subscription
436 Override in a subclass to manipulate the response
437 after it is returned by the Subscriber server but before
438 it is returned to user code.
439 """
440 return response
442 def pre_get_iam_policy(
443 self,
444 request: iam_policy_pb2.GetIamPolicyRequest,
445 metadata: Sequence[Tuple[str, str]],
446 ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]:
447 """Pre-rpc interceptor for get_iam_policy
449 Override in a subclass to manipulate the request or metadata
450 before they are sent to the Subscriber server.
451 """
452 return request, metadata
454 def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
455 """Post-rpc interceptor for get_iam_policy
457 Override in a subclass to manipulate the response
458 after it is returned by the Subscriber server but before
459 it is returned to user code.
460 """
461 return response
463 def pre_set_iam_policy(
464 self,
465 request: iam_policy_pb2.SetIamPolicyRequest,
466 metadata: Sequence[Tuple[str, str]],
467 ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]:
468 """Pre-rpc interceptor for set_iam_policy
470 Override in a subclass to manipulate the request or metadata
471 before they are sent to the Subscriber server.
472 """
473 return request, metadata
475 def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
476 """Post-rpc interceptor for set_iam_policy
478 Override in a subclass to manipulate the response
479 after it is returned by the Subscriber server but before
480 it is returned to user code.
481 """
482 return response
484 def pre_test_iam_permissions(
485 self,
486 request: iam_policy_pb2.TestIamPermissionsRequest,
487 metadata: Sequence[Tuple[str, str]],
488 ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]:
489 """Pre-rpc interceptor for test_iam_permissions
491 Override in a subclass to manipulate the request or metadata
492 before they are sent to the Subscriber server.
493 """
494 return request, metadata
496 def post_test_iam_permissions(
497 self, response: iam_policy_pb2.TestIamPermissionsResponse
498 ) -> iam_policy_pb2.TestIamPermissionsResponse:
499 """Post-rpc interceptor for test_iam_permissions
501 Override in a subclass to manipulate the response
502 after it is returned by the Subscriber server but before
503 it is returned to user code.
504 """
505 return response
508@dataclasses.dataclass
509class SubscriberRestStub:
510 _session: AuthorizedSession
511 _host: str
512 _interceptor: SubscriberRestInterceptor
515class SubscriberRestTransport(SubscriberTransport):
516 """REST backend transport for Subscriber.
518 The service that an application uses to manipulate subscriptions and
519 to consume messages from a subscription via the ``Pull`` method or
520 by establishing a bi-directional stream using the ``StreamingPull``
521 method.
523 This class defines the same methods as the primary client, so the
524 primary client can load the underlying transport implementation
525 and call it.
527 It sends JSON representations of protocol buffers over HTTP/1.1
529 """
531 def __init__(
532 self,
533 *,
534 host: str = "pubsub.googleapis.com",
535 credentials: Optional[ga_credentials.Credentials] = None,
536 credentials_file: Optional[str] = None,
537 scopes: Optional[Sequence[str]] = None,
538 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
539 quota_project_id: Optional[str] = None,
540 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
541 always_use_jwt_access: Optional[bool] = False,
542 url_scheme: str = "https",
543 interceptor: Optional[SubscriberRestInterceptor] = None,
544 api_audience: Optional[str] = None,
545 ) -> None:
546 """Instantiate the transport.
548 Args:
549 host (Optional[str]):
550 The hostname to connect to.
551 credentials (Optional[google.auth.credentials.Credentials]): The
552 authorization credentials to attach to requests. These
553 credentials identify the application to the service; if none
554 are specified, the client will attempt to ascertain the
555 credentials from the environment.
557 credentials_file (Optional[str]): A file with credentials that can
558 be loaded with :func:`google.auth.load_credentials_from_file`.
559 This argument is ignored if ``channel`` is provided.
560 scopes (Optional(Sequence[str])): A list of scopes. This argument is
561 ignored if ``channel`` is provided.
562 client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
563 certificate to configure mutual TLS HTTP channel. It is ignored
564 if ``channel`` is provided.
565 quota_project_id (Optional[str]): An optional project to use for billing
566 and quota.
567 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
568 The client info used to send a user-agent string along with
569 API requests. If ``None``, then default info will be used.
570 Generally, you only need to set this if you are developing
571 your own client library.
572 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
573 be used for service account credentials.
574 url_scheme: the protocol scheme for the API endpoint. Normally
575 "https", but for testing or local servers,
576 "http" can be specified.
577 """
578 # Run the base constructor
579 # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
580 # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
581 # credentials object
582 maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
583 if maybe_url_match is None:
584 raise ValueError(
585 f"Unexpected hostname structure: {host}"
586 ) # pragma: NO COVER
588 url_match_items = maybe_url_match.groupdict()
590 host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
592 super().__init__(
593 host=host,
594 credentials=credentials,
595 client_info=client_info,
596 always_use_jwt_access=always_use_jwt_access,
597 api_audience=api_audience,
598 )
599 self._session = AuthorizedSession(
600 self._credentials, default_host=self.DEFAULT_HOST
601 )
602 if client_cert_source_for_mtls:
603 self._session.configure_mtls_channel(client_cert_source_for_mtls)
604 self._interceptor = interceptor or SubscriberRestInterceptor()
605 self._prep_wrapped_messages(client_info)
607 class _Acknowledge(SubscriberRestStub):
608 def __hash__(self):
609 return hash("Acknowledge")
611 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
613 @classmethod
614 def _get_unset_required_fields(cls, message_dict):
615 return {
616 k: v
617 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
618 if k not in message_dict
619 }
621 def __call__(
622 self,
623 request: pubsub.AcknowledgeRequest,
624 *,
625 retry: OptionalRetry = gapic_v1.method.DEFAULT,
626 timeout: Optional[float] = None,
627 metadata: Sequence[Tuple[str, str]] = (),
628 ):
629 r"""Call the acknowledge method over HTTP.
631 Args:
632 request (~.pubsub.AcknowledgeRequest):
633 The request object. Request for the Acknowledge method.
634 retry (google.api_core.retry.Retry): Designation of what errors, if any,
635 should be retried.
636 timeout (float): The timeout for this request.
637 metadata (Sequence[Tuple[str, str]]): Strings which should be
638 sent along with the request as metadata.
639 """
641 http_options: List[Dict[str, str]] = [
642 {
643 "method": "post",
644 "uri": "/v1/{subscription=projects/*/subscriptions/*}:acknowledge",
645 "body": "*",
646 },
647 ]
648 request, metadata = self._interceptor.pre_acknowledge(request, metadata)
649 pb_request = pubsub.AcknowledgeRequest.pb(request)
650 transcoded_request = path_template.transcode(http_options, pb_request)
652 # Jsonify the request body
654 body = json_format.MessageToJson(
655 transcoded_request["body"],
656 including_default_value_fields=False,
657 use_integers_for_enums=True,
658 )
659 uri = transcoded_request["uri"]
660 method = transcoded_request["method"]
662 # Jsonify the query params
663 query_params = json.loads(
664 json_format.MessageToJson(
665 transcoded_request["query_params"],
666 including_default_value_fields=False,
667 use_integers_for_enums=True,
668 )
669 )
670 query_params.update(self._get_unset_required_fields(query_params))
672 query_params["$alt"] = "json;enum-encoding=int"
674 # Send the request
675 headers = dict(metadata)
676 headers["Content-Type"] = "application/json"
677 response = getattr(self._session, method)(
678 "{host}{uri}".format(host=self._host, uri=uri),
679 timeout=timeout,
680 headers=headers,
681 params=rest_helpers.flatten_query_params(query_params, strict=True),
682 data=body,
683 )
685 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
686 # subclass.
687 if response.status_code >= 400:
688 raise core_exceptions.from_http_response(response)
690 class _CreateSnapshot(SubscriberRestStub):
691 def __hash__(self):
692 return hash("CreateSnapshot")
694 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
696 @classmethod
697 def _get_unset_required_fields(cls, message_dict):
698 return {
699 k: v
700 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
701 if k not in message_dict
702 }
704 def __call__(
705 self,
706 request: pubsub.CreateSnapshotRequest,
707 *,
708 retry: OptionalRetry = gapic_v1.method.DEFAULT,
709 timeout: Optional[float] = None,
710 metadata: Sequence[Tuple[str, str]] = (),
711 ) -> pubsub.Snapshot:
712 r"""Call the create snapshot method over HTTP.
714 Args:
715 request (~.pubsub.CreateSnapshotRequest):
716 The request object. Request for the ``CreateSnapshot`` method.
717 retry (google.api_core.retry.Retry): Designation of what errors, if any,
718 should be retried.
719 timeout (float): The timeout for this request.
720 metadata (Sequence[Tuple[str, str]]): Strings which should be
721 sent along with the request as metadata.
723 Returns:
724 ~.pubsub.Snapshot:
725 A snapshot resource. Snapshots are used in
726 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
727 operations, which allow you to manage message
728 acknowledgments in bulk. That is, you can set the
729 acknowledgment state of messages in an existing
730 subscription to the state captured by a snapshot.
732 """
734 http_options: List[Dict[str, str]] = [
735 {
736 "method": "put",
737 "uri": "/v1/{name=projects/*/snapshots/*}",
738 "body": "*",
739 },
740 ]
741 request, metadata = self._interceptor.pre_create_snapshot(request, metadata)
742 pb_request = pubsub.CreateSnapshotRequest.pb(request)
743 transcoded_request = path_template.transcode(http_options, pb_request)
745 # Jsonify the request body
747 body = json_format.MessageToJson(
748 transcoded_request["body"],
749 including_default_value_fields=False,
750 use_integers_for_enums=True,
751 )
752 uri = transcoded_request["uri"]
753 method = transcoded_request["method"]
755 # Jsonify the query params
756 query_params = json.loads(
757 json_format.MessageToJson(
758 transcoded_request["query_params"],
759 including_default_value_fields=False,
760 use_integers_for_enums=True,
761 )
762 )
763 query_params.update(self._get_unset_required_fields(query_params))
765 query_params["$alt"] = "json;enum-encoding=int"
767 # Send the request
768 headers = dict(metadata)
769 headers["Content-Type"] = "application/json"
770 response = getattr(self._session, method)(
771 "{host}{uri}".format(host=self._host, uri=uri),
772 timeout=timeout,
773 headers=headers,
774 params=rest_helpers.flatten_query_params(query_params, strict=True),
775 data=body,
776 )
778 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
779 # subclass.
780 if response.status_code >= 400:
781 raise core_exceptions.from_http_response(response)
783 # Return the response
784 resp = pubsub.Snapshot()
785 pb_resp = pubsub.Snapshot.pb(resp)
787 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
788 resp = self._interceptor.post_create_snapshot(resp)
789 return resp
791 class _CreateSubscription(SubscriberRestStub):
792 def __hash__(self):
793 return hash("CreateSubscription")
795 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
797 @classmethod
798 def _get_unset_required_fields(cls, message_dict):
799 return {
800 k: v
801 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
802 if k not in message_dict
803 }
805 def __call__(
806 self,
807 request: pubsub.Subscription,
808 *,
809 retry: OptionalRetry = gapic_v1.method.DEFAULT,
810 timeout: Optional[float] = None,
811 metadata: Sequence[Tuple[str, str]] = (),
812 ) -> pubsub.Subscription:
813 r"""Call the create subscription method over HTTP.
815 Args:
816 request (~.pubsub.Subscription):
817 The request object. A subscription resource. If none of ``push_config``,
818 ``bigquery_config``, or ``cloud_storage_config`` is set,
819 then the subscriber will pull and ack messages using API
820 methods. At most one of these fields may be set.
821 retry (google.api_core.retry.Retry): Designation of what errors, if any,
822 should be retried.
823 timeout (float): The timeout for this request.
824 metadata (Sequence[Tuple[str, str]]): Strings which should be
825 sent along with the request as metadata.
827 Returns:
828 ~.pubsub.Subscription:
829 A subscription resource. If none of ``push_config``,
830 ``bigquery_config``, or ``cloud_storage_config`` is set,
831 then the subscriber will pull and ack messages using API
832 methods. At most one of these fields may be set.
834 """
836 http_options: List[Dict[str, str]] = [
837 {
838 "method": "put",
839 "uri": "/v1/{name=projects/*/subscriptions/*}",
840 "body": "*",
841 },
842 ]
843 request, metadata = self._interceptor.pre_create_subscription(
844 request, metadata
845 )
846 pb_request = pubsub.Subscription.pb(request)
847 transcoded_request = path_template.transcode(http_options, pb_request)
849 # Jsonify the request body
851 body = json_format.MessageToJson(
852 transcoded_request["body"],
853 including_default_value_fields=False,
854 use_integers_for_enums=True,
855 )
856 uri = transcoded_request["uri"]
857 method = transcoded_request["method"]
859 # Jsonify the query params
860 query_params = json.loads(
861 json_format.MessageToJson(
862 transcoded_request["query_params"],
863 including_default_value_fields=False,
864 use_integers_for_enums=True,
865 )
866 )
867 query_params.update(self._get_unset_required_fields(query_params))
869 query_params["$alt"] = "json;enum-encoding=int"
871 # Send the request
872 headers = dict(metadata)
873 headers["Content-Type"] = "application/json"
874 response = getattr(self._session, method)(
875 "{host}{uri}".format(host=self._host, uri=uri),
876 timeout=timeout,
877 headers=headers,
878 params=rest_helpers.flatten_query_params(query_params, strict=True),
879 data=body,
880 )
882 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
883 # subclass.
884 if response.status_code >= 400:
885 raise core_exceptions.from_http_response(response)
887 # Return the response
888 resp = pubsub.Subscription()
889 pb_resp = pubsub.Subscription.pb(resp)
891 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
892 resp = self._interceptor.post_create_subscription(resp)
893 return resp
895 class _DeleteSnapshot(SubscriberRestStub):
896 def __hash__(self):
897 return hash("DeleteSnapshot")
899 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
901 @classmethod
902 def _get_unset_required_fields(cls, message_dict):
903 return {
904 k: v
905 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
906 if k not in message_dict
907 }
909 def __call__(
910 self,
911 request: pubsub.DeleteSnapshotRequest,
912 *,
913 retry: OptionalRetry = gapic_v1.method.DEFAULT,
914 timeout: Optional[float] = None,
915 metadata: Sequence[Tuple[str, str]] = (),
916 ):
917 r"""Call the delete snapshot method over HTTP.
919 Args:
920 request (~.pubsub.DeleteSnapshotRequest):
921 The request object. Request for the ``DeleteSnapshot`` method.
922 retry (google.api_core.retry.Retry): Designation of what errors, if any,
923 should be retried.
924 timeout (float): The timeout for this request.
925 metadata (Sequence[Tuple[str, str]]): Strings which should be
926 sent along with the request as metadata.
927 """
929 http_options: List[Dict[str, str]] = [
930 {
931 "method": "delete",
932 "uri": "/v1/{snapshot=projects/*/snapshots/*}",
933 },
934 ]
935 request, metadata = self._interceptor.pre_delete_snapshot(request, metadata)
936 pb_request = pubsub.DeleteSnapshotRequest.pb(request)
937 transcoded_request = path_template.transcode(http_options, pb_request)
939 uri = transcoded_request["uri"]
940 method = transcoded_request["method"]
942 # Jsonify the query params
943 query_params = json.loads(
944 json_format.MessageToJson(
945 transcoded_request["query_params"],
946 including_default_value_fields=False,
947 use_integers_for_enums=True,
948 )
949 )
950 query_params.update(self._get_unset_required_fields(query_params))
952 query_params["$alt"] = "json;enum-encoding=int"
954 # Send the request
955 headers = dict(metadata)
956 headers["Content-Type"] = "application/json"
957 response = getattr(self._session, method)(
958 "{host}{uri}".format(host=self._host, uri=uri),
959 timeout=timeout,
960 headers=headers,
961 params=rest_helpers.flatten_query_params(query_params, strict=True),
962 )
964 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
965 # subclass.
966 if response.status_code >= 400:
967 raise core_exceptions.from_http_response(response)
969 class _DeleteSubscription(SubscriberRestStub):
970 def __hash__(self):
971 return hash("DeleteSubscription")
973 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
975 @classmethod
976 def _get_unset_required_fields(cls, message_dict):
977 return {
978 k: v
979 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
980 if k not in message_dict
981 }
983 def __call__(
984 self,
985 request: pubsub.DeleteSubscriptionRequest,
986 *,
987 retry: OptionalRetry = gapic_v1.method.DEFAULT,
988 timeout: Optional[float] = None,
989 metadata: Sequence[Tuple[str, str]] = (),
990 ):
991 r"""Call the delete subscription method over HTTP.
993 Args:
994 request (~.pubsub.DeleteSubscriptionRequest):
995 The request object. Request for the DeleteSubscription
996 method.
997 retry (google.api_core.retry.Retry): Designation of what errors, if any,
998 should be retried.
999 timeout (float): The timeout for this request.
1000 metadata (Sequence[Tuple[str, str]]): Strings which should be
1001 sent along with the request as metadata.
1002 """
1004 http_options: List[Dict[str, str]] = [
1005 {
1006 "method": "delete",
1007 "uri": "/v1/{subscription=projects/*/subscriptions/*}",
1008 },
1009 ]
1010 request, metadata = self._interceptor.pre_delete_subscription(
1011 request, metadata
1012 )
1013 pb_request = pubsub.DeleteSubscriptionRequest.pb(request)
1014 transcoded_request = path_template.transcode(http_options, pb_request)
1016 uri = transcoded_request["uri"]
1017 method = transcoded_request["method"]
1019 # Jsonify the query params
1020 query_params = json.loads(
1021 json_format.MessageToJson(
1022 transcoded_request["query_params"],
1023 including_default_value_fields=False,
1024 use_integers_for_enums=True,
1025 )
1026 )
1027 query_params.update(self._get_unset_required_fields(query_params))
1029 query_params["$alt"] = "json;enum-encoding=int"
1031 # Send the request
1032 headers = dict(metadata)
1033 headers["Content-Type"] = "application/json"
1034 response = getattr(self._session, method)(
1035 "{host}{uri}".format(host=self._host, uri=uri),
1036 timeout=timeout,
1037 headers=headers,
1038 params=rest_helpers.flatten_query_params(query_params, strict=True),
1039 )
1041 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1042 # subclass.
1043 if response.status_code >= 400:
1044 raise core_exceptions.from_http_response(response)
1046 class _GetSnapshot(SubscriberRestStub):
1047 def __hash__(self):
1048 return hash("GetSnapshot")
1050 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1052 @classmethod
1053 def _get_unset_required_fields(cls, message_dict):
1054 return {
1055 k: v
1056 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1057 if k not in message_dict
1058 }
1060 def __call__(
1061 self,
1062 request: pubsub.GetSnapshotRequest,
1063 *,
1064 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1065 timeout: Optional[float] = None,
1066 metadata: Sequence[Tuple[str, str]] = (),
1067 ) -> pubsub.Snapshot:
1068 r"""Call the get snapshot method over HTTP.
1070 Args:
1071 request (~.pubsub.GetSnapshotRequest):
1072 The request object. Request for the GetSnapshot method.
1073 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1074 should be retried.
1075 timeout (float): The timeout for this request.
1076 metadata (Sequence[Tuple[str, str]]): Strings which should be
1077 sent along with the request as metadata.
1079 Returns:
1080 ~.pubsub.Snapshot:
1081 A snapshot resource. Snapshots are used in
1082 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1083 operations, which allow you to manage message
1084 acknowledgments in bulk. That is, you can set the
1085 acknowledgment state of messages in an existing
1086 subscription to the state captured by a snapshot.
1088 """
1090 http_options: List[Dict[str, str]] = [
1091 {
1092 "method": "get",
1093 "uri": "/v1/{snapshot=projects/*/snapshots/*}",
1094 },
1095 ]
1096 request, metadata = self._interceptor.pre_get_snapshot(request, metadata)
1097 pb_request = pubsub.GetSnapshotRequest.pb(request)
1098 transcoded_request = path_template.transcode(http_options, pb_request)
1100 uri = transcoded_request["uri"]
1101 method = transcoded_request["method"]
1103 # Jsonify the query params
1104 query_params = json.loads(
1105 json_format.MessageToJson(
1106 transcoded_request["query_params"],
1107 including_default_value_fields=False,
1108 use_integers_for_enums=True,
1109 )
1110 )
1111 query_params.update(self._get_unset_required_fields(query_params))
1113 query_params["$alt"] = "json;enum-encoding=int"
1115 # Send the request
1116 headers = dict(metadata)
1117 headers["Content-Type"] = "application/json"
1118 response = getattr(self._session, method)(
1119 "{host}{uri}".format(host=self._host, uri=uri),
1120 timeout=timeout,
1121 headers=headers,
1122 params=rest_helpers.flatten_query_params(query_params, strict=True),
1123 )
1125 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1126 # subclass.
1127 if response.status_code >= 400:
1128 raise core_exceptions.from_http_response(response)
1130 # Return the response
1131 resp = pubsub.Snapshot()
1132 pb_resp = pubsub.Snapshot.pb(resp)
1134 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1135 resp = self._interceptor.post_get_snapshot(resp)
1136 return resp
1138 class _GetSubscription(SubscriberRestStub):
1139 def __hash__(self):
1140 return hash("GetSubscription")
1142 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1144 @classmethod
1145 def _get_unset_required_fields(cls, message_dict):
1146 return {
1147 k: v
1148 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1149 if k not in message_dict
1150 }
1152 def __call__(
1153 self,
1154 request: pubsub.GetSubscriptionRequest,
1155 *,
1156 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1157 timeout: Optional[float] = None,
1158 metadata: Sequence[Tuple[str, str]] = (),
1159 ) -> pubsub.Subscription:
1160 r"""Call the get subscription method over HTTP.
1162 Args:
1163 request (~.pubsub.GetSubscriptionRequest):
1164 The request object. Request for the GetSubscription
1165 method.
1166 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1167 should be retried.
1168 timeout (float): The timeout for this request.
1169 metadata (Sequence[Tuple[str, str]]): Strings which should be
1170 sent along with the request as metadata.
1172 Returns:
1173 ~.pubsub.Subscription:
1174 A subscription resource. If none of ``push_config``,
1175 ``bigquery_config``, or ``cloud_storage_config`` is set,
1176 then the subscriber will pull and ack messages using API
1177 methods. At most one of these fields may be set.
1179 """
1181 http_options: List[Dict[str, str]] = [
1182 {
1183 "method": "get",
1184 "uri": "/v1/{subscription=projects/*/subscriptions/*}",
1185 },
1186 ]
1187 request, metadata = self._interceptor.pre_get_subscription(
1188 request, metadata
1189 )
1190 pb_request = pubsub.GetSubscriptionRequest.pb(request)
1191 transcoded_request = path_template.transcode(http_options, pb_request)
1193 uri = transcoded_request["uri"]
1194 method = transcoded_request["method"]
1196 # Jsonify the query params
1197 query_params = json.loads(
1198 json_format.MessageToJson(
1199 transcoded_request["query_params"],
1200 including_default_value_fields=False,
1201 use_integers_for_enums=True,
1202 )
1203 )
1204 query_params.update(self._get_unset_required_fields(query_params))
1206 query_params["$alt"] = "json;enum-encoding=int"
1208 # Send the request
1209 headers = dict(metadata)
1210 headers["Content-Type"] = "application/json"
1211 response = getattr(self._session, method)(
1212 "{host}{uri}".format(host=self._host, uri=uri),
1213 timeout=timeout,
1214 headers=headers,
1215 params=rest_helpers.flatten_query_params(query_params, strict=True),
1216 )
1218 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1219 # subclass.
1220 if response.status_code >= 400:
1221 raise core_exceptions.from_http_response(response)
1223 # Return the response
1224 resp = pubsub.Subscription()
1225 pb_resp = pubsub.Subscription.pb(resp)
1227 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1228 resp = self._interceptor.post_get_subscription(resp)
1229 return resp
1231 class _ListSnapshots(SubscriberRestStub):
1232 def __hash__(self):
1233 return hash("ListSnapshots")
1235 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1237 @classmethod
1238 def _get_unset_required_fields(cls, message_dict):
1239 return {
1240 k: v
1241 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1242 if k not in message_dict
1243 }
1245 def __call__(
1246 self,
1247 request: pubsub.ListSnapshotsRequest,
1248 *,
1249 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1250 timeout: Optional[float] = None,
1251 metadata: Sequence[Tuple[str, str]] = (),
1252 ) -> pubsub.ListSnapshotsResponse:
1253 r"""Call the list snapshots method over HTTP.
1255 Args:
1256 request (~.pubsub.ListSnapshotsRequest):
1257 The request object. Request for the ``ListSnapshots`` method.
1258 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1259 should be retried.
1260 timeout (float): The timeout for this request.
1261 metadata (Sequence[Tuple[str, str]]): Strings which should be
1262 sent along with the request as metadata.
1264 Returns:
1265 ~.pubsub.ListSnapshotsResponse:
1266 Response for the ``ListSnapshots`` method.
1267 """
1269 http_options: List[Dict[str, str]] = [
1270 {
1271 "method": "get",
1272 "uri": "/v1/{project=projects/*}/snapshots",
1273 },
1274 ]
1275 request, metadata = self._interceptor.pre_list_snapshots(request, metadata)
1276 pb_request = pubsub.ListSnapshotsRequest.pb(request)
1277 transcoded_request = path_template.transcode(http_options, pb_request)
1279 uri = transcoded_request["uri"]
1280 method = transcoded_request["method"]
1282 # Jsonify the query params
1283 query_params = json.loads(
1284 json_format.MessageToJson(
1285 transcoded_request["query_params"],
1286 including_default_value_fields=False,
1287 use_integers_for_enums=True,
1288 )
1289 )
1290 query_params.update(self._get_unset_required_fields(query_params))
1292 query_params["$alt"] = "json;enum-encoding=int"
1294 # Send the request
1295 headers = dict(metadata)
1296 headers["Content-Type"] = "application/json"
1297 response = getattr(self._session, method)(
1298 "{host}{uri}".format(host=self._host, uri=uri),
1299 timeout=timeout,
1300 headers=headers,
1301 params=rest_helpers.flatten_query_params(query_params, strict=True),
1302 )
1304 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1305 # subclass.
1306 if response.status_code >= 400:
1307 raise core_exceptions.from_http_response(response)
1309 # Return the response
1310 resp = pubsub.ListSnapshotsResponse()
1311 pb_resp = pubsub.ListSnapshotsResponse.pb(resp)
1313 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1314 resp = self._interceptor.post_list_snapshots(resp)
1315 return resp
1317 class _ListSubscriptions(SubscriberRestStub):
1318 def __hash__(self):
1319 return hash("ListSubscriptions")
1321 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1323 @classmethod
1324 def _get_unset_required_fields(cls, message_dict):
1325 return {
1326 k: v
1327 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1328 if k not in message_dict
1329 }
1331 def __call__(
1332 self,
1333 request: pubsub.ListSubscriptionsRequest,
1334 *,
1335 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1336 timeout: Optional[float] = None,
1337 metadata: Sequence[Tuple[str, str]] = (),
1338 ) -> pubsub.ListSubscriptionsResponse:
1339 r"""Call the list subscriptions method over HTTP.
1341 Args:
1342 request (~.pubsub.ListSubscriptionsRequest):
1343 The request object. Request for the ``ListSubscriptions`` method.
1344 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1345 should be retried.
1346 timeout (float): The timeout for this request.
1347 metadata (Sequence[Tuple[str, str]]): Strings which should be
1348 sent along with the request as metadata.
1350 Returns:
1351 ~.pubsub.ListSubscriptionsResponse:
1352 Response for the ``ListSubscriptions`` method.
1353 """
1355 http_options: List[Dict[str, str]] = [
1356 {
1357 "method": "get",
1358 "uri": "/v1/{project=projects/*}/subscriptions",
1359 },
1360 ]
1361 request, metadata = self._interceptor.pre_list_subscriptions(
1362 request, metadata
1363 )
1364 pb_request = pubsub.ListSubscriptionsRequest.pb(request)
1365 transcoded_request = path_template.transcode(http_options, pb_request)
1367 uri = transcoded_request["uri"]
1368 method = transcoded_request["method"]
1370 # Jsonify the query params
1371 query_params = json.loads(
1372 json_format.MessageToJson(
1373 transcoded_request["query_params"],
1374 including_default_value_fields=False,
1375 use_integers_for_enums=True,
1376 )
1377 )
1378 query_params.update(self._get_unset_required_fields(query_params))
1380 query_params["$alt"] = "json;enum-encoding=int"
1382 # Send the request
1383 headers = dict(metadata)
1384 headers["Content-Type"] = "application/json"
1385 response = getattr(self._session, method)(
1386 "{host}{uri}".format(host=self._host, uri=uri),
1387 timeout=timeout,
1388 headers=headers,
1389 params=rest_helpers.flatten_query_params(query_params, strict=True),
1390 )
1392 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1393 # subclass.
1394 if response.status_code >= 400:
1395 raise core_exceptions.from_http_response(response)
1397 # Return the response
1398 resp = pubsub.ListSubscriptionsResponse()
1399 pb_resp = pubsub.ListSubscriptionsResponse.pb(resp)
1401 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1402 resp = self._interceptor.post_list_subscriptions(resp)
1403 return resp
1405 class _ModifyAckDeadline(SubscriberRestStub):
1406 def __hash__(self):
1407 return hash("ModifyAckDeadline")
1409 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1411 @classmethod
1412 def _get_unset_required_fields(cls, message_dict):
1413 return {
1414 k: v
1415 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1416 if k not in message_dict
1417 }
1419 def __call__(
1420 self,
1421 request: pubsub.ModifyAckDeadlineRequest,
1422 *,
1423 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1424 timeout: Optional[float] = None,
1425 metadata: Sequence[Tuple[str, str]] = (),
1426 ):
1427 r"""Call the modify ack deadline method over HTTP.
1429 Args:
1430 request (~.pubsub.ModifyAckDeadlineRequest):
1431 The request object. Request for the ModifyAckDeadline
1432 method.
1433 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1434 should be retried.
1435 timeout (float): The timeout for this request.
1436 metadata (Sequence[Tuple[str, str]]): Strings which should be
1437 sent along with the request as metadata.
1438 """
1440 http_options: List[Dict[str, str]] = [
1441 {
1442 "method": "post",
1443 "uri": "/v1/{subscription=projects/*/subscriptions/*}:modifyAckDeadline",
1444 "body": "*",
1445 },
1446 ]
1447 request, metadata = self._interceptor.pre_modify_ack_deadline(
1448 request, metadata
1449 )
1450 pb_request = pubsub.ModifyAckDeadlineRequest.pb(request)
1451 transcoded_request = path_template.transcode(http_options, pb_request)
1453 # Jsonify the request body
1455 body = json_format.MessageToJson(
1456 transcoded_request["body"],
1457 including_default_value_fields=False,
1458 use_integers_for_enums=True,
1459 )
1460 uri = transcoded_request["uri"]
1461 method = transcoded_request["method"]
1463 # Jsonify the query params
1464 query_params = json.loads(
1465 json_format.MessageToJson(
1466 transcoded_request["query_params"],
1467 including_default_value_fields=False,
1468 use_integers_for_enums=True,
1469 )
1470 )
1471 query_params.update(self._get_unset_required_fields(query_params))
1473 query_params["$alt"] = "json;enum-encoding=int"
1475 # Send the request
1476 headers = dict(metadata)
1477 headers["Content-Type"] = "application/json"
1478 response = getattr(self._session, method)(
1479 "{host}{uri}".format(host=self._host, uri=uri),
1480 timeout=timeout,
1481 headers=headers,
1482 params=rest_helpers.flatten_query_params(query_params, strict=True),
1483 data=body,
1484 )
1486 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1487 # subclass.
1488 if response.status_code >= 400:
1489 raise core_exceptions.from_http_response(response)
1491 class _ModifyPushConfig(SubscriberRestStub):
1492 def __hash__(self):
1493 return hash("ModifyPushConfig")
1495 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1497 @classmethod
1498 def _get_unset_required_fields(cls, message_dict):
1499 return {
1500 k: v
1501 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1502 if k not in message_dict
1503 }
1505 def __call__(
1506 self,
1507 request: pubsub.ModifyPushConfigRequest,
1508 *,
1509 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1510 timeout: Optional[float] = None,
1511 metadata: Sequence[Tuple[str, str]] = (),
1512 ):
1513 r"""Call the modify push config method over HTTP.
1515 Args:
1516 request (~.pubsub.ModifyPushConfigRequest):
1517 The request object. Request for the ModifyPushConfig
1518 method.
1519 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1520 should be retried.
1521 timeout (float): The timeout for this request.
1522 metadata (Sequence[Tuple[str, str]]): Strings which should be
1523 sent along with the request as metadata.
1524 """
1526 http_options: List[Dict[str, str]] = [
1527 {
1528 "method": "post",
1529 "uri": "/v1/{subscription=projects/*/subscriptions/*}:modifyPushConfig",
1530 "body": "*",
1531 },
1532 ]
1533 request, metadata = self._interceptor.pre_modify_push_config(
1534 request, metadata
1535 )
1536 pb_request = pubsub.ModifyPushConfigRequest.pb(request)
1537 transcoded_request = path_template.transcode(http_options, pb_request)
1539 # Jsonify the request body
1541 body = json_format.MessageToJson(
1542 transcoded_request["body"],
1543 including_default_value_fields=False,
1544 use_integers_for_enums=True,
1545 )
1546 uri = transcoded_request["uri"]
1547 method = transcoded_request["method"]
1549 # Jsonify the query params
1550 query_params = json.loads(
1551 json_format.MessageToJson(
1552 transcoded_request["query_params"],
1553 including_default_value_fields=False,
1554 use_integers_for_enums=True,
1555 )
1556 )
1557 query_params.update(self._get_unset_required_fields(query_params))
1559 query_params["$alt"] = "json;enum-encoding=int"
1561 # Send the request
1562 headers = dict(metadata)
1563 headers["Content-Type"] = "application/json"
1564 response = getattr(self._session, method)(
1565 "{host}{uri}".format(host=self._host, uri=uri),
1566 timeout=timeout,
1567 headers=headers,
1568 params=rest_helpers.flatten_query_params(query_params, strict=True),
1569 data=body,
1570 )
1572 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1573 # subclass.
1574 if response.status_code >= 400:
1575 raise core_exceptions.from_http_response(response)
1577 class _Pull(SubscriberRestStub):
1578 def __hash__(self):
1579 return hash("Pull")
1581 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1583 @classmethod
1584 def _get_unset_required_fields(cls, message_dict):
1585 return {
1586 k: v
1587 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1588 if k not in message_dict
1589 }
1591 def __call__(
1592 self,
1593 request: pubsub.PullRequest,
1594 *,
1595 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1596 timeout: Optional[float] = None,
1597 metadata: Sequence[Tuple[str, str]] = (),
1598 ) -> pubsub.PullResponse:
1599 r"""Call the pull method over HTTP.
1601 Args:
1602 request (~.pubsub.PullRequest):
1603 The request object. Request for the ``Pull`` method.
1604 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1605 should be retried.
1606 timeout (float): The timeout for this request.
1607 metadata (Sequence[Tuple[str, str]]): Strings which should be
1608 sent along with the request as metadata.
1610 Returns:
1611 ~.pubsub.PullResponse:
1612 Response for the ``Pull`` method.
1613 """
1615 http_options: List[Dict[str, str]] = [
1616 {
1617 "method": "post",
1618 "uri": "/v1/{subscription=projects/*/subscriptions/*}:pull",
1619 "body": "*",
1620 },
1621 ]
1622 request, metadata = self._interceptor.pre_pull(request, metadata)
1623 pb_request = pubsub.PullRequest.pb(request)
1624 transcoded_request = path_template.transcode(http_options, pb_request)
1626 # Jsonify the request body
1628 body = json_format.MessageToJson(
1629 transcoded_request["body"],
1630 including_default_value_fields=False,
1631 use_integers_for_enums=True,
1632 )
1633 uri = transcoded_request["uri"]
1634 method = transcoded_request["method"]
1636 # Jsonify the query params
1637 query_params = json.loads(
1638 json_format.MessageToJson(
1639 transcoded_request["query_params"],
1640 including_default_value_fields=False,
1641 use_integers_for_enums=True,
1642 )
1643 )
1644 query_params.update(self._get_unset_required_fields(query_params))
1646 query_params["$alt"] = "json;enum-encoding=int"
1648 # Send the request
1649 headers = dict(metadata)
1650 headers["Content-Type"] = "application/json"
1651 response = getattr(self._session, method)(
1652 "{host}{uri}".format(host=self._host, uri=uri),
1653 timeout=timeout,
1654 headers=headers,
1655 params=rest_helpers.flatten_query_params(query_params, strict=True),
1656 data=body,
1657 )
1659 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1660 # subclass.
1661 if response.status_code >= 400:
1662 raise core_exceptions.from_http_response(response)
1664 # Return the response
1665 resp = pubsub.PullResponse()
1666 pb_resp = pubsub.PullResponse.pb(resp)
1668 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1669 resp = self._interceptor.post_pull(resp)
1670 return resp
1672 class _Seek(SubscriberRestStub):
1673 def __hash__(self):
1674 return hash("Seek")
1676 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1678 @classmethod
1679 def _get_unset_required_fields(cls, message_dict):
1680 return {
1681 k: v
1682 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1683 if k not in message_dict
1684 }
1686 def __call__(
1687 self,
1688 request: pubsub.SeekRequest,
1689 *,
1690 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1691 timeout: Optional[float] = None,
1692 metadata: Sequence[Tuple[str, str]] = (),
1693 ) -> pubsub.SeekResponse:
1694 r"""Call the seek method over HTTP.
1696 Args:
1697 request (~.pubsub.SeekRequest):
1698 The request object. Request for the ``Seek`` method.
1699 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1700 should be retried.
1701 timeout (float): The timeout for this request.
1702 metadata (Sequence[Tuple[str, str]]): Strings which should be
1703 sent along with the request as metadata.
1705 Returns:
1706 ~.pubsub.SeekResponse:
1707 Response for the ``Seek`` method (this response is
1708 empty).
1710 """
1712 http_options: List[Dict[str, str]] = [
1713 {
1714 "method": "post",
1715 "uri": "/v1/{subscription=projects/*/subscriptions/*}:seek",
1716 "body": "*",
1717 },
1718 ]
1719 request, metadata = self._interceptor.pre_seek(request, metadata)
1720 pb_request = pubsub.SeekRequest.pb(request)
1721 transcoded_request = path_template.transcode(http_options, pb_request)
1723 # Jsonify the request body
1725 body = json_format.MessageToJson(
1726 transcoded_request["body"],
1727 including_default_value_fields=False,
1728 use_integers_for_enums=True,
1729 )
1730 uri = transcoded_request["uri"]
1731 method = transcoded_request["method"]
1733 # Jsonify the query params
1734 query_params = json.loads(
1735 json_format.MessageToJson(
1736 transcoded_request["query_params"],
1737 including_default_value_fields=False,
1738 use_integers_for_enums=True,
1739 )
1740 )
1741 query_params.update(self._get_unset_required_fields(query_params))
1743 query_params["$alt"] = "json;enum-encoding=int"
1745 # Send the request
1746 headers = dict(metadata)
1747 headers["Content-Type"] = "application/json"
1748 response = getattr(self._session, method)(
1749 "{host}{uri}".format(host=self._host, uri=uri),
1750 timeout=timeout,
1751 headers=headers,
1752 params=rest_helpers.flatten_query_params(query_params, strict=True),
1753 data=body,
1754 )
1756 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1757 # subclass.
1758 if response.status_code >= 400:
1759 raise core_exceptions.from_http_response(response)
1761 # Return the response
1762 resp = pubsub.SeekResponse()
1763 pb_resp = pubsub.SeekResponse.pb(resp)
1765 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1766 resp = self._interceptor.post_seek(resp)
1767 return resp
1769 class _StreamingPull(SubscriberRestStub):
1770 def __hash__(self):
1771 return hash("StreamingPull")
1773 def __call__(
1774 self,
1775 request: pubsub.StreamingPullRequest,
1776 *,
1777 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1778 timeout: Optional[float] = None,
1779 metadata: Sequence[Tuple[str, str]] = (),
1780 ) -> rest_streaming.ResponseIterator:
1781 raise NotImplementedError(
1782 "Method StreamingPull is not available over REST transport"
1783 )
1785 class _UpdateSnapshot(SubscriberRestStub):
1786 def __hash__(self):
1787 return hash("UpdateSnapshot")
1789 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1791 @classmethod
1792 def _get_unset_required_fields(cls, message_dict):
1793 return {
1794 k: v
1795 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1796 if k not in message_dict
1797 }
1799 def __call__(
1800 self,
1801 request: pubsub.UpdateSnapshotRequest,
1802 *,
1803 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1804 timeout: Optional[float] = None,
1805 metadata: Sequence[Tuple[str, str]] = (),
1806 ) -> pubsub.Snapshot:
1807 r"""Call the update snapshot method over HTTP.
1809 Args:
1810 request (~.pubsub.UpdateSnapshotRequest):
1811 The request object. Request for the UpdateSnapshot
1812 method.
1813 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1814 should be retried.
1815 timeout (float): The timeout for this request.
1816 metadata (Sequence[Tuple[str, str]]): Strings which should be
1817 sent along with the request as metadata.
1819 Returns:
1820 ~.pubsub.Snapshot:
1821 A snapshot resource. Snapshots are used in
1822 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1823 operations, which allow you to manage message
1824 acknowledgments in bulk. That is, you can set the
1825 acknowledgment state of messages in an existing
1826 subscription to the state captured by a snapshot.
1828 """
1830 http_options: List[Dict[str, str]] = [
1831 {
1832 "method": "patch",
1833 "uri": "/v1/{snapshot.name=projects/*/snapshots/*}",
1834 "body": "*",
1835 },
1836 ]
1837 request, metadata = self._interceptor.pre_update_snapshot(request, metadata)
1838 pb_request = pubsub.UpdateSnapshotRequest.pb(request)
1839 transcoded_request = path_template.transcode(http_options, pb_request)
1841 # Jsonify the request body
1843 body = json_format.MessageToJson(
1844 transcoded_request["body"],
1845 including_default_value_fields=False,
1846 use_integers_for_enums=True,
1847 )
1848 uri = transcoded_request["uri"]
1849 method = transcoded_request["method"]
1851 # Jsonify the query params
1852 query_params = json.loads(
1853 json_format.MessageToJson(
1854 transcoded_request["query_params"],
1855 including_default_value_fields=False,
1856 use_integers_for_enums=True,
1857 )
1858 )
1859 query_params.update(self._get_unset_required_fields(query_params))
1861 query_params["$alt"] = "json;enum-encoding=int"
1863 # Send the request
1864 headers = dict(metadata)
1865 headers["Content-Type"] = "application/json"
1866 response = getattr(self._session, method)(
1867 "{host}{uri}".format(host=self._host, uri=uri),
1868 timeout=timeout,
1869 headers=headers,
1870 params=rest_helpers.flatten_query_params(query_params, strict=True),
1871 data=body,
1872 )
1874 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1875 # subclass.
1876 if response.status_code >= 400:
1877 raise core_exceptions.from_http_response(response)
1879 # Return the response
1880 resp = pubsub.Snapshot()
1881 pb_resp = pubsub.Snapshot.pb(resp)
1883 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1884 resp = self._interceptor.post_update_snapshot(resp)
1885 return resp
1887 class _UpdateSubscription(SubscriberRestStub):
1888 def __hash__(self):
1889 return hash("UpdateSubscription")
1891 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1893 @classmethod
1894 def _get_unset_required_fields(cls, message_dict):
1895 return {
1896 k: v
1897 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1898 if k not in message_dict
1899 }
1901 def __call__(
1902 self,
1903 request: pubsub.UpdateSubscriptionRequest,
1904 *,
1905 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1906 timeout: Optional[float] = None,
1907 metadata: Sequence[Tuple[str, str]] = (),
1908 ) -> pubsub.Subscription:
1909 r"""Call the update subscription method over HTTP.
1911 Args:
1912 request (~.pubsub.UpdateSubscriptionRequest):
1913 The request object. Request for the UpdateSubscription
1914 method.
1915 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1916 should be retried.
1917 timeout (float): The timeout for this request.
1918 metadata (Sequence[Tuple[str, str]]): Strings which should be
1919 sent along with the request as metadata.
1921 Returns:
1922 ~.pubsub.Subscription:
1923 A subscription resource. If none of ``push_config``,
1924 ``bigquery_config``, or ``cloud_storage_config`` is set,
1925 then the subscriber will pull and ack messages using API
1926 methods. At most one of these fields may be set.
1928 """
1930 http_options: List[Dict[str, str]] = [
1931 {
1932 "method": "patch",
1933 "uri": "/v1/{subscription.name=projects/*/subscriptions/*}",
1934 "body": "*",
1935 },
1936 ]
1937 request, metadata = self._interceptor.pre_update_subscription(
1938 request, metadata
1939 )
1940 pb_request = pubsub.UpdateSubscriptionRequest.pb(request)
1941 transcoded_request = path_template.transcode(http_options, pb_request)
1943 # Jsonify the request body
1945 body = json_format.MessageToJson(
1946 transcoded_request["body"],
1947 including_default_value_fields=False,
1948 use_integers_for_enums=True,
1949 )
1950 uri = transcoded_request["uri"]
1951 method = transcoded_request["method"]
1953 # Jsonify the query params
1954 query_params = json.loads(
1955 json_format.MessageToJson(
1956 transcoded_request["query_params"],
1957 including_default_value_fields=False,
1958 use_integers_for_enums=True,
1959 )
1960 )
1961 query_params.update(self._get_unset_required_fields(query_params))
1963 query_params["$alt"] = "json;enum-encoding=int"
1965 # Send the request
1966 headers = dict(metadata)
1967 headers["Content-Type"] = "application/json"
1968 response = getattr(self._session, method)(
1969 "{host}{uri}".format(host=self._host, uri=uri),
1970 timeout=timeout,
1971 headers=headers,
1972 params=rest_helpers.flatten_query_params(query_params, strict=True),
1973 data=body,
1974 )
1976 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1977 # subclass.
1978 if response.status_code >= 400:
1979 raise core_exceptions.from_http_response(response)
1981 # Return the response
1982 resp = pubsub.Subscription()
1983 pb_resp = pubsub.Subscription.pb(resp)
1985 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1986 resp = self._interceptor.post_update_subscription(resp)
1987 return resp
1989 @property
1990 def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty_pb2.Empty]:
1991 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1992 # In C++ this would require a dynamic_cast
1993 return self._Acknowledge(self._session, self._host, self._interceptor) # type: ignore
1995 @property
1996 def create_snapshot(
1997 self,
1998 ) -> Callable[[pubsub.CreateSnapshotRequest], pubsub.Snapshot]:
1999 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2000 # In C++ this would require a dynamic_cast
2001 return self._CreateSnapshot(self._session, self._host, self._interceptor) # type: ignore
2003 @property
2004 def create_subscription(
2005 self,
2006 ) -> Callable[[pubsub.Subscription], pubsub.Subscription]:
2007 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2008 # In C++ this would require a dynamic_cast
2009 return self._CreateSubscription(self._session, self._host, self._interceptor) # type: ignore
2011 @property
2012 def delete_snapshot(
2013 self,
2014 ) -> Callable[[pubsub.DeleteSnapshotRequest], empty_pb2.Empty]:
2015 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2016 # In C++ this would require a dynamic_cast
2017 return self._DeleteSnapshot(self._session, self._host, self._interceptor) # type: ignore
2019 @property
2020 def delete_subscription(
2021 self,
2022 ) -> Callable[[pubsub.DeleteSubscriptionRequest], empty_pb2.Empty]:
2023 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2024 # In C++ this would require a dynamic_cast
2025 return self._DeleteSubscription(self._session, self._host, self._interceptor) # type: ignore
2027 @property
2028 def get_snapshot(self) -> Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot]:
2029 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2030 # In C++ this would require a dynamic_cast
2031 return self._GetSnapshot(self._session, self._host, self._interceptor) # type: ignore
2033 @property
2034 def get_subscription(
2035 self,
2036 ) -> Callable[[pubsub.GetSubscriptionRequest], pubsub.Subscription]:
2037 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2038 # In C++ this would require a dynamic_cast
2039 return self._GetSubscription(self._session, self._host, self._interceptor) # type: ignore
2041 @property
2042 def list_snapshots(
2043 self,
2044 ) -> Callable[[pubsub.ListSnapshotsRequest], pubsub.ListSnapshotsResponse]:
2045 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2046 # In C++ this would require a dynamic_cast
2047 return self._ListSnapshots(self._session, self._host, self._interceptor) # type: ignore
2049 @property
2050 def list_subscriptions(
2051 self,
2052 ) -> Callable[[pubsub.ListSubscriptionsRequest], pubsub.ListSubscriptionsResponse]:
2053 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2054 # In C++ this would require a dynamic_cast
2055 return self._ListSubscriptions(self._session, self._host, self._interceptor) # type: ignore
2057 @property
2058 def modify_ack_deadline(
2059 self,
2060 ) -> Callable[[pubsub.ModifyAckDeadlineRequest], empty_pb2.Empty]:
2061 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2062 # In C++ this would require a dynamic_cast
2063 return self._ModifyAckDeadline(self._session, self._host, self._interceptor) # type: ignore
2065 @property
2066 def modify_push_config(
2067 self,
2068 ) -> Callable[[pubsub.ModifyPushConfigRequest], empty_pb2.Empty]:
2069 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2070 # In C++ this would require a dynamic_cast
2071 return self._ModifyPushConfig(self._session, self._host, self._interceptor) # type: ignore
2073 @property
2074 def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]:
2075 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2076 # In C++ this would require a dynamic_cast
2077 return self._Pull(self._session, self._host, self._interceptor) # type: ignore
2079 @property
2080 def seek(self) -> Callable[[pubsub.SeekRequest], pubsub.SeekResponse]:
2081 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2082 # In C++ this would require a dynamic_cast
2083 return self._Seek(self._session, self._host, self._interceptor) # type: ignore
2085 @property
2086 def streaming_pull(
2087 self,
2088 ) -> Callable[[pubsub.StreamingPullRequest], pubsub.StreamingPullResponse]:
2089 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2090 # In C++ this would require a dynamic_cast
2091 return self._StreamingPull(self._session, self._host, self._interceptor) # type: ignore
2093 @property
2094 def update_snapshot(
2095 self,
2096 ) -> Callable[[pubsub.UpdateSnapshotRequest], pubsub.Snapshot]:
2097 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2098 # In C++ this would require a dynamic_cast
2099 return self._UpdateSnapshot(self._session, self._host, self._interceptor) # type: ignore
2101 @property
2102 def update_subscription(
2103 self,
2104 ) -> Callable[[pubsub.UpdateSubscriptionRequest], pubsub.Subscription]:
2105 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2106 # In C++ this would require a dynamic_cast
2107 return self._UpdateSubscription(self._session, self._host, self._interceptor) # type: ignore
2109 @property
2110 def get_iam_policy(self):
2111 return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
2113 class _GetIamPolicy(SubscriberRestStub):
2114 def __call__(
2115 self,
2116 request: iam_policy_pb2.GetIamPolicyRequest,
2117 *,
2118 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2119 timeout: Optional[float] = None,
2120 metadata: Sequence[Tuple[str, str]] = (),
2121 ) -> policy_pb2.Policy:
2123 r"""Call the get iam policy method over HTTP.
2125 Args:
2126 request (iam_policy_pb2.GetIamPolicyRequest):
2127 The request object for GetIamPolicy method.
2128 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2129 should be retried.
2130 timeout (float): The timeout for this request.
2131 metadata (Sequence[Tuple[str, str]]): Strings which should be
2132 sent along with the request as metadata.
2134 Returns:
2135 policy_pb2.Policy: Response from GetIamPolicy method.
2136 """
2138 http_options: List[Dict[str, str]] = [
2139 {
2140 "method": "get",
2141 "uri": "/v1/{resource=projects/*/topics/*}:getIamPolicy",
2142 },
2143 {
2144 "method": "get",
2145 "uri": "/v1/{resource=projects/*/subscriptions/*}:getIamPolicy",
2146 },
2147 {
2148 "method": "get",
2149 "uri": "/v1/{resource=projects/*/snapshots/*}:getIamPolicy",
2150 },
2151 {
2152 "method": "get",
2153 "uri": "/v1/{resource=projects/*/schemas/*}:getIamPolicy",
2154 },
2155 ]
2157 request, metadata = self._interceptor.pre_get_iam_policy(request, metadata)
2158 request_kwargs = json_format.MessageToDict(request)
2159 transcoded_request = path_template.transcode(http_options, **request_kwargs)
2161 uri = transcoded_request["uri"]
2162 method = transcoded_request["method"]
2164 # Jsonify the query params
2165 query_params = json.loads(json.dumps(transcoded_request["query_params"]))
2167 # Send the request
2168 headers = dict(metadata)
2169 headers["Content-Type"] = "application/json"
2171 response = getattr(self._session, method)(
2172 "{host}{uri}".format(host=self._host, uri=uri),
2173 timeout=timeout,
2174 headers=headers,
2175 params=rest_helpers.flatten_query_params(query_params),
2176 )
2178 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
2179 # subclass.
2180 if response.status_code >= 400:
2181 raise core_exceptions.from_http_response(response)
2183 resp = policy_pb2.Policy()
2184 resp = json_format.Parse(response.content.decode("utf-8"), resp)
2185 resp = self._interceptor.post_get_iam_policy(resp)
2186 return resp
2188 @property
2189 def set_iam_policy(self):
2190 return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
2192 class _SetIamPolicy(SubscriberRestStub):
2193 def __call__(
2194 self,
2195 request: iam_policy_pb2.SetIamPolicyRequest,
2196 *,
2197 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2198 timeout: Optional[float] = None,
2199 metadata: Sequence[Tuple[str, str]] = (),
2200 ) -> policy_pb2.Policy:
2202 r"""Call the set iam policy method over HTTP.
2204 Args:
2205 request (iam_policy_pb2.SetIamPolicyRequest):
2206 The request object for SetIamPolicy method.
2207 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2208 should be retried.
2209 timeout (float): The timeout for this request.
2210 metadata (Sequence[Tuple[str, str]]): Strings which should be
2211 sent along with the request as metadata.
2213 Returns:
2214 policy_pb2.Policy: Response from SetIamPolicy method.
2215 """
2217 http_options: List[Dict[str, str]] = [
2218 {
2219 "method": "post",
2220 "uri": "/v1/{resource=projects/*/topics/*}:setIamPolicy",
2221 "body": "*",
2222 },
2223 {
2224 "method": "post",
2225 "uri": "/v1/{resource=projects/*/subscriptions/*}:setIamPolicy",
2226 "body": "*",
2227 },
2228 {
2229 "method": "post",
2230 "uri": "/v1/{resource=projects/*/snapshots/*}:setIamPolicy",
2231 "body": "*",
2232 },
2233 {
2234 "method": "post",
2235 "uri": "/v1/{resource=projects/*/schemas/*}:setIamPolicy",
2236 "body": "*",
2237 },
2238 ]
2240 request, metadata = self._interceptor.pre_set_iam_policy(request, metadata)
2241 request_kwargs = json_format.MessageToDict(request)
2242 transcoded_request = path_template.transcode(http_options, **request_kwargs)
2244 body = json.loads(json.dumps(transcoded_request["body"]))
2245 uri = transcoded_request["uri"]
2246 method = transcoded_request["method"]
2248 # Jsonify the query params
2249 query_params = json.loads(json.dumps(transcoded_request["query_params"]))
2251 # Send the request
2252 headers = dict(metadata)
2253 headers["Content-Type"] = "application/json"
2255 response = getattr(self._session, method)(
2256 "{host}{uri}".format(host=self._host, uri=uri),
2257 timeout=timeout,
2258 headers=headers,
2259 params=rest_helpers.flatten_query_params(query_params),
2260 data=body,
2261 )
2263 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
2264 # subclass.
2265 if response.status_code >= 400:
2266 raise core_exceptions.from_http_response(response)
2268 resp = policy_pb2.Policy()
2269 resp = json_format.Parse(response.content.decode("utf-8"), resp)
2270 resp = self._interceptor.post_set_iam_policy(resp)
2271 return resp
2273 @property
2274 def test_iam_permissions(self):
2275 return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore
2277 class _TestIamPermissions(SubscriberRestStub):
2278 def __call__(
2279 self,
2280 request: iam_policy_pb2.TestIamPermissionsRequest,
2281 *,
2282 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2283 timeout: Optional[float] = None,
2284 metadata: Sequence[Tuple[str, str]] = (),
2285 ) -> iam_policy_pb2.TestIamPermissionsResponse:
2287 r"""Call the test iam permissions method over HTTP.
2289 Args:
2290 request (iam_policy_pb2.TestIamPermissionsRequest):
2291 The request object for TestIamPermissions method.
2292 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2293 should be retried.
2294 timeout (float): The timeout for this request.
2295 metadata (Sequence[Tuple[str, str]]): Strings which should be
2296 sent along with the request as metadata.
2298 Returns:
2299 iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method.
2300 """
2302 http_options: List[Dict[str, str]] = [
2303 {
2304 "method": "post",
2305 "uri": "/v1/{resource=projects/*/subscriptions/*}:testIamPermissions",
2306 "body": "*",
2307 },
2308 {
2309 "method": "post",
2310 "uri": "/v1/{resource=projects/*/topics/*}:testIamPermissions",
2311 "body": "*",
2312 },
2313 {
2314 "method": "post",
2315 "uri": "/v1/{resource=projects/*/snapshots/*}:testIamPermissions",
2316 "body": "*",
2317 },
2318 {
2319 "method": "post",
2320 "uri": "/v1/{resource=projects/*/schemas/*}:testIamPermissions",
2321 "body": "*",
2322 },
2323 ]
2325 request, metadata = self._interceptor.pre_test_iam_permissions(
2326 request, metadata
2327 )
2328 request_kwargs = json_format.MessageToDict(request)
2329 transcoded_request = path_template.transcode(http_options, **request_kwargs)
2331 body = json.loads(json.dumps(transcoded_request["body"]))
2332 uri = transcoded_request["uri"]
2333 method = transcoded_request["method"]
2335 # Jsonify the query params
2336 query_params = json.loads(json.dumps(transcoded_request["query_params"]))
2338 # Send the request
2339 headers = dict(metadata)
2340 headers["Content-Type"] = "application/json"
2342 response = getattr(self._session, method)(
2343 "{host}{uri}".format(host=self._host, uri=uri),
2344 timeout=timeout,
2345 headers=headers,
2346 params=rest_helpers.flatten_query_params(query_params),
2347 data=body,
2348 )
2350 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
2351 # subclass.
2352 if response.status_code >= 400:
2353 raise core_exceptions.from_http_response(response)
2355 resp = iam_policy_pb2.TestIamPermissionsResponse()
2356 resp = json_format.Parse(response.content.decode("utf-8"), resp)
2357 resp = self._interceptor.post_test_iam_permissions(resp)
2358 return resp
2360 @property
2361 def kind(self) -> str:
2362 return "rest"
2364 def close(self):
2365 self._session.close()
2368__all__ = ("SubscriberRestTransport",)