1# -*- coding: utf-8 -*-
2# Copyright 2024 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#
16import logging
17import json # type: ignore
18
19from google.auth.transport.requests import AuthorizedSession # type: ignore
20from google.auth import credentials as ga_credentials # type: ignore
21from google.api_core import exceptions as core_exceptions
22from google.api_core import retry as retries
23from google.api_core import rest_helpers
24from google.api_core import rest_streaming
25from google.api_core import gapic_v1
26
27from google.protobuf import json_format
28from google.iam.v1 import iam_policy_pb2 # type: ignore
29from google.iam.v1 import policy_pb2 # type: ignore
30
31from requests import __version__ as requests_version
32import dataclasses
33from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
34import warnings
35
36
37from google.protobuf import empty_pb2 # type: ignore
38from google.pubsub_v1.types import pubsub
39
40
41from .rest_base import _BasePublisherRestTransport
42from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
43
44try:
45 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
46except AttributeError: # pragma: NO COVER
47 OptionalRetry = Union[retries.Retry, object, None] # type: ignore
48
49try:
50 from google.api_core import client_logging # type: ignore
51
52 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
53except ImportError: # pragma: NO COVER
54 CLIENT_LOGGING_SUPPORTED = False
55
56_LOGGER = logging.getLogger(__name__)
57
58DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
59 gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
60 grpc_version=None,
61 rest_version=f"requests@{requests_version}",
62)
63
64
65class PublisherRestInterceptor:
66 """Interceptor for Publisher.
67
68 Interceptors are used to manipulate requests, request metadata, and responses
69 in arbitrary ways.
70 Example use cases include:
71 * Logging
72 * Verifying requests according to service or custom semantics
73 * Stripping extraneous information from responses
74
75 These use cases and more can be enabled by injecting an
76 instance of a custom subclass when constructing the PublisherRestTransport.
77
78 .. code-block:: python
79 class MyCustomPublisherInterceptor(PublisherRestInterceptor):
80 def pre_create_topic(self, request, metadata):
81 logging.log(f"Received request: {request}")
82 return request, metadata
83
84 def post_create_topic(self, response):
85 logging.log(f"Received response: {response}")
86 return response
87
88 def pre_delete_topic(self, request, metadata):
89 logging.log(f"Received request: {request}")
90 return request, metadata
91
92 def pre_detach_subscription(self, request, metadata):
93 logging.log(f"Received request: {request}")
94 return request, metadata
95
96 def post_detach_subscription(self, response):
97 logging.log(f"Received response: {response}")
98 return response
99
100 def pre_get_topic(self, request, metadata):
101 logging.log(f"Received request: {request}")
102 return request, metadata
103
104 def post_get_topic(self, response):
105 logging.log(f"Received response: {response}")
106 return response
107
108 def pre_list_topics(self, request, metadata):
109 logging.log(f"Received request: {request}")
110 return request, metadata
111
112 def post_list_topics(self, response):
113 logging.log(f"Received response: {response}")
114 return response
115
116 def pre_list_topic_snapshots(self, request, metadata):
117 logging.log(f"Received request: {request}")
118 return request, metadata
119
120 def post_list_topic_snapshots(self, response):
121 logging.log(f"Received response: {response}")
122 return response
123
124 def pre_list_topic_subscriptions(self, request, metadata):
125 logging.log(f"Received request: {request}")
126 return request, metadata
127
128 def post_list_topic_subscriptions(self, response):
129 logging.log(f"Received response: {response}")
130 return response
131
132 def pre_publish(self, request, metadata):
133 logging.log(f"Received request: {request}")
134 return request, metadata
135
136 def post_publish(self, response):
137 logging.log(f"Received response: {response}")
138 return response
139
140 def pre_update_topic(self, request, metadata):
141 logging.log(f"Received request: {request}")
142 return request, metadata
143
144 def post_update_topic(self, response):
145 logging.log(f"Received response: {response}")
146 return response
147
148 transport = PublisherRestTransport(interceptor=MyCustomPublisherInterceptor())
149 client = PublisherClient(transport=transport)
150
151
152 """
153
154 def pre_create_topic(
155 self, request: pubsub.Topic, metadata: Sequence[Tuple[str, Union[str, bytes]]]
156 ) -> Tuple[pubsub.Topic, Sequence[Tuple[str, Union[str, bytes]]]]:
157 """Pre-rpc interceptor for create_topic
158
159 Override in a subclass to manipulate the request or metadata
160 before they are sent to the Publisher server.
161 """
162 return request, metadata
163
164 def post_create_topic(self, response: pubsub.Topic) -> pubsub.Topic:
165 """Post-rpc interceptor for create_topic
166
167 DEPRECATED. Please use the `post_create_topic_with_metadata`
168 interceptor instead.
169
170 Override in a subclass to read or manipulate the response
171 after it is returned by the Publisher server but before
172 it is returned to user code. This `post_create_topic` interceptor runs
173 before the `post_create_topic_with_metadata` interceptor.
174 """
175 return response
176
177 def post_create_topic_with_metadata(
178 self, response: pubsub.Topic, metadata: Sequence[Tuple[str, Union[str, bytes]]]
179 ) -> Tuple[pubsub.Topic, Sequence[Tuple[str, Union[str, bytes]]]]:
180 """Post-rpc interceptor for create_topic
181
182 Override in a subclass to read or manipulate the response or metadata after it
183 is returned by the Publisher server but before it is returned to user code.
184
185 We recommend only using this `post_create_topic_with_metadata`
186 interceptor in new development instead of the `post_create_topic` interceptor.
187 When both interceptors are used, this `post_create_topic_with_metadata` interceptor runs after the
188 `post_create_topic` interceptor. The (possibly modified) response returned by
189 `post_create_topic` will be passed to
190 `post_create_topic_with_metadata`.
191 """
192 return response, metadata
193
194 def pre_delete_topic(
195 self,
196 request: pubsub.DeleteTopicRequest,
197 metadata: Sequence[Tuple[str, Union[str, bytes]]],
198 ) -> Tuple[pubsub.DeleteTopicRequest, Sequence[Tuple[str, Union[str, bytes]]]]:
199 """Pre-rpc interceptor for delete_topic
200
201 Override in a subclass to manipulate the request or metadata
202 before they are sent to the Publisher server.
203 """
204 return request, metadata
205
206 def pre_detach_subscription(
207 self,
208 request: pubsub.DetachSubscriptionRequest,
209 metadata: Sequence[Tuple[str, Union[str, bytes]]],
210 ) -> Tuple[
211 pubsub.DetachSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]
212 ]:
213 """Pre-rpc interceptor for detach_subscription
214
215 Override in a subclass to manipulate the request or metadata
216 before they are sent to the Publisher server.
217 """
218 return request, metadata
219
220 def post_detach_subscription(
221 self, response: pubsub.DetachSubscriptionResponse
222 ) -> pubsub.DetachSubscriptionResponse:
223 """Post-rpc interceptor for detach_subscription
224
225 DEPRECATED. Please use the `post_detach_subscription_with_metadata`
226 interceptor instead.
227
228 Override in a subclass to read or manipulate the response
229 after it is returned by the Publisher server but before
230 it is returned to user code. This `post_detach_subscription` interceptor runs
231 before the `post_detach_subscription_with_metadata` interceptor.
232 """
233 return response
234
235 def post_detach_subscription_with_metadata(
236 self,
237 response: pubsub.DetachSubscriptionResponse,
238 metadata: Sequence[Tuple[str, Union[str, bytes]]],
239 ) -> Tuple[
240 pubsub.DetachSubscriptionResponse, Sequence[Tuple[str, Union[str, bytes]]]
241 ]:
242 """Post-rpc interceptor for detach_subscription
243
244 Override in a subclass to read or manipulate the response or metadata after it
245 is returned by the Publisher server but before it is returned to user code.
246
247 We recommend only using this `post_detach_subscription_with_metadata`
248 interceptor in new development instead of the `post_detach_subscription` interceptor.
249 When both interceptors are used, this `post_detach_subscription_with_metadata` interceptor runs after the
250 `post_detach_subscription` interceptor. The (possibly modified) response returned by
251 `post_detach_subscription` will be passed to
252 `post_detach_subscription_with_metadata`.
253 """
254 return response, metadata
255
256 def pre_get_topic(
257 self,
258 request: pubsub.GetTopicRequest,
259 metadata: Sequence[Tuple[str, Union[str, bytes]]],
260 ) -> Tuple[pubsub.GetTopicRequest, Sequence[Tuple[str, Union[str, bytes]]]]:
261 """Pre-rpc interceptor for get_topic
262
263 Override in a subclass to manipulate the request or metadata
264 before they are sent to the Publisher server.
265 """
266 return request, metadata
267
268 def post_get_topic(self, response: pubsub.Topic) -> pubsub.Topic:
269 """Post-rpc interceptor for get_topic
270
271 DEPRECATED. Please use the `post_get_topic_with_metadata`
272 interceptor instead.
273
274 Override in a subclass to read or manipulate the response
275 after it is returned by the Publisher server but before
276 it is returned to user code. This `post_get_topic` interceptor runs
277 before the `post_get_topic_with_metadata` interceptor.
278 """
279 return response
280
281 def post_get_topic_with_metadata(
282 self, response: pubsub.Topic, metadata: Sequence[Tuple[str, Union[str, bytes]]]
283 ) -> Tuple[pubsub.Topic, Sequence[Tuple[str, Union[str, bytes]]]]:
284 """Post-rpc interceptor for get_topic
285
286 Override in a subclass to read or manipulate the response or metadata after it
287 is returned by the Publisher server but before it is returned to user code.
288
289 We recommend only using this `post_get_topic_with_metadata`
290 interceptor in new development instead of the `post_get_topic` interceptor.
291 When both interceptors are used, this `post_get_topic_with_metadata` interceptor runs after the
292 `post_get_topic` interceptor. The (possibly modified) response returned by
293 `post_get_topic` will be passed to
294 `post_get_topic_with_metadata`.
295 """
296 return response, metadata
297
298 def pre_list_topics(
299 self,
300 request: pubsub.ListTopicsRequest,
301 metadata: Sequence[Tuple[str, Union[str, bytes]]],
302 ) -> Tuple[pubsub.ListTopicsRequest, Sequence[Tuple[str, Union[str, bytes]]]]:
303 """Pre-rpc interceptor for list_topics
304
305 Override in a subclass to manipulate the request or metadata
306 before they are sent to the Publisher server.
307 """
308 return request, metadata
309
310 def post_list_topics(
311 self, response: pubsub.ListTopicsResponse
312 ) -> pubsub.ListTopicsResponse:
313 """Post-rpc interceptor for list_topics
314
315 DEPRECATED. Please use the `post_list_topics_with_metadata`
316 interceptor instead.
317
318 Override in a subclass to read or manipulate the response
319 after it is returned by the Publisher server but before
320 it is returned to user code. This `post_list_topics` interceptor runs
321 before the `post_list_topics_with_metadata` interceptor.
322 """
323 return response
324
325 def post_list_topics_with_metadata(
326 self,
327 response: pubsub.ListTopicsResponse,
328 metadata: Sequence[Tuple[str, Union[str, bytes]]],
329 ) -> Tuple[pubsub.ListTopicsResponse, Sequence[Tuple[str, Union[str, bytes]]]]:
330 """Post-rpc interceptor for list_topics
331
332 Override in a subclass to read or manipulate the response or metadata after it
333 is returned by the Publisher server but before it is returned to user code.
334
335 We recommend only using this `post_list_topics_with_metadata`
336 interceptor in new development instead of the `post_list_topics` interceptor.
337 When both interceptors are used, this `post_list_topics_with_metadata` interceptor runs after the
338 `post_list_topics` interceptor. The (possibly modified) response returned by
339 `post_list_topics` will be passed to
340 `post_list_topics_with_metadata`.
341 """
342 return response, metadata
343
344 def pre_list_topic_snapshots(
345 self,
346 request: pubsub.ListTopicSnapshotsRequest,
347 metadata: Sequence[Tuple[str, Union[str, bytes]]],
348 ) -> Tuple[
349 pubsub.ListTopicSnapshotsRequest, Sequence[Tuple[str, Union[str, bytes]]]
350 ]:
351 """Pre-rpc interceptor for list_topic_snapshots
352
353 Override in a subclass to manipulate the request or metadata
354 before they are sent to the Publisher server.
355 """
356 return request, metadata
357
358 def post_list_topic_snapshots(
359 self, response: pubsub.ListTopicSnapshotsResponse
360 ) -> pubsub.ListTopicSnapshotsResponse:
361 """Post-rpc interceptor for list_topic_snapshots
362
363 DEPRECATED. Please use the `post_list_topic_snapshots_with_metadata`
364 interceptor instead.
365
366 Override in a subclass to read or manipulate the response
367 after it is returned by the Publisher server but before
368 it is returned to user code. This `post_list_topic_snapshots` interceptor runs
369 before the `post_list_topic_snapshots_with_metadata` interceptor.
370 """
371 return response
372
373 def post_list_topic_snapshots_with_metadata(
374 self,
375 response: pubsub.ListTopicSnapshotsResponse,
376 metadata: Sequence[Tuple[str, Union[str, bytes]]],
377 ) -> Tuple[
378 pubsub.ListTopicSnapshotsResponse, Sequence[Tuple[str, Union[str, bytes]]]
379 ]:
380 """Post-rpc interceptor for list_topic_snapshots
381
382 Override in a subclass to read or manipulate the response or metadata after it
383 is returned by the Publisher server but before it is returned to user code.
384
385 We recommend only using this `post_list_topic_snapshots_with_metadata`
386 interceptor in new development instead of the `post_list_topic_snapshots` interceptor.
387 When both interceptors are used, this `post_list_topic_snapshots_with_metadata` interceptor runs after the
388 `post_list_topic_snapshots` interceptor. The (possibly modified) response returned by
389 `post_list_topic_snapshots` will be passed to
390 `post_list_topic_snapshots_with_metadata`.
391 """
392 return response, metadata
393
394 def pre_list_topic_subscriptions(
395 self,
396 request: pubsub.ListTopicSubscriptionsRequest,
397 metadata: Sequence[Tuple[str, Union[str, bytes]]],
398 ) -> Tuple[
399 pubsub.ListTopicSubscriptionsRequest, Sequence[Tuple[str, Union[str, bytes]]]
400 ]:
401 """Pre-rpc interceptor for list_topic_subscriptions
402
403 Override in a subclass to manipulate the request or metadata
404 before they are sent to the Publisher server.
405 """
406 return request, metadata
407
408 def post_list_topic_subscriptions(
409 self, response: pubsub.ListTopicSubscriptionsResponse
410 ) -> pubsub.ListTopicSubscriptionsResponse:
411 """Post-rpc interceptor for list_topic_subscriptions
412
413 DEPRECATED. Please use the `post_list_topic_subscriptions_with_metadata`
414 interceptor instead.
415
416 Override in a subclass to read or manipulate the response
417 after it is returned by the Publisher server but before
418 it is returned to user code. This `post_list_topic_subscriptions` interceptor runs
419 before the `post_list_topic_subscriptions_with_metadata` interceptor.
420 """
421 return response
422
423 def post_list_topic_subscriptions_with_metadata(
424 self,
425 response: pubsub.ListTopicSubscriptionsResponse,
426 metadata: Sequence[Tuple[str, Union[str, bytes]]],
427 ) -> Tuple[
428 pubsub.ListTopicSubscriptionsResponse, Sequence[Tuple[str, Union[str, bytes]]]
429 ]:
430 """Post-rpc interceptor for list_topic_subscriptions
431
432 Override in a subclass to read or manipulate the response or metadata after it
433 is returned by the Publisher server but before it is returned to user code.
434
435 We recommend only using this `post_list_topic_subscriptions_with_metadata`
436 interceptor in new development instead of the `post_list_topic_subscriptions` interceptor.
437 When both interceptors are used, this `post_list_topic_subscriptions_with_metadata` interceptor runs after the
438 `post_list_topic_subscriptions` interceptor. The (possibly modified) response returned by
439 `post_list_topic_subscriptions` will be passed to
440 `post_list_topic_subscriptions_with_metadata`.
441 """
442 return response, metadata
443
444 def pre_publish(
445 self,
446 request: pubsub.PublishRequest,
447 metadata: Sequence[Tuple[str, Union[str, bytes]]],
448 ) -> Tuple[pubsub.PublishRequest, Sequence[Tuple[str, Union[str, bytes]]]]:
449 """Pre-rpc interceptor for publish
450
451 Override in a subclass to manipulate the request or metadata
452 before they are sent to the Publisher server.
453 """
454 return request, metadata
455
456 def post_publish(self, response: pubsub.PublishResponse) -> pubsub.PublishResponse:
457 """Post-rpc interceptor for publish
458
459 DEPRECATED. Please use the `post_publish_with_metadata`
460 interceptor instead.
461
462 Override in a subclass to read or manipulate the response
463 after it is returned by the Publisher server but before
464 it is returned to user code. This `post_publish` interceptor runs
465 before the `post_publish_with_metadata` interceptor.
466 """
467 return response
468
469 def post_publish_with_metadata(
470 self,
471 response: pubsub.PublishResponse,
472 metadata: Sequence[Tuple[str, Union[str, bytes]]],
473 ) -> Tuple[pubsub.PublishResponse, Sequence[Tuple[str, Union[str, bytes]]]]:
474 """Post-rpc interceptor for publish
475
476 Override in a subclass to read or manipulate the response or metadata after it
477 is returned by the Publisher server but before it is returned to user code.
478
479 We recommend only using this `post_publish_with_metadata`
480 interceptor in new development instead of the `post_publish` interceptor.
481 When both interceptors are used, this `post_publish_with_metadata` interceptor runs after the
482 `post_publish` interceptor. The (possibly modified) response returned by
483 `post_publish` will be passed to
484 `post_publish_with_metadata`.
485 """
486 return response, metadata
487
488 def pre_update_topic(
489 self,
490 request: pubsub.UpdateTopicRequest,
491 metadata: Sequence[Tuple[str, Union[str, bytes]]],
492 ) -> Tuple[pubsub.UpdateTopicRequest, Sequence[Tuple[str, Union[str, bytes]]]]:
493 """Pre-rpc interceptor for update_topic
494
495 Override in a subclass to manipulate the request or metadata
496 before they are sent to the Publisher server.
497 """
498 return request, metadata
499
500 def post_update_topic(self, response: pubsub.Topic) -> pubsub.Topic:
501 """Post-rpc interceptor for update_topic
502
503 DEPRECATED. Please use the `post_update_topic_with_metadata`
504 interceptor instead.
505
506 Override in a subclass to read or manipulate the response
507 after it is returned by the Publisher server but before
508 it is returned to user code. This `post_update_topic` interceptor runs
509 before the `post_update_topic_with_metadata` interceptor.
510 """
511 return response
512
513 def post_update_topic_with_metadata(
514 self, response: pubsub.Topic, metadata: Sequence[Tuple[str, Union[str, bytes]]]
515 ) -> Tuple[pubsub.Topic, Sequence[Tuple[str, Union[str, bytes]]]]:
516 """Post-rpc interceptor for update_topic
517
518 Override in a subclass to read or manipulate the response or metadata after it
519 is returned by the Publisher server but before it is returned to user code.
520
521 We recommend only using this `post_update_topic_with_metadata`
522 interceptor in new development instead of the `post_update_topic` interceptor.
523 When both interceptors are used, this `post_update_topic_with_metadata` interceptor runs after the
524 `post_update_topic` interceptor. The (possibly modified) response returned by
525 `post_update_topic` will be passed to
526 `post_update_topic_with_metadata`.
527 """
528 return response, metadata
529
530 def pre_get_iam_policy(
531 self,
532 request: iam_policy_pb2.GetIamPolicyRequest,
533 metadata: Sequence[Tuple[str, Union[str, bytes]]],
534 ) -> Tuple[
535 iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]
536 ]:
537 """Pre-rpc interceptor for get_iam_policy
538
539 Override in a subclass to manipulate the request or metadata
540 before they are sent to the Publisher server.
541 """
542 return request, metadata
543
544 def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
545 """Post-rpc interceptor for get_iam_policy
546
547 Override in a subclass to manipulate the response
548 after it is returned by the Publisher server but before
549 it is returned to user code.
550 """
551 return response
552
553 def pre_set_iam_policy(
554 self,
555 request: iam_policy_pb2.SetIamPolicyRequest,
556 metadata: Sequence[Tuple[str, Union[str, bytes]]],
557 ) -> Tuple[
558 iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]
559 ]:
560 """Pre-rpc interceptor for set_iam_policy
561
562 Override in a subclass to manipulate the request or metadata
563 before they are sent to the Publisher server.
564 """
565 return request, metadata
566
567 def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
568 """Post-rpc interceptor for set_iam_policy
569
570 Override in a subclass to manipulate the response
571 after it is returned by the Publisher server but before
572 it is returned to user code.
573 """
574 return response
575
576 def pre_test_iam_permissions(
577 self,
578 request: iam_policy_pb2.TestIamPermissionsRequest,
579 metadata: Sequence[Tuple[str, Union[str, bytes]]],
580 ) -> Tuple[
581 iam_policy_pb2.TestIamPermissionsRequest,
582 Sequence[Tuple[str, Union[str, bytes]]],
583 ]:
584 """Pre-rpc interceptor for test_iam_permissions
585
586 Override in a subclass to manipulate the request or metadata
587 before they are sent to the Publisher server.
588 """
589 return request, metadata
590
591 def post_test_iam_permissions(
592 self, response: iam_policy_pb2.TestIamPermissionsResponse
593 ) -> iam_policy_pb2.TestIamPermissionsResponse:
594 """Post-rpc interceptor for test_iam_permissions
595
596 Override in a subclass to manipulate the response
597 after it is returned by the Publisher server but before
598 it is returned to user code.
599 """
600 return response
601
602
603@dataclasses.dataclass
604class PublisherRestStub:
605 _session: AuthorizedSession
606 _host: str
607 _interceptor: PublisherRestInterceptor
608
609
610class PublisherRestTransport(_BasePublisherRestTransport):
611 """REST backend synchronous transport for Publisher.
612
613 The service that an application uses to manipulate topics,
614 and to send messages to a topic.
615
616 This class defines the same methods as the primary client, so the
617 primary client can load the underlying transport implementation
618 and call it.
619
620 It sends JSON representations of protocol buffers over HTTP/1.1
621 """
622
623 def __init__(
624 self,
625 *,
626 host: str = "pubsub.googleapis.com",
627 credentials: Optional[ga_credentials.Credentials] = None,
628 credentials_file: Optional[str] = None,
629 scopes: Optional[Sequence[str]] = None,
630 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
631 quota_project_id: Optional[str] = None,
632 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
633 always_use_jwt_access: Optional[bool] = False,
634 url_scheme: str = "https",
635 interceptor: Optional[PublisherRestInterceptor] = None,
636 api_audience: Optional[str] = None,
637 ) -> None:
638 """Instantiate the transport.
639
640 Args:
641 host (Optional[str]):
642 The hostname to connect to (default: 'pubsub.googleapis.com').
643 credentials (Optional[google.auth.credentials.Credentials]): The
644 authorization credentials to attach to requests. These
645 credentials identify the application to the service; if none
646 are specified, the client will attempt to ascertain the
647 credentials from the environment.
648
649 credentials_file (Optional[str]): A file with credentials that can
650 be loaded with :func:`google.auth.load_credentials_from_file`.
651 This argument is ignored if ``channel`` is provided.
652 scopes (Optional(Sequence[str])): A list of scopes. This argument is
653 ignored if ``channel`` is provided.
654 client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
655 certificate to configure mutual TLS HTTP channel. It is ignored
656 if ``channel`` is provided.
657 quota_project_id (Optional[str]): An optional project to use for billing
658 and quota.
659 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
660 The client info used to send a user-agent string along with
661 API requests. If ``None``, then default info will be used.
662 Generally, you only need to set this if you are developing
663 your own client library.
664 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
665 be used for service account credentials.
666 url_scheme: the protocol scheme for the API endpoint. Normally
667 "https", but for testing or local servers,
668 "http" can be specified.
669 """
670 # Run the base constructor
671 # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
672 # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
673 # credentials object
674 super().__init__(
675 host=host,
676 credentials=credentials,
677 client_info=client_info,
678 always_use_jwt_access=always_use_jwt_access,
679 url_scheme=url_scheme,
680 api_audience=api_audience,
681 )
682 self._session = AuthorizedSession(
683 self._credentials, default_host=self.DEFAULT_HOST
684 )
685 if client_cert_source_for_mtls:
686 self._session.configure_mtls_channel(client_cert_source_for_mtls)
687 self._interceptor = interceptor or PublisherRestInterceptor()
688 self._prep_wrapped_messages(client_info)
689
690 class _CreateTopic(_BasePublisherRestTransport._BaseCreateTopic, PublisherRestStub):
691 def __hash__(self):
692 return hash("PublisherRestTransport.CreateTopic")
693
694 @staticmethod
695 def _get_response(
696 host,
697 metadata,
698 query_params,
699 session,
700 timeout,
701 transcoded_request,
702 body=None,
703 ):
704 uri = transcoded_request["uri"]
705 method = transcoded_request["method"]
706 headers = dict(metadata)
707 headers["Content-Type"] = "application/json"
708 response = getattr(session, method)(
709 "{host}{uri}".format(host=host, uri=uri),
710 timeout=timeout,
711 headers=headers,
712 params=rest_helpers.flatten_query_params(query_params, strict=True),
713 data=body,
714 )
715 return response
716
717 def __call__(
718 self,
719 request: pubsub.Topic,
720 *,
721 retry: OptionalRetry = gapic_v1.method.DEFAULT,
722 timeout: Optional[float] = None,
723 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
724 ) -> pubsub.Topic:
725 r"""Call the create topic method over HTTP.
726
727 Args:
728 request (~.pubsub.Topic):
729 The request object. A topic resource.
730 retry (google.api_core.retry.Retry): Designation of what errors, if any,
731 should be retried.
732 timeout (float): The timeout for this request.
733 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
734 sent along with the request as metadata. Normally, each value must be of type `str`,
735 but for metadata keys ending with the suffix `-bin`, the corresponding values must
736 be of type `bytes`.
737
738 Returns:
739 ~.pubsub.Topic:
740 A topic resource.
741 """
742
743 http_options = (
744 _BasePublisherRestTransport._BaseCreateTopic._get_http_options()
745 )
746
747 request, metadata = self._interceptor.pre_create_topic(request, metadata)
748 transcoded_request = (
749 _BasePublisherRestTransport._BaseCreateTopic._get_transcoded_request(
750 http_options, request
751 )
752 )
753
754 body = _BasePublisherRestTransport._BaseCreateTopic._get_request_body_json(
755 transcoded_request
756 )
757
758 # Jsonify the query params
759 query_params = (
760 _BasePublisherRestTransport._BaseCreateTopic._get_query_params_json(
761 transcoded_request
762 )
763 )
764
765 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
766 logging.DEBUG
767 ): # pragma: NO COVER
768 request_url = "{host}{uri}".format(
769 host=self._host, uri=transcoded_request["uri"]
770 )
771 method = transcoded_request["method"]
772 try:
773 request_payload = type(request).to_json(request)
774 except:
775 request_payload = None
776 http_request = {
777 "payload": request_payload,
778 "requestMethod": method,
779 "requestUrl": request_url,
780 "headers": dict(metadata),
781 }
782 _LOGGER.debug(
783 f"Sending request for google.pubsub_v1.PublisherClient.CreateTopic",
784 extra={
785 "serviceName": "google.pubsub.v1.Publisher",
786 "rpcName": "CreateTopic",
787 "httpRequest": http_request,
788 "metadata": http_request["headers"],
789 },
790 )
791
792 # Send the request
793 response = PublisherRestTransport._CreateTopic._get_response(
794 self._host,
795 metadata,
796 query_params,
797 self._session,
798 timeout,
799 transcoded_request,
800 body,
801 )
802
803 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
804 # subclass.
805 if response.status_code >= 400:
806 raise core_exceptions.from_http_response(response)
807
808 # Return the response
809 resp = pubsub.Topic()
810 pb_resp = pubsub.Topic.pb(resp)
811
812 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
813
814 resp = self._interceptor.post_create_topic(resp)
815 response_metadata = [(k, str(v)) for k, v in response.headers.items()]
816 resp, _ = self._interceptor.post_create_topic_with_metadata(
817 resp, response_metadata
818 )
819 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
820 logging.DEBUG
821 ): # pragma: NO COVER
822 try:
823 response_payload = pubsub.Topic.to_json(response)
824 except:
825 response_payload = None
826 http_response = {
827 "payload": response_payload,
828 "headers": dict(response.headers),
829 "status": response.status_code,
830 }
831 _LOGGER.debug(
832 "Received response for google.pubsub_v1.PublisherClient.create_topic",
833 extra={
834 "serviceName": "google.pubsub.v1.Publisher",
835 "rpcName": "CreateTopic",
836 "metadata": http_response["headers"],
837 "httpResponse": http_response,
838 },
839 )
840 return resp
841
842 class _DeleteTopic(_BasePublisherRestTransport._BaseDeleteTopic, PublisherRestStub):
843 def __hash__(self):
844 return hash("PublisherRestTransport.DeleteTopic")
845
846 @staticmethod
847 def _get_response(
848 host,
849 metadata,
850 query_params,
851 session,
852 timeout,
853 transcoded_request,
854 body=None,
855 ):
856 uri = transcoded_request["uri"]
857 method = transcoded_request["method"]
858 headers = dict(metadata)
859 headers["Content-Type"] = "application/json"
860 response = getattr(session, method)(
861 "{host}{uri}".format(host=host, uri=uri),
862 timeout=timeout,
863 headers=headers,
864 params=rest_helpers.flatten_query_params(query_params, strict=True),
865 )
866 return response
867
868 def __call__(
869 self,
870 request: pubsub.DeleteTopicRequest,
871 *,
872 retry: OptionalRetry = gapic_v1.method.DEFAULT,
873 timeout: Optional[float] = None,
874 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
875 ):
876 r"""Call the delete topic method over HTTP.
877
878 Args:
879 request (~.pubsub.DeleteTopicRequest):
880 The request object. Request for the ``DeleteTopic`` method.
881 retry (google.api_core.retry.Retry): Designation of what errors, if any,
882 should be retried.
883 timeout (float): The timeout for this request.
884 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
885 sent along with the request as metadata. Normally, each value must be of type `str`,
886 but for metadata keys ending with the suffix `-bin`, the corresponding values must
887 be of type `bytes`.
888 """
889
890 http_options = (
891 _BasePublisherRestTransport._BaseDeleteTopic._get_http_options()
892 )
893
894 request, metadata = self._interceptor.pre_delete_topic(request, metadata)
895 transcoded_request = (
896 _BasePublisherRestTransport._BaseDeleteTopic._get_transcoded_request(
897 http_options, request
898 )
899 )
900
901 # Jsonify the query params
902 query_params = (
903 _BasePublisherRestTransport._BaseDeleteTopic._get_query_params_json(
904 transcoded_request
905 )
906 )
907
908 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
909 logging.DEBUG
910 ): # pragma: NO COVER
911 request_url = "{host}{uri}".format(
912 host=self._host, uri=transcoded_request["uri"]
913 )
914 method = transcoded_request["method"]
915 try:
916 request_payload = json_format.MessageToJson(request)
917 except:
918 request_payload = None
919 http_request = {
920 "payload": request_payload,
921 "requestMethod": method,
922 "requestUrl": request_url,
923 "headers": dict(metadata),
924 }
925 _LOGGER.debug(
926 f"Sending request for google.pubsub_v1.PublisherClient.DeleteTopic",
927 extra={
928 "serviceName": "google.pubsub.v1.Publisher",
929 "rpcName": "DeleteTopic",
930 "httpRequest": http_request,
931 "metadata": http_request["headers"],
932 },
933 )
934
935 # Send the request
936 response = PublisherRestTransport._DeleteTopic._get_response(
937 self._host,
938 metadata,
939 query_params,
940 self._session,
941 timeout,
942 transcoded_request,
943 )
944
945 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
946 # subclass.
947 if response.status_code >= 400:
948 raise core_exceptions.from_http_response(response)
949
950 class _DetachSubscription(
951 _BasePublisherRestTransport._BaseDetachSubscription, PublisherRestStub
952 ):
953 def __hash__(self):
954 return hash("PublisherRestTransport.DetachSubscription")
955
956 @staticmethod
957 def _get_response(
958 host,
959 metadata,
960 query_params,
961 session,
962 timeout,
963 transcoded_request,
964 body=None,
965 ):
966 uri = transcoded_request["uri"]
967 method = transcoded_request["method"]
968 headers = dict(metadata)
969 headers["Content-Type"] = "application/json"
970 response = getattr(session, method)(
971 "{host}{uri}".format(host=host, uri=uri),
972 timeout=timeout,
973 headers=headers,
974 params=rest_helpers.flatten_query_params(query_params, strict=True),
975 )
976 return response
977
978 def __call__(
979 self,
980 request: pubsub.DetachSubscriptionRequest,
981 *,
982 retry: OptionalRetry = gapic_v1.method.DEFAULT,
983 timeout: Optional[float] = None,
984 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
985 ) -> pubsub.DetachSubscriptionResponse:
986 r"""Call the detach subscription method over HTTP.
987
988 Args:
989 request (~.pubsub.DetachSubscriptionRequest):
990 The request object. Request for the DetachSubscription
991 method.
992 retry (google.api_core.retry.Retry): Designation of what errors, if any,
993 should be retried.
994 timeout (float): The timeout for this request.
995 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
996 sent along with the request as metadata. Normally, each value must be of type `str`,
997 but for metadata keys ending with the suffix `-bin`, the corresponding values must
998 be of type `bytes`.
999
1000 Returns:
1001 ~.pubsub.DetachSubscriptionResponse:
1002 Response for the DetachSubscription
1003 method. Reserved for future use.
1004
1005 """
1006
1007 http_options = (
1008 _BasePublisherRestTransport._BaseDetachSubscription._get_http_options()
1009 )
1010
1011 request, metadata = self._interceptor.pre_detach_subscription(
1012 request, metadata
1013 )
1014 transcoded_request = _BasePublisherRestTransport._BaseDetachSubscription._get_transcoded_request(
1015 http_options, request
1016 )
1017
1018 # Jsonify the query params
1019 query_params = _BasePublisherRestTransport._BaseDetachSubscription._get_query_params_json(
1020 transcoded_request
1021 )
1022
1023 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1024 logging.DEBUG
1025 ): # pragma: NO COVER
1026 request_url = "{host}{uri}".format(
1027 host=self._host, uri=transcoded_request["uri"]
1028 )
1029 method = transcoded_request["method"]
1030 try:
1031 request_payload = type(request).to_json(request)
1032 except:
1033 request_payload = None
1034 http_request = {
1035 "payload": request_payload,
1036 "requestMethod": method,
1037 "requestUrl": request_url,
1038 "headers": dict(metadata),
1039 }
1040 _LOGGER.debug(
1041 f"Sending request for google.pubsub_v1.PublisherClient.DetachSubscription",
1042 extra={
1043 "serviceName": "google.pubsub.v1.Publisher",
1044 "rpcName": "DetachSubscription",
1045 "httpRequest": http_request,
1046 "metadata": http_request["headers"],
1047 },
1048 )
1049
1050 # Send the request
1051 response = PublisherRestTransport._DetachSubscription._get_response(
1052 self._host,
1053 metadata,
1054 query_params,
1055 self._session,
1056 timeout,
1057 transcoded_request,
1058 )
1059
1060 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1061 # subclass.
1062 if response.status_code >= 400:
1063 raise core_exceptions.from_http_response(response)
1064
1065 # Return the response
1066 resp = pubsub.DetachSubscriptionResponse()
1067 pb_resp = pubsub.DetachSubscriptionResponse.pb(resp)
1068
1069 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1070
1071 resp = self._interceptor.post_detach_subscription(resp)
1072 response_metadata = [(k, str(v)) for k, v in response.headers.items()]
1073 resp, _ = self._interceptor.post_detach_subscription_with_metadata(
1074 resp, response_metadata
1075 )
1076 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1077 logging.DEBUG
1078 ): # pragma: NO COVER
1079 try:
1080 response_payload = pubsub.DetachSubscriptionResponse.to_json(
1081 response
1082 )
1083 except:
1084 response_payload = None
1085 http_response = {
1086 "payload": response_payload,
1087 "headers": dict(response.headers),
1088 "status": response.status_code,
1089 }
1090 _LOGGER.debug(
1091 "Received response for google.pubsub_v1.PublisherClient.detach_subscription",
1092 extra={
1093 "serviceName": "google.pubsub.v1.Publisher",
1094 "rpcName": "DetachSubscription",
1095 "metadata": http_response["headers"],
1096 "httpResponse": http_response,
1097 },
1098 )
1099 return resp
1100
1101 class _GetTopic(_BasePublisherRestTransport._BaseGetTopic, PublisherRestStub):
1102 def __hash__(self):
1103 return hash("PublisherRestTransport.GetTopic")
1104
1105 @staticmethod
1106 def _get_response(
1107 host,
1108 metadata,
1109 query_params,
1110 session,
1111 timeout,
1112 transcoded_request,
1113 body=None,
1114 ):
1115 uri = transcoded_request["uri"]
1116 method = transcoded_request["method"]
1117 headers = dict(metadata)
1118 headers["Content-Type"] = "application/json"
1119 response = getattr(session, method)(
1120 "{host}{uri}".format(host=host, uri=uri),
1121 timeout=timeout,
1122 headers=headers,
1123 params=rest_helpers.flatten_query_params(query_params, strict=True),
1124 )
1125 return response
1126
1127 def __call__(
1128 self,
1129 request: pubsub.GetTopicRequest,
1130 *,
1131 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1132 timeout: Optional[float] = None,
1133 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1134 ) -> pubsub.Topic:
1135 r"""Call the get topic method over HTTP.
1136
1137 Args:
1138 request (~.pubsub.GetTopicRequest):
1139 The request object. Request for the GetTopic method.
1140 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1141 should be retried.
1142 timeout (float): The timeout for this request.
1143 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1144 sent along with the request as metadata. Normally, each value must be of type `str`,
1145 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1146 be of type `bytes`.
1147
1148 Returns:
1149 ~.pubsub.Topic:
1150 A topic resource.
1151 """
1152
1153 http_options = _BasePublisherRestTransport._BaseGetTopic._get_http_options()
1154
1155 request, metadata = self._interceptor.pre_get_topic(request, metadata)
1156 transcoded_request = (
1157 _BasePublisherRestTransport._BaseGetTopic._get_transcoded_request(
1158 http_options, request
1159 )
1160 )
1161
1162 # Jsonify the query params
1163 query_params = (
1164 _BasePublisherRestTransport._BaseGetTopic._get_query_params_json(
1165 transcoded_request
1166 )
1167 )
1168
1169 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1170 logging.DEBUG
1171 ): # pragma: NO COVER
1172 request_url = "{host}{uri}".format(
1173 host=self._host, uri=transcoded_request["uri"]
1174 )
1175 method = transcoded_request["method"]
1176 try:
1177 request_payload = type(request).to_json(request)
1178 except:
1179 request_payload = None
1180 http_request = {
1181 "payload": request_payload,
1182 "requestMethod": method,
1183 "requestUrl": request_url,
1184 "headers": dict(metadata),
1185 }
1186 _LOGGER.debug(
1187 f"Sending request for google.pubsub_v1.PublisherClient.GetTopic",
1188 extra={
1189 "serviceName": "google.pubsub.v1.Publisher",
1190 "rpcName": "GetTopic",
1191 "httpRequest": http_request,
1192 "metadata": http_request["headers"],
1193 },
1194 )
1195
1196 # Send the request
1197 response = PublisherRestTransport._GetTopic._get_response(
1198 self._host,
1199 metadata,
1200 query_params,
1201 self._session,
1202 timeout,
1203 transcoded_request,
1204 )
1205
1206 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1207 # subclass.
1208 if response.status_code >= 400:
1209 raise core_exceptions.from_http_response(response)
1210
1211 # Return the response
1212 resp = pubsub.Topic()
1213 pb_resp = pubsub.Topic.pb(resp)
1214
1215 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1216
1217 resp = self._interceptor.post_get_topic(resp)
1218 response_metadata = [(k, str(v)) for k, v in response.headers.items()]
1219 resp, _ = self._interceptor.post_get_topic_with_metadata(
1220 resp, response_metadata
1221 )
1222 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1223 logging.DEBUG
1224 ): # pragma: NO COVER
1225 try:
1226 response_payload = pubsub.Topic.to_json(response)
1227 except:
1228 response_payload = None
1229 http_response = {
1230 "payload": response_payload,
1231 "headers": dict(response.headers),
1232 "status": response.status_code,
1233 }
1234 _LOGGER.debug(
1235 "Received response for google.pubsub_v1.PublisherClient.get_topic",
1236 extra={
1237 "serviceName": "google.pubsub.v1.Publisher",
1238 "rpcName": "GetTopic",
1239 "metadata": http_response["headers"],
1240 "httpResponse": http_response,
1241 },
1242 )
1243 return resp
1244
1245 class _ListTopics(_BasePublisherRestTransport._BaseListTopics, PublisherRestStub):
1246 def __hash__(self):
1247 return hash("PublisherRestTransport.ListTopics")
1248
1249 @staticmethod
1250 def _get_response(
1251 host,
1252 metadata,
1253 query_params,
1254 session,
1255 timeout,
1256 transcoded_request,
1257 body=None,
1258 ):
1259 uri = transcoded_request["uri"]
1260 method = transcoded_request["method"]
1261 headers = dict(metadata)
1262 headers["Content-Type"] = "application/json"
1263 response = getattr(session, method)(
1264 "{host}{uri}".format(host=host, uri=uri),
1265 timeout=timeout,
1266 headers=headers,
1267 params=rest_helpers.flatten_query_params(query_params, strict=True),
1268 )
1269 return response
1270
1271 def __call__(
1272 self,
1273 request: pubsub.ListTopicsRequest,
1274 *,
1275 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1276 timeout: Optional[float] = None,
1277 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1278 ) -> pubsub.ListTopicsResponse:
1279 r"""Call the list topics method over HTTP.
1280
1281 Args:
1282 request (~.pubsub.ListTopicsRequest):
1283 The request object. Request for the ``ListTopics`` method.
1284 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1285 should be retried.
1286 timeout (float): The timeout for this request.
1287 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1288 sent along with the request as metadata. Normally, each value must be of type `str`,
1289 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1290 be of type `bytes`.
1291
1292 Returns:
1293 ~.pubsub.ListTopicsResponse:
1294 Response for the ``ListTopics`` method.
1295 """
1296
1297 http_options = (
1298 _BasePublisherRestTransport._BaseListTopics._get_http_options()
1299 )
1300
1301 request, metadata = self._interceptor.pre_list_topics(request, metadata)
1302 transcoded_request = (
1303 _BasePublisherRestTransport._BaseListTopics._get_transcoded_request(
1304 http_options, request
1305 )
1306 )
1307
1308 # Jsonify the query params
1309 query_params = (
1310 _BasePublisherRestTransport._BaseListTopics._get_query_params_json(
1311 transcoded_request
1312 )
1313 )
1314
1315 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1316 logging.DEBUG
1317 ): # pragma: NO COVER
1318 request_url = "{host}{uri}".format(
1319 host=self._host, uri=transcoded_request["uri"]
1320 )
1321 method = transcoded_request["method"]
1322 try:
1323 request_payload = type(request).to_json(request)
1324 except:
1325 request_payload = None
1326 http_request = {
1327 "payload": request_payload,
1328 "requestMethod": method,
1329 "requestUrl": request_url,
1330 "headers": dict(metadata),
1331 }
1332 _LOGGER.debug(
1333 f"Sending request for google.pubsub_v1.PublisherClient.ListTopics",
1334 extra={
1335 "serviceName": "google.pubsub.v1.Publisher",
1336 "rpcName": "ListTopics",
1337 "httpRequest": http_request,
1338 "metadata": http_request["headers"],
1339 },
1340 )
1341
1342 # Send the request
1343 response = PublisherRestTransport._ListTopics._get_response(
1344 self._host,
1345 metadata,
1346 query_params,
1347 self._session,
1348 timeout,
1349 transcoded_request,
1350 )
1351
1352 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1353 # subclass.
1354 if response.status_code >= 400:
1355 raise core_exceptions.from_http_response(response)
1356
1357 # Return the response
1358 resp = pubsub.ListTopicsResponse()
1359 pb_resp = pubsub.ListTopicsResponse.pb(resp)
1360
1361 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1362
1363 resp = self._interceptor.post_list_topics(resp)
1364 response_metadata = [(k, str(v)) for k, v in response.headers.items()]
1365 resp, _ = self._interceptor.post_list_topics_with_metadata(
1366 resp, response_metadata
1367 )
1368 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1369 logging.DEBUG
1370 ): # pragma: NO COVER
1371 try:
1372 response_payload = pubsub.ListTopicsResponse.to_json(response)
1373 except:
1374 response_payload = None
1375 http_response = {
1376 "payload": response_payload,
1377 "headers": dict(response.headers),
1378 "status": response.status_code,
1379 }
1380 _LOGGER.debug(
1381 "Received response for google.pubsub_v1.PublisherClient.list_topics",
1382 extra={
1383 "serviceName": "google.pubsub.v1.Publisher",
1384 "rpcName": "ListTopics",
1385 "metadata": http_response["headers"],
1386 "httpResponse": http_response,
1387 },
1388 )
1389 return resp
1390
1391 class _ListTopicSnapshots(
1392 _BasePublisherRestTransport._BaseListTopicSnapshots, PublisherRestStub
1393 ):
1394 def __hash__(self):
1395 return hash("PublisherRestTransport.ListTopicSnapshots")
1396
1397 @staticmethod
1398 def _get_response(
1399 host,
1400 metadata,
1401 query_params,
1402 session,
1403 timeout,
1404 transcoded_request,
1405 body=None,
1406 ):
1407 uri = transcoded_request["uri"]
1408 method = transcoded_request["method"]
1409 headers = dict(metadata)
1410 headers["Content-Type"] = "application/json"
1411 response = getattr(session, method)(
1412 "{host}{uri}".format(host=host, uri=uri),
1413 timeout=timeout,
1414 headers=headers,
1415 params=rest_helpers.flatten_query_params(query_params, strict=True),
1416 )
1417 return response
1418
1419 def __call__(
1420 self,
1421 request: pubsub.ListTopicSnapshotsRequest,
1422 *,
1423 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1424 timeout: Optional[float] = None,
1425 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1426 ) -> pubsub.ListTopicSnapshotsResponse:
1427 r"""Call the list topic snapshots method over HTTP.
1428
1429 Args:
1430 request (~.pubsub.ListTopicSnapshotsRequest):
1431 The request object. Request for the ``ListTopicSnapshots`` method.
1432 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1433 should be retried.
1434 timeout (float): The timeout for this request.
1435 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1436 sent along with the request as metadata. Normally, each value must be of type `str`,
1437 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1438 be of type `bytes`.
1439
1440 Returns:
1441 ~.pubsub.ListTopicSnapshotsResponse:
1442 Response for the ``ListTopicSnapshots`` method.
1443 """
1444
1445 http_options = (
1446 _BasePublisherRestTransport._BaseListTopicSnapshots._get_http_options()
1447 )
1448
1449 request, metadata = self._interceptor.pre_list_topic_snapshots(
1450 request, metadata
1451 )
1452 transcoded_request = _BasePublisherRestTransport._BaseListTopicSnapshots._get_transcoded_request(
1453 http_options, request
1454 )
1455
1456 # Jsonify the query params
1457 query_params = _BasePublisherRestTransport._BaseListTopicSnapshots._get_query_params_json(
1458 transcoded_request
1459 )
1460
1461 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1462 logging.DEBUG
1463 ): # pragma: NO COVER
1464 request_url = "{host}{uri}".format(
1465 host=self._host, uri=transcoded_request["uri"]
1466 )
1467 method = transcoded_request["method"]
1468 try:
1469 request_payload = type(request).to_json(request)
1470 except:
1471 request_payload = None
1472 http_request = {
1473 "payload": request_payload,
1474 "requestMethod": method,
1475 "requestUrl": request_url,
1476 "headers": dict(metadata),
1477 }
1478 _LOGGER.debug(
1479 f"Sending request for google.pubsub_v1.PublisherClient.ListTopicSnapshots",
1480 extra={
1481 "serviceName": "google.pubsub.v1.Publisher",
1482 "rpcName": "ListTopicSnapshots",
1483 "httpRequest": http_request,
1484 "metadata": http_request["headers"],
1485 },
1486 )
1487
1488 # Send the request
1489 response = PublisherRestTransport._ListTopicSnapshots._get_response(
1490 self._host,
1491 metadata,
1492 query_params,
1493 self._session,
1494 timeout,
1495 transcoded_request,
1496 )
1497
1498 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1499 # subclass.
1500 if response.status_code >= 400:
1501 raise core_exceptions.from_http_response(response)
1502
1503 # Return the response
1504 resp = pubsub.ListTopicSnapshotsResponse()
1505 pb_resp = pubsub.ListTopicSnapshotsResponse.pb(resp)
1506
1507 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1508
1509 resp = self._interceptor.post_list_topic_snapshots(resp)
1510 response_metadata = [(k, str(v)) for k, v in response.headers.items()]
1511 resp, _ = self._interceptor.post_list_topic_snapshots_with_metadata(
1512 resp, response_metadata
1513 )
1514 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1515 logging.DEBUG
1516 ): # pragma: NO COVER
1517 try:
1518 response_payload = pubsub.ListTopicSnapshotsResponse.to_json(
1519 response
1520 )
1521 except:
1522 response_payload = None
1523 http_response = {
1524 "payload": response_payload,
1525 "headers": dict(response.headers),
1526 "status": response.status_code,
1527 }
1528 _LOGGER.debug(
1529 "Received response for google.pubsub_v1.PublisherClient.list_topic_snapshots",
1530 extra={
1531 "serviceName": "google.pubsub.v1.Publisher",
1532 "rpcName": "ListTopicSnapshots",
1533 "metadata": http_response["headers"],
1534 "httpResponse": http_response,
1535 },
1536 )
1537 return resp
1538
1539 class _ListTopicSubscriptions(
1540 _BasePublisherRestTransport._BaseListTopicSubscriptions, PublisherRestStub
1541 ):
1542 def __hash__(self):
1543 return hash("PublisherRestTransport.ListTopicSubscriptions")
1544
1545 @staticmethod
1546 def _get_response(
1547 host,
1548 metadata,
1549 query_params,
1550 session,
1551 timeout,
1552 transcoded_request,
1553 body=None,
1554 ):
1555 uri = transcoded_request["uri"]
1556 method = transcoded_request["method"]
1557 headers = dict(metadata)
1558 headers["Content-Type"] = "application/json"
1559 response = getattr(session, method)(
1560 "{host}{uri}".format(host=host, uri=uri),
1561 timeout=timeout,
1562 headers=headers,
1563 params=rest_helpers.flatten_query_params(query_params, strict=True),
1564 )
1565 return response
1566
1567 def __call__(
1568 self,
1569 request: pubsub.ListTopicSubscriptionsRequest,
1570 *,
1571 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1572 timeout: Optional[float] = None,
1573 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1574 ) -> pubsub.ListTopicSubscriptionsResponse:
1575 r"""Call the list topic subscriptions method over HTTP.
1576
1577 Args:
1578 request (~.pubsub.ListTopicSubscriptionsRequest):
1579 The request object. Request for the ``ListTopicSubscriptions`` method.
1580 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1581 should be retried.
1582 timeout (float): The timeout for this request.
1583 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1584 sent along with the request as metadata. Normally, each value must be of type `str`,
1585 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1586 be of type `bytes`.
1587
1588 Returns:
1589 ~.pubsub.ListTopicSubscriptionsResponse:
1590 Response for the ``ListTopicSubscriptions`` method.
1591 """
1592
1593 http_options = (
1594 _BasePublisherRestTransport._BaseListTopicSubscriptions._get_http_options()
1595 )
1596
1597 request, metadata = self._interceptor.pre_list_topic_subscriptions(
1598 request, metadata
1599 )
1600 transcoded_request = _BasePublisherRestTransport._BaseListTopicSubscriptions._get_transcoded_request(
1601 http_options, request
1602 )
1603
1604 # Jsonify the query params
1605 query_params = _BasePublisherRestTransport._BaseListTopicSubscriptions._get_query_params_json(
1606 transcoded_request
1607 )
1608
1609 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1610 logging.DEBUG
1611 ): # pragma: NO COVER
1612 request_url = "{host}{uri}".format(
1613 host=self._host, uri=transcoded_request["uri"]
1614 )
1615 method = transcoded_request["method"]
1616 try:
1617 request_payload = type(request).to_json(request)
1618 except:
1619 request_payload = None
1620 http_request = {
1621 "payload": request_payload,
1622 "requestMethod": method,
1623 "requestUrl": request_url,
1624 "headers": dict(metadata),
1625 }
1626 _LOGGER.debug(
1627 f"Sending request for google.pubsub_v1.PublisherClient.ListTopicSubscriptions",
1628 extra={
1629 "serviceName": "google.pubsub.v1.Publisher",
1630 "rpcName": "ListTopicSubscriptions",
1631 "httpRequest": http_request,
1632 "metadata": http_request["headers"],
1633 },
1634 )
1635
1636 # Send the request
1637 response = PublisherRestTransport._ListTopicSubscriptions._get_response(
1638 self._host,
1639 metadata,
1640 query_params,
1641 self._session,
1642 timeout,
1643 transcoded_request,
1644 )
1645
1646 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1647 # subclass.
1648 if response.status_code >= 400:
1649 raise core_exceptions.from_http_response(response)
1650
1651 # Return the response
1652 resp = pubsub.ListTopicSubscriptionsResponse()
1653 pb_resp = pubsub.ListTopicSubscriptionsResponse.pb(resp)
1654
1655 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1656
1657 resp = self._interceptor.post_list_topic_subscriptions(resp)
1658 response_metadata = [(k, str(v)) for k, v in response.headers.items()]
1659 resp, _ = self._interceptor.post_list_topic_subscriptions_with_metadata(
1660 resp, response_metadata
1661 )
1662 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1663 logging.DEBUG
1664 ): # pragma: NO COVER
1665 try:
1666 response_payload = pubsub.ListTopicSubscriptionsResponse.to_json(
1667 response
1668 )
1669 except:
1670 response_payload = None
1671 http_response = {
1672 "payload": response_payload,
1673 "headers": dict(response.headers),
1674 "status": response.status_code,
1675 }
1676 _LOGGER.debug(
1677 "Received response for google.pubsub_v1.PublisherClient.list_topic_subscriptions",
1678 extra={
1679 "serviceName": "google.pubsub.v1.Publisher",
1680 "rpcName": "ListTopicSubscriptions",
1681 "metadata": http_response["headers"],
1682 "httpResponse": http_response,
1683 },
1684 )
1685 return resp
1686
1687 class _Publish(_BasePublisherRestTransport._BasePublish, PublisherRestStub):
1688 def __hash__(self):
1689 return hash("PublisherRestTransport.Publish")
1690
1691 @staticmethod
1692 def _get_response(
1693 host,
1694 metadata,
1695 query_params,
1696 session,
1697 timeout,
1698 transcoded_request,
1699 body=None,
1700 ):
1701 uri = transcoded_request["uri"]
1702 method = transcoded_request["method"]
1703 headers = dict(metadata)
1704 headers["Content-Type"] = "application/json"
1705 response = getattr(session, method)(
1706 "{host}{uri}".format(host=host, uri=uri),
1707 timeout=timeout,
1708 headers=headers,
1709 params=rest_helpers.flatten_query_params(query_params, strict=True),
1710 data=body,
1711 )
1712 return response
1713
1714 def __call__(
1715 self,
1716 request: pubsub.PublishRequest,
1717 *,
1718 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1719 timeout: Optional[float] = None,
1720 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1721 ) -> pubsub.PublishResponse:
1722 r"""Call the publish method over HTTP.
1723
1724 Args:
1725 request (~.pubsub.PublishRequest):
1726 The request object. Request for the Publish method.
1727 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1728 should be retried.
1729 timeout (float): The timeout for this request.
1730 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1731 sent along with the request as metadata. Normally, each value must be of type `str`,
1732 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1733 be of type `bytes`.
1734
1735 Returns:
1736 ~.pubsub.PublishResponse:
1737 Response for the ``Publish`` method.
1738 """
1739
1740 http_options = _BasePublisherRestTransport._BasePublish._get_http_options()
1741
1742 request, metadata = self._interceptor.pre_publish(request, metadata)
1743 transcoded_request = (
1744 _BasePublisherRestTransport._BasePublish._get_transcoded_request(
1745 http_options, request
1746 )
1747 )
1748
1749 body = _BasePublisherRestTransport._BasePublish._get_request_body_json(
1750 transcoded_request
1751 )
1752
1753 # Jsonify the query params
1754 query_params = (
1755 _BasePublisherRestTransport._BasePublish._get_query_params_json(
1756 transcoded_request
1757 )
1758 )
1759
1760 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1761 logging.DEBUG
1762 ): # pragma: NO COVER
1763 request_url = "{host}{uri}".format(
1764 host=self._host, uri=transcoded_request["uri"]
1765 )
1766 method = transcoded_request["method"]
1767 try:
1768 request_payload = type(request).to_json(request)
1769 except:
1770 request_payload = None
1771 http_request = {
1772 "payload": request_payload,
1773 "requestMethod": method,
1774 "requestUrl": request_url,
1775 "headers": dict(metadata),
1776 }
1777 _LOGGER.debug(
1778 f"Sending request for google.pubsub_v1.PublisherClient.Publish",
1779 extra={
1780 "serviceName": "google.pubsub.v1.Publisher",
1781 "rpcName": "Publish",
1782 "httpRequest": http_request,
1783 "metadata": http_request["headers"],
1784 },
1785 )
1786
1787 # Send the request
1788 response = PublisherRestTransport._Publish._get_response(
1789 self._host,
1790 metadata,
1791 query_params,
1792 self._session,
1793 timeout,
1794 transcoded_request,
1795 body,
1796 )
1797
1798 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1799 # subclass.
1800 if response.status_code >= 400:
1801 raise core_exceptions.from_http_response(response)
1802
1803 # Return the response
1804 resp = pubsub.PublishResponse()
1805 pb_resp = pubsub.PublishResponse.pb(resp)
1806
1807 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1808
1809 resp = self._interceptor.post_publish(resp)
1810 response_metadata = [(k, str(v)) for k, v in response.headers.items()]
1811 resp, _ = self._interceptor.post_publish_with_metadata(
1812 resp, response_metadata
1813 )
1814 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1815 logging.DEBUG
1816 ): # pragma: NO COVER
1817 try:
1818 response_payload = pubsub.PublishResponse.to_json(response)
1819 except:
1820 response_payload = None
1821 http_response = {
1822 "payload": response_payload,
1823 "headers": dict(response.headers),
1824 "status": response.status_code,
1825 }
1826 _LOGGER.debug(
1827 "Received response for google.pubsub_v1.PublisherClient.publish",
1828 extra={
1829 "serviceName": "google.pubsub.v1.Publisher",
1830 "rpcName": "Publish",
1831 "metadata": http_response["headers"],
1832 "httpResponse": http_response,
1833 },
1834 )
1835 return resp
1836
1837 class _UpdateTopic(_BasePublisherRestTransport._BaseUpdateTopic, PublisherRestStub):
1838 def __hash__(self):
1839 return hash("PublisherRestTransport.UpdateTopic")
1840
1841 @staticmethod
1842 def _get_response(
1843 host,
1844 metadata,
1845 query_params,
1846 session,
1847 timeout,
1848 transcoded_request,
1849 body=None,
1850 ):
1851 uri = transcoded_request["uri"]
1852 method = transcoded_request["method"]
1853 headers = dict(metadata)
1854 headers["Content-Type"] = "application/json"
1855 response = getattr(session, method)(
1856 "{host}{uri}".format(host=host, uri=uri),
1857 timeout=timeout,
1858 headers=headers,
1859 params=rest_helpers.flatten_query_params(query_params, strict=True),
1860 data=body,
1861 )
1862 return response
1863
1864 def __call__(
1865 self,
1866 request: pubsub.UpdateTopicRequest,
1867 *,
1868 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1869 timeout: Optional[float] = None,
1870 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1871 ) -> pubsub.Topic:
1872 r"""Call the update topic method over HTTP.
1873
1874 Args:
1875 request (~.pubsub.UpdateTopicRequest):
1876 The request object. Request for the UpdateTopic method.
1877 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1878 should be retried.
1879 timeout (float): The timeout for this request.
1880 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1881 sent along with the request as metadata. Normally, each value must be of type `str`,
1882 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1883 be of type `bytes`.
1884
1885 Returns:
1886 ~.pubsub.Topic:
1887 A topic resource.
1888 """
1889
1890 http_options = (
1891 _BasePublisherRestTransport._BaseUpdateTopic._get_http_options()
1892 )
1893
1894 request, metadata = self._interceptor.pre_update_topic(request, metadata)
1895 transcoded_request = (
1896 _BasePublisherRestTransport._BaseUpdateTopic._get_transcoded_request(
1897 http_options, request
1898 )
1899 )
1900
1901 body = _BasePublisherRestTransport._BaseUpdateTopic._get_request_body_json(
1902 transcoded_request
1903 )
1904
1905 # Jsonify the query params
1906 query_params = (
1907 _BasePublisherRestTransport._BaseUpdateTopic._get_query_params_json(
1908 transcoded_request
1909 )
1910 )
1911
1912 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1913 logging.DEBUG
1914 ): # pragma: NO COVER
1915 request_url = "{host}{uri}".format(
1916 host=self._host, uri=transcoded_request["uri"]
1917 )
1918 method = transcoded_request["method"]
1919 try:
1920 request_payload = type(request).to_json(request)
1921 except:
1922 request_payload = None
1923 http_request = {
1924 "payload": request_payload,
1925 "requestMethod": method,
1926 "requestUrl": request_url,
1927 "headers": dict(metadata),
1928 }
1929 _LOGGER.debug(
1930 f"Sending request for google.pubsub_v1.PublisherClient.UpdateTopic",
1931 extra={
1932 "serviceName": "google.pubsub.v1.Publisher",
1933 "rpcName": "UpdateTopic",
1934 "httpRequest": http_request,
1935 "metadata": http_request["headers"],
1936 },
1937 )
1938
1939 # Send the request
1940 response = PublisherRestTransport._UpdateTopic._get_response(
1941 self._host,
1942 metadata,
1943 query_params,
1944 self._session,
1945 timeout,
1946 transcoded_request,
1947 body,
1948 )
1949
1950 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1951 # subclass.
1952 if response.status_code >= 400:
1953 raise core_exceptions.from_http_response(response)
1954
1955 # Return the response
1956 resp = pubsub.Topic()
1957 pb_resp = pubsub.Topic.pb(resp)
1958
1959 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1960
1961 resp = self._interceptor.post_update_topic(resp)
1962 response_metadata = [(k, str(v)) for k, v in response.headers.items()]
1963 resp, _ = self._interceptor.post_update_topic_with_metadata(
1964 resp, response_metadata
1965 )
1966 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1967 logging.DEBUG
1968 ): # pragma: NO COVER
1969 try:
1970 response_payload = pubsub.Topic.to_json(response)
1971 except:
1972 response_payload = None
1973 http_response = {
1974 "payload": response_payload,
1975 "headers": dict(response.headers),
1976 "status": response.status_code,
1977 }
1978 _LOGGER.debug(
1979 "Received response for google.pubsub_v1.PublisherClient.update_topic",
1980 extra={
1981 "serviceName": "google.pubsub.v1.Publisher",
1982 "rpcName": "UpdateTopic",
1983 "metadata": http_response["headers"],
1984 "httpResponse": http_response,
1985 },
1986 )
1987 return resp
1988
1989 @property
1990 def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]:
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._CreateTopic(self._session, self._host, self._interceptor) # type: ignore
1994
1995 @property
1996 def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty_pb2.Empty]:
1997 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1998 # In C++ this would require a dynamic_cast
1999 return self._DeleteTopic(self._session, self._host, self._interceptor) # type: ignore
2000
2001 @property
2002 def detach_subscription(
2003 self,
2004 ) -> Callable[
2005 [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse
2006 ]:
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._DetachSubscription(self._session, self._host, self._interceptor) # type: ignore
2010
2011 @property
2012 def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]:
2013 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2014 # In C++ this would require a dynamic_cast
2015 return self._GetTopic(self._session, self._host, self._interceptor) # type: ignore
2016
2017 @property
2018 def list_topics(
2019 self,
2020 ) -> Callable[[pubsub.ListTopicsRequest], pubsub.ListTopicsResponse]:
2021 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2022 # In C++ this would require a dynamic_cast
2023 return self._ListTopics(self._session, self._host, self._interceptor) # type: ignore
2024
2025 @property
2026 def list_topic_snapshots(
2027 self,
2028 ) -> Callable[
2029 [pubsub.ListTopicSnapshotsRequest], pubsub.ListTopicSnapshotsResponse
2030 ]:
2031 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2032 # In C++ this would require a dynamic_cast
2033 return self._ListTopicSnapshots(self._session, self._host, self._interceptor) # type: ignore
2034
2035 @property
2036 def list_topic_subscriptions(
2037 self,
2038 ) -> Callable[
2039 [pubsub.ListTopicSubscriptionsRequest], pubsub.ListTopicSubscriptionsResponse
2040 ]:
2041 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2042 # In C++ this would require a dynamic_cast
2043 return self._ListTopicSubscriptions(self._session, self._host, self._interceptor) # type: ignore
2044
2045 @property
2046 def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]:
2047 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2048 # In C++ this would require a dynamic_cast
2049 return self._Publish(self._session, self._host, self._interceptor) # type: ignore
2050
2051 @property
2052 def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]:
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._UpdateTopic(self._session, self._host, self._interceptor) # type: ignore
2056
2057 @property
2058 def get_iam_policy(self):
2059 return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
2060
2061 class _GetIamPolicy(
2062 _BasePublisherRestTransport._BaseGetIamPolicy, PublisherRestStub
2063 ):
2064 def __hash__(self):
2065 return hash("PublisherRestTransport.GetIamPolicy")
2066
2067 @staticmethod
2068 def _get_response(
2069 host,
2070 metadata,
2071 query_params,
2072 session,
2073 timeout,
2074 transcoded_request,
2075 body=None,
2076 ):
2077 uri = transcoded_request["uri"]
2078 method = transcoded_request["method"]
2079 headers = dict(metadata)
2080 headers["Content-Type"] = "application/json"
2081 response = getattr(session, method)(
2082 "{host}{uri}".format(host=host, uri=uri),
2083 timeout=timeout,
2084 headers=headers,
2085 params=rest_helpers.flatten_query_params(query_params, strict=True),
2086 )
2087 return response
2088
2089 def __call__(
2090 self,
2091 request: iam_policy_pb2.GetIamPolicyRequest,
2092 *,
2093 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2094 timeout: Optional[float] = None,
2095 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2096 ) -> policy_pb2.Policy:
2097 r"""Call the get iam policy method over HTTP.
2098
2099 Args:
2100 request (iam_policy_pb2.GetIamPolicyRequest):
2101 The request object for GetIamPolicy method.
2102 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2103 should be retried.
2104 timeout (float): The timeout for this request.
2105 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2106 sent along with the request as metadata. Normally, each value must be of type `str`,
2107 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2108 be of type `bytes`.
2109
2110 Returns:
2111 policy_pb2.Policy: Response from GetIamPolicy method.
2112 """
2113
2114 http_options = (
2115 _BasePublisherRestTransport._BaseGetIamPolicy._get_http_options()
2116 )
2117
2118 request, metadata = self._interceptor.pre_get_iam_policy(request, metadata)
2119 transcoded_request = (
2120 _BasePublisherRestTransport._BaseGetIamPolicy._get_transcoded_request(
2121 http_options, request
2122 )
2123 )
2124
2125 # Jsonify the query params
2126 query_params = (
2127 _BasePublisherRestTransport._BaseGetIamPolicy._get_query_params_json(
2128 transcoded_request
2129 )
2130 )
2131
2132 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
2133 logging.DEBUG
2134 ): # pragma: NO COVER
2135 request_url = "{host}{uri}".format(
2136 host=self._host, uri=transcoded_request["uri"]
2137 )
2138 method = transcoded_request["method"]
2139 try:
2140 request_payload = json_format.MessageToJson(request)
2141 except:
2142 request_payload = None
2143 http_request = {
2144 "payload": request_payload,
2145 "requestMethod": method,
2146 "requestUrl": request_url,
2147 "headers": dict(metadata),
2148 }
2149 _LOGGER.debug(
2150 f"Sending request for google.pubsub_v1.PublisherClient.GetIamPolicy",
2151 extra={
2152 "serviceName": "google.pubsub.v1.Publisher",
2153 "rpcName": "GetIamPolicy",
2154 "httpRequest": http_request,
2155 "metadata": http_request["headers"],
2156 },
2157 )
2158
2159 # Send the request
2160 response = PublisherRestTransport._GetIamPolicy._get_response(
2161 self._host,
2162 metadata,
2163 query_params,
2164 self._session,
2165 timeout,
2166 transcoded_request,
2167 )
2168
2169 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
2170 # subclass.
2171 if response.status_code >= 400:
2172 raise core_exceptions.from_http_response(response)
2173
2174 content = response.content.decode("utf-8")
2175 resp = policy_pb2.Policy()
2176 resp = json_format.Parse(content, resp)
2177 resp = self._interceptor.post_get_iam_policy(resp)
2178 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
2179 logging.DEBUG
2180 ): # pragma: NO COVER
2181 try:
2182 response_payload = json_format.MessageToJson(resp)
2183 except:
2184 response_payload = None
2185 http_response = {
2186 "payload": response_payload,
2187 "headers": dict(response.headers),
2188 "status": response.status_code,
2189 }
2190 _LOGGER.debug(
2191 "Received response for google.pubsub_v1.PublisherAsyncClient.GetIamPolicy",
2192 extra={
2193 "serviceName": "google.pubsub.v1.Publisher",
2194 "rpcName": "GetIamPolicy",
2195 "httpResponse": http_response,
2196 "metadata": http_response["headers"],
2197 },
2198 )
2199 return resp
2200
2201 @property
2202 def set_iam_policy(self):
2203 return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
2204
2205 class _SetIamPolicy(
2206 _BasePublisherRestTransport._BaseSetIamPolicy, PublisherRestStub
2207 ):
2208 def __hash__(self):
2209 return hash("PublisherRestTransport.SetIamPolicy")
2210
2211 @staticmethod
2212 def _get_response(
2213 host,
2214 metadata,
2215 query_params,
2216 session,
2217 timeout,
2218 transcoded_request,
2219 body=None,
2220 ):
2221 uri = transcoded_request["uri"]
2222 method = transcoded_request["method"]
2223 headers = dict(metadata)
2224 headers["Content-Type"] = "application/json"
2225 response = getattr(session, method)(
2226 "{host}{uri}".format(host=host, uri=uri),
2227 timeout=timeout,
2228 headers=headers,
2229 params=rest_helpers.flatten_query_params(query_params, strict=True),
2230 data=body,
2231 )
2232 return response
2233
2234 def __call__(
2235 self,
2236 request: iam_policy_pb2.SetIamPolicyRequest,
2237 *,
2238 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2239 timeout: Optional[float] = None,
2240 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2241 ) -> policy_pb2.Policy:
2242 r"""Call the set iam policy method over HTTP.
2243
2244 Args:
2245 request (iam_policy_pb2.SetIamPolicyRequest):
2246 The request object for SetIamPolicy method.
2247 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2248 should be retried.
2249 timeout (float): The timeout for this request.
2250 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2251 sent along with the request as metadata. Normally, each value must be of type `str`,
2252 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2253 be of type `bytes`.
2254
2255 Returns:
2256 policy_pb2.Policy: Response from SetIamPolicy method.
2257 """
2258
2259 http_options = (
2260 _BasePublisherRestTransport._BaseSetIamPolicy._get_http_options()
2261 )
2262
2263 request, metadata = self._interceptor.pre_set_iam_policy(request, metadata)
2264 transcoded_request = (
2265 _BasePublisherRestTransport._BaseSetIamPolicy._get_transcoded_request(
2266 http_options, request
2267 )
2268 )
2269
2270 body = _BasePublisherRestTransport._BaseSetIamPolicy._get_request_body_json(
2271 transcoded_request
2272 )
2273
2274 # Jsonify the query params
2275 query_params = (
2276 _BasePublisherRestTransport._BaseSetIamPolicy._get_query_params_json(
2277 transcoded_request
2278 )
2279 )
2280
2281 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
2282 logging.DEBUG
2283 ): # pragma: NO COVER
2284 request_url = "{host}{uri}".format(
2285 host=self._host, uri=transcoded_request["uri"]
2286 )
2287 method = transcoded_request["method"]
2288 try:
2289 request_payload = json_format.MessageToJson(request)
2290 except:
2291 request_payload = None
2292 http_request = {
2293 "payload": request_payload,
2294 "requestMethod": method,
2295 "requestUrl": request_url,
2296 "headers": dict(metadata),
2297 }
2298 _LOGGER.debug(
2299 f"Sending request for google.pubsub_v1.PublisherClient.SetIamPolicy",
2300 extra={
2301 "serviceName": "google.pubsub.v1.Publisher",
2302 "rpcName": "SetIamPolicy",
2303 "httpRequest": http_request,
2304 "metadata": http_request["headers"],
2305 },
2306 )
2307
2308 # Send the request
2309 response = PublisherRestTransport._SetIamPolicy._get_response(
2310 self._host,
2311 metadata,
2312 query_params,
2313 self._session,
2314 timeout,
2315 transcoded_request,
2316 body,
2317 )
2318
2319 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
2320 # subclass.
2321 if response.status_code >= 400:
2322 raise core_exceptions.from_http_response(response)
2323
2324 content = response.content.decode("utf-8")
2325 resp = policy_pb2.Policy()
2326 resp = json_format.Parse(content, resp)
2327 resp = self._interceptor.post_set_iam_policy(resp)
2328 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
2329 logging.DEBUG
2330 ): # pragma: NO COVER
2331 try:
2332 response_payload = json_format.MessageToJson(resp)
2333 except:
2334 response_payload = None
2335 http_response = {
2336 "payload": response_payload,
2337 "headers": dict(response.headers),
2338 "status": response.status_code,
2339 }
2340 _LOGGER.debug(
2341 "Received response for google.pubsub_v1.PublisherAsyncClient.SetIamPolicy",
2342 extra={
2343 "serviceName": "google.pubsub.v1.Publisher",
2344 "rpcName": "SetIamPolicy",
2345 "httpResponse": http_response,
2346 "metadata": http_response["headers"],
2347 },
2348 )
2349 return resp
2350
2351 @property
2352 def test_iam_permissions(self):
2353 return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore
2354
2355 class _TestIamPermissions(
2356 _BasePublisherRestTransport._BaseTestIamPermissions, PublisherRestStub
2357 ):
2358 def __hash__(self):
2359 return hash("PublisherRestTransport.TestIamPermissions")
2360
2361 @staticmethod
2362 def _get_response(
2363 host,
2364 metadata,
2365 query_params,
2366 session,
2367 timeout,
2368 transcoded_request,
2369 body=None,
2370 ):
2371 uri = transcoded_request["uri"]
2372 method = transcoded_request["method"]
2373 headers = dict(metadata)
2374 headers["Content-Type"] = "application/json"
2375 response = getattr(session, method)(
2376 "{host}{uri}".format(host=host, uri=uri),
2377 timeout=timeout,
2378 headers=headers,
2379 params=rest_helpers.flatten_query_params(query_params, strict=True),
2380 data=body,
2381 )
2382 return response
2383
2384 def __call__(
2385 self,
2386 request: iam_policy_pb2.TestIamPermissionsRequest,
2387 *,
2388 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2389 timeout: Optional[float] = None,
2390 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2391 ) -> iam_policy_pb2.TestIamPermissionsResponse:
2392 r"""Call the test iam permissions method over HTTP.
2393
2394 Args:
2395 request (iam_policy_pb2.TestIamPermissionsRequest):
2396 The request object for TestIamPermissions method.
2397 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2398 should be retried.
2399 timeout (float): The timeout for this request.
2400 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2401 sent along with the request as metadata. Normally, each value must be of type `str`,
2402 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2403 be of type `bytes`.
2404
2405 Returns:
2406 iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method.
2407 """
2408
2409 http_options = (
2410 _BasePublisherRestTransport._BaseTestIamPermissions._get_http_options()
2411 )
2412
2413 request, metadata = self._interceptor.pre_test_iam_permissions(
2414 request, metadata
2415 )
2416 transcoded_request = _BasePublisherRestTransport._BaseTestIamPermissions._get_transcoded_request(
2417 http_options, request
2418 )
2419
2420 body = _BasePublisherRestTransport._BaseTestIamPermissions._get_request_body_json(
2421 transcoded_request
2422 )
2423
2424 # Jsonify the query params
2425 query_params = _BasePublisherRestTransport._BaseTestIamPermissions._get_query_params_json(
2426 transcoded_request
2427 )
2428
2429 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
2430 logging.DEBUG
2431 ): # pragma: NO COVER
2432 request_url = "{host}{uri}".format(
2433 host=self._host, uri=transcoded_request["uri"]
2434 )
2435 method = transcoded_request["method"]
2436 try:
2437 request_payload = json_format.MessageToJson(request)
2438 except:
2439 request_payload = None
2440 http_request = {
2441 "payload": request_payload,
2442 "requestMethod": method,
2443 "requestUrl": request_url,
2444 "headers": dict(metadata),
2445 }
2446 _LOGGER.debug(
2447 f"Sending request for google.pubsub_v1.PublisherClient.TestIamPermissions",
2448 extra={
2449 "serviceName": "google.pubsub.v1.Publisher",
2450 "rpcName": "TestIamPermissions",
2451 "httpRequest": http_request,
2452 "metadata": http_request["headers"],
2453 },
2454 )
2455
2456 # Send the request
2457 response = PublisherRestTransport._TestIamPermissions._get_response(
2458 self._host,
2459 metadata,
2460 query_params,
2461 self._session,
2462 timeout,
2463 transcoded_request,
2464 body,
2465 )
2466
2467 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
2468 # subclass.
2469 if response.status_code >= 400:
2470 raise core_exceptions.from_http_response(response)
2471
2472 content = response.content.decode("utf-8")
2473 resp = iam_policy_pb2.TestIamPermissionsResponse()
2474 resp = json_format.Parse(content, resp)
2475 resp = self._interceptor.post_test_iam_permissions(resp)
2476 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
2477 logging.DEBUG
2478 ): # pragma: NO COVER
2479 try:
2480 response_payload = json_format.MessageToJson(resp)
2481 except:
2482 response_payload = None
2483 http_response = {
2484 "payload": response_payload,
2485 "headers": dict(response.headers),
2486 "status": response.status_code,
2487 }
2488 _LOGGER.debug(
2489 "Received response for google.pubsub_v1.PublisherAsyncClient.TestIamPermissions",
2490 extra={
2491 "serviceName": "google.pubsub.v1.Publisher",
2492 "rpcName": "TestIamPermissions",
2493 "httpResponse": http_response,
2494 "metadata": http_response["headers"],
2495 },
2496 )
2497 return resp
2498
2499 @property
2500 def kind(self) -> str:
2501 return "rest"
2502
2503 def close(self):
2504 self._session.close()
2505
2506
2507__all__ = ("PublisherRestTransport",)