Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/google/pubsub_v1/services/publisher/async_client.py: 35%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

226 statements  

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 as std_logging 

17from collections import OrderedDict 

18import re 

19from typing import ( 

20 Dict, 

21 Callable, 

22 Mapping, 

23 MutableMapping, 

24 MutableSequence, 

25 Optional, 

26 Sequence, 

27 Tuple, 

28 Type, 

29 Union, 

30) 

31 

32from google.pubsub_v1 import gapic_version as package_version 

33 

34from google.api_core.client_options import ClientOptions 

35from google.api_core import exceptions as core_exceptions 

36from google.api_core import gapic_v1 

37from google.api_core import retry_async as retries 

38from google.auth import credentials as ga_credentials # type: ignore 

39from google.oauth2 import service_account # type: ignore 

40 

41 

42try: 

43 OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 

44except AttributeError: # pragma: NO COVER 

45 OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore 

46 

47from google.iam.v1 import iam_policy_pb2 # type: ignore 

48from google.iam.v1 import policy_pb2 # type: ignore 

49from google.protobuf import duration_pb2 # type: ignore 

50from google.protobuf import field_mask_pb2 # type: ignore 

51from google.pubsub_v1.services.publisher import pagers 

52from google.pubsub_v1.types import pubsub 

53from google.pubsub_v1.types import TimeoutType 

54from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO 

55from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport 

56from .client import PublisherClient 

57 

58try: 

59 from google.api_core import client_logging # type: ignore 

60 

61 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

62except ImportError: # pragma: NO COVER 

63 CLIENT_LOGGING_SUPPORTED = False 

64 

65_LOGGER = std_logging.getLogger(__name__) 

66 

67 

68class PublisherAsyncClient: 

69 """The service that an application uses to manipulate topics, 

70 and to send messages to a topic. 

71 """ 

72 

73 _client: PublisherClient 

74 

75 # Copy defaults from the synchronous client for use here. 

76 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. 

77 DEFAULT_ENDPOINT = PublisherClient.DEFAULT_ENDPOINT 

78 DEFAULT_MTLS_ENDPOINT = PublisherClient.DEFAULT_MTLS_ENDPOINT 

79 _DEFAULT_ENDPOINT_TEMPLATE = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE 

80 _DEFAULT_UNIVERSE = PublisherClient._DEFAULT_UNIVERSE 

81 

82 schema_path = staticmethod(PublisherClient.schema_path) 

83 parse_schema_path = staticmethod(PublisherClient.parse_schema_path) 

84 subscription_path = staticmethod(PublisherClient.subscription_path) 

85 parse_subscription_path = staticmethod(PublisherClient.parse_subscription_path) 

86 topic_path = staticmethod(PublisherClient.topic_path) 

87 parse_topic_path = staticmethod(PublisherClient.parse_topic_path) 

88 common_billing_account_path = staticmethod( 

89 PublisherClient.common_billing_account_path 

90 ) 

91 parse_common_billing_account_path = staticmethod( 

92 PublisherClient.parse_common_billing_account_path 

93 ) 

94 common_folder_path = staticmethod(PublisherClient.common_folder_path) 

95 parse_common_folder_path = staticmethod(PublisherClient.parse_common_folder_path) 

96 common_organization_path = staticmethod(PublisherClient.common_organization_path) 

97 parse_common_organization_path = staticmethod( 

98 PublisherClient.parse_common_organization_path 

99 ) 

100 common_project_path = staticmethod(PublisherClient.common_project_path) 

101 parse_common_project_path = staticmethod(PublisherClient.parse_common_project_path) 

102 common_location_path = staticmethod(PublisherClient.common_location_path) 

103 parse_common_location_path = staticmethod( 

104 PublisherClient.parse_common_location_path 

105 ) 

106 

107 @classmethod 

108 def from_service_account_info(cls, info: dict, *args, **kwargs): 

109 """Creates an instance of this client using the provided credentials 

110 info. 

111 

112 Args: 

113 info (dict): The service account private key info. 

114 args: Additional arguments to pass to the constructor. 

115 kwargs: Additional arguments to pass to the constructor. 

116 

117 Returns: 

118 PublisherAsyncClient: The constructed client. 

119 """ 

120 return PublisherClient.from_service_account_info.__func__(PublisherAsyncClient, info, *args, **kwargs) # type: ignore 

121 

122 @classmethod 

123 def from_service_account_file(cls, filename: str, *args, **kwargs): 

124 """Creates an instance of this client using the provided credentials 

125 file. 

126 

127 Args: 

128 filename (str): The path to the service account private key json 

129 file. 

130 args: Additional arguments to pass to the constructor. 

131 kwargs: Additional arguments to pass to the constructor. 

132 

133 Returns: 

134 PublisherAsyncClient: The constructed client. 

135 """ 

136 return PublisherClient.from_service_account_file.__func__(PublisherAsyncClient, filename, *args, **kwargs) # type: ignore 

137 

138 from_service_account_json = from_service_account_file 

139 

140 @classmethod 

141 def get_mtls_endpoint_and_cert_source( 

142 cls, client_options: Optional[ClientOptions] = None 

143 ): 

144 """Return the API endpoint and client cert source for mutual TLS. 

145 

146 The client cert source is determined in the following order: 

147 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the 

148 client cert source is None. 

149 (2) if `client_options.client_cert_source` is provided, use the provided one; if the 

150 default client cert source exists, use the default one; otherwise the client cert 

151 source is None. 

152 

153 The API endpoint is determined in the following order: 

154 (1) if `client_options.api_endpoint` if provided, use the provided one. 

155 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the 

156 default mTLS endpoint; if the environment variable is "never", use the default API 

157 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise 

158 use the default API endpoint. 

159 

160 More details can be found at https://google.aip.dev/auth/4114. 

161 

162 Args: 

163 client_options (google.api_core.client_options.ClientOptions): Custom options for the 

164 client. Only the `api_endpoint` and `client_cert_source` properties may be used 

165 in this method. 

166 

167 Returns: 

168 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the 

169 client cert source to use. 

170 

171 Raises: 

172 google.auth.exceptions.MutualTLSChannelError: If any errors happen. 

173 """ 

174 return PublisherClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore 

175 

176 @property 

177 def transport(self) -> PublisherTransport: 

178 """Returns the transport used by the client instance. 

179 

180 Returns: 

181 PublisherTransport: The transport used by the client instance. 

182 """ 

183 return self._client.transport 

184 

185 @property 

186 def api_endpoint(self): 

187 """Return the API endpoint used by the client instance. 

188 

189 Returns: 

190 str: The API endpoint used by the client instance. 

191 """ 

192 return self._client._api_endpoint 

193 

194 @property 

195 def universe_domain(self) -> str: 

196 """Return the universe domain used by the client instance. 

197 

198 Returns: 

199 str: The universe domain used 

200 by the client instance. 

201 """ 

202 return self._client._universe_domain 

203 

204 get_transport_class = PublisherClient.get_transport_class 

205 

206 def __init__( 

207 self, 

208 *, 

209 credentials: Optional[ga_credentials.Credentials] = None, 

210 transport: Optional[ 

211 Union[str, PublisherTransport, Callable[..., PublisherTransport]] 

212 ] = "grpc_asyncio", 

213 client_options: Optional[ClientOptions] = None, 

214 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

215 ) -> None: 

216 """Instantiates the publisher async client. 

217 

218 Args: 

219 credentials (Optional[google.auth.credentials.Credentials]): The 

220 authorization credentials to attach to requests. These 

221 credentials identify the application to the service; if none 

222 are specified, the client will attempt to ascertain the 

223 credentials from the environment. 

224 transport (Optional[Union[str,PublisherTransport,Callable[..., PublisherTransport]]]): 

225 The transport to use, or a Callable that constructs and returns a new transport to use. 

226 If a Callable is given, it will be called with the same set of initialization 

227 arguments as used in the PublisherTransport constructor. 

228 If set to None, a transport is chosen automatically. 

229 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 

230 Custom options for the client. 

231 

232 1. The ``api_endpoint`` property can be used to override the 

233 default endpoint provided by the client when ``transport`` is 

234 not explicitly provided. Only if this property is not set and 

235 ``transport`` was not explicitly provided, the endpoint is 

236 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

237 variable, which have one of the following values: 

238 "always" (always use the default mTLS endpoint), "never" (always 

239 use the default regular endpoint) and "auto" (auto-switch to the 

240 default mTLS endpoint if client certificate is present; this is 

241 the default value). 

242 

243 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

244 is "true", then the ``client_cert_source`` property can be used 

245 to provide a client certificate for mTLS transport. If 

246 not provided, the default SSL client certificate will be used if 

247 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

248 set, no client certificate will be used. 

249 

250 3. The ``universe_domain`` property can be used to override the 

251 default "googleapis.com" universe. Note that ``api_endpoint`` 

252 property still takes precedence; and ``universe_domain`` is 

253 currently not supported for mTLS. 

254 

255 client_info (google.api_core.gapic_v1.client_info.ClientInfo): 

256 The client info used to send a user-agent string along with 

257 API requests. If ``None``, then default info will be used. 

258 Generally, you only need to set this if you're developing 

259 your own client library. 

260 

261 Raises: 

262 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport 

263 creation failed for any reason. 

264 """ 

265 self._client = PublisherClient( 

266 credentials=credentials, 

267 transport=transport, 

268 client_options=client_options, 

269 client_info=client_info, 

270 ) 

271 

272 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

273 std_logging.DEBUG 

274 ): # pragma: NO COVER 

275 _LOGGER.debug( 

276 "Created client `google.pubsub_v1.PublisherAsyncClient`.", 

277 extra={ 

278 "serviceName": "google.pubsub.v1.Publisher", 

279 "universeDomain": getattr( 

280 self._client._transport._credentials, "universe_domain", "" 

281 ), 

282 "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", 

283 "credentialsInfo": getattr( 

284 self.transport._credentials, "get_cred_info", lambda: None 

285 )(), 

286 } 

287 if hasattr(self._client._transport, "_credentials") 

288 else { 

289 "serviceName": "google.pubsub.v1.Publisher", 

290 "credentialsType": None, 

291 }, 

292 ) 

293 

294 async def create_topic( 

295 self, 

296 request: Optional[Union[pubsub.Topic, dict]] = None, 

297 *, 

298 name: Optional[str] = None, 

299 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

300 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

301 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

302 ) -> pubsub.Topic: 

303 r"""Creates the given topic with the given name. See the [resource 

304 name rules] 

305 (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). 

306 

307 .. code-block:: python 

308 

309 # This snippet has been automatically generated and should be regarded as a 

310 # code template only. 

311 # It will require modifications to work: 

312 # - It may require correct/in-range values for request initialization. 

313 # - It may require specifying regional endpoints when creating the service 

314 # client as shown in: 

315 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

316 from google import pubsub_v1 

317 

318 async def sample_create_topic(): 

319 # Create a client 

320 client = pubsub_v1.PublisherAsyncClient() 

321 

322 # Initialize request argument(s) 

323 request = pubsub_v1.Topic( 

324 name="name_value", 

325 ) 

326 

327 # Make the request 

328 response = await client.create_topic(request=request) 

329 

330 # Handle the response 

331 print(response) 

332 

333 Args: 

334 request (Optional[Union[google.pubsub_v1.types.Topic, dict]]): 

335 The request object. A topic resource. 

336 name (:class:`str`): 

337 Required. The name of the topic. It must have the format 

338 ``"projects/{project}/topics/{topic}"``. ``{topic}`` 

339 must start with a letter, and contain only letters 

340 (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), 

341 underscores (``_``), periods (``.``), tildes (``~``), 

342 plus (``+``) or percent signs (``%``). It must be 

343 between 3 and 255 characters in length, and it must not 

344 start with ``"goog"``. 

345 

346 This corresponds to the ``name`` field 

347 on the ``request`` instance; if ``request`` is provided, this 

348 should not be set. 

349 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

350 should be retried. 

351 timeout (TimeoutType): 

352 The timeout for this request. 

353 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

354 sent along with the request as metadata. Normally, each value must be of type `str`, 

355 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

356 be of type `bytes`. 

357 

358 Returns: 

359 google.pubsub_v1.types.Topic: 

360 A topic resource. 

361 """ 

362 # Create or coerce a protobuf request object. 

363 # - Quick check: If we got a request object, we should *not* have 

364 # gotten any keyword arguments that map to the request. 

365 flattened_params = [name] 

366 has_flattened_params = ( 

367 len([param for param in flattened_params if param is not None]) > 0 

368 ) 

369 if request is not None and has_flattened_params: 

370 raise ValueError( 

371 "If the `request` argument is set, then none of " 

372 "the individual field arguments should be set." 

373 ) 

374 

375 # - Use the request object if provided (there's no risk of modifying the input as 

376 # there are no flattened fields), or create one. 

377 if not isinstance(request, pubsub.Topic): 

378 request = pubsub.Topic(request) 

379 

380 # If we have keyword arguments corresponding to fields on the 

381 # request, apply these. 

382 if name is not None: 

383 request.name = name 

384 

385 # Wrap the RPC method; this adds retry and timeout information, 

386 # and friendly error handling. 

387 rpc = self._client._transport._wrapped_methods[ 

388 self._client._transport.create_topic 

389 ] 

390 

391 # Certain fields should be provided within the metadata header; 

392 # add these here. 

393 metadata = tuple(metadata) + ( 

394 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

395 ) 

396 

397 # Validate the universe domain. 

398 self._client._validate_universe_domain() 

399 

400 # Send the request. 

401 response = await rpc( 

402 request, 

403 retry=retry, 

404 timeout=timeout, 

405 metadata=metadata, 

406 ) 

407 

408 # Done; return the response. 

409 return response 

410 

411 async def update_topic( 

412 self, 

413 request: Optional[Union[pubsub.UpdateTopicRequest, dict]] = None, 

414 *, 

415 topic: Optional[pubsub.Topic] = None, 

416 update_mask: Optional[field_mask_pb2.FieldMask] = None, 

417 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

418 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

419 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

420 ) -> pubsub.Topic: 

421 r"""Updates an existing topic by updating the fields 

422 specified in the update mask. Note that certain 

423 properties of a topic are not modifiable. 

424 

425 .. code-block:: python 

426 

427 # This snippet has been automatically generated and should be regarded as a 

428 # code template only. 

429 # It will require modifications to work: 

430 # - It may require correct/in-range values for request initialization. 

431 # - It may require specifying regional endpoints when creating the service 

432 # client as shown in: 

433 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

434 from google import pubsub_v1 

435 

436 async def sample_update_topic(): 

437 # Create a client 

438 client = pubsub_v1.PublisherAsyncClient() 

439 

440 # Initialize request argument(s) 

441 topic = pubsub_v1.Topic() 

442 topic.name = "name_value" 

443 

444 request = pubsub_v1.UpdateTopicRequest( 

445 topic=topic, 

446 ) 

447 

448 # Make the request 

449 response = await client.update_topic(request=request) 

450 

451 # Handle the response 

452 print(response) 

453 

454 Args: 

455 request (Optional[Union[google.pubsub_v1.types.UpdateTopicRequest, dict]]): 

456 The request object. Request for the UpdateTopic method. 

457 topic (:class:`google.pubsub_v1.types.Topic`): 

458 Required. The updated topic object. 

459 This corresponds to the ``topic`` field 

460 on the ``request`` instance; if ``request`` is provided, this 

461 should not be set. 

462 update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): 

463 Required. Indicates which fields in the provided topic 

464 to update. Must be specified and non-empty. Note that if 

465 ``update_mask`` contains "message_storage_policy" but 

466 the ``message_storage_policy`` is not set in the 

467 ``topic`` provided above, then the updated value is 

468 determined by the policy configured at the project or 

469 organization level. 

470 

471 This corresponds to the ``update_mask`` field 

472 on the ``request`` instance; if ``request`` is provided, this 

473 should not be set. 

474 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

475 should be retried. 

476 timeout (TimeoutType): 

477 The timeout for this request. 

478 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

479 sent along with the request as metadata. Normally, each value must be of type `str`, 

480 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

481 be of type `bytes`. 

482 

483 Returns: 

484 google.pubsub_v1.types.Topic: 

485 A topic resource. 

486 """ 

487 # Create or coerce a protobuf request object. 

488 # - Quick check: If we got a request object, we should *not* have 

489 # gotten any keyword arguments that map to the request. 

490 flattened_params = [topic, update_mask] 

491 has_flattened_params = ( 

492 len([param for param in flattened_params if param is not None]) > 0 

493 ) 

494 if request is not None and has_flattened_params: 

495 raise ValueError( 

496 "If the `request` argument is set, then none of " 

497 "the individual field arguments should be set." 

498 ) 

499 

500 # - Use the request object if provided (there's no risk of modifying the input as 

501 # there are no flattened fields), or create one. 

502 if not isinstance(request, pubsub.UpdateTopicRequest): 

503 request = pubsub.UpdateTopicRequest(request) 

504 

505 # If we have keyword arguments corresponding to fields on the 

506 # request, apply these. 

507 if topic is not None: 

508 request.topic = topic 

509 if update_mask is not None: 

510 request.update_mask = update_mask 

511 

512 # Wrap the RPC method; this adds retry and timeout information, 

513 # and friendly error handling. 

514 rpc = self._client._transport._wrapped_methods[ 

515 self._client._transport.update_topic 

516 ] 

517 

518 # Certain fields should be provided within the metadata header; 

519 # add these here. 

520 metadata = tuple(metadata) + ( 

521 gapic_v1.routing_header.to_grpc_metadata( 

522 (("topic.name", request.topic.name),) 

523 ), 

524 ) 

525 

526 # Validate the universe domain. 

527 self._client._validate_universe_domain() 

528 

529 # Send the request. 

530 response = await rpc( 

531 request, 

532 retry=retry, 

533 timeout=timeout, 

534 metadata=metadata, 

535 ) 

536 

537 # Done; return the response. 

538 return response 

539 

540 async def publish( 

541 self, 

542 request: Optional[Union[pubsub.PublishRequest, dict]] = None, 

543 *, 

544 topic: Optional[str] = None, 

545 messages: Optional[MutableSequence[pubsub.PubsubMessage]] = None, 

546 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

547 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

548 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

549 ) -> pubsub.PublishResponse: 

550 r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if 

551 the topic does not exist. 

552 

553 .. code-block:: python 

554 

555 # This snippet has been automatically generated and should be regarded as a 

556 # code template only. 

557 # It will require modifications to work: 

558 # - It may require correct/in-range values for request initialization. 

559 # - It may require specifying regional endpoints when creating the service 

560 # client as shown in: 

561 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

562 from google import pubsub_v1 

563 

564 async def sample_publish(): 

565 # Create a client 

566 client = pubsub_v1.PublisherAsyncClient() 

567 

568 # Initialize request argument(s) 

569 request = pubsub_v1.PublishRequest( 

570 topic="topic_value", 

571 ) 

572 

573 # Make the request 

574 response = await client.publish(request=request) 

575 

576 # Handle the response 

577 print(response) 

578 

579 Args: 

580 request (Optional[Union[google.pubsub_v1.types.PublishRequest, dict]]): 

581 The request object. Request for the Publish method. 

582 topic (:class:`str`): 

583 Required. The messages in the request will be published 

584 on this topic. Format is 

585 ``projects/{project}/topics/{topic}``. 

586 

587 This corresponds to the ``topic`` field 

588 on the ``request`` instance; if ``request`` is provided, this 

589 should not be set. 

590 messages (:class:`MutableSequence[google.pubsub_v1.types.PubsubMessage]`): 

591 Required. The messages to publish. 

592 This corresponds to the ``messages`` field 

593 on the ``request`` instance; if ``request`` is provided, this 

594 should not be set. 

595 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

596 should be retried. 

597 timeout (TimeoutType): 

598 The timeout for this request. 

599 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

600 sent along with the request as metadata. Normally, each value must be of type `str`, 

601 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

602 be of type `bytes`. 

603 

604 Returns: 

605 google.pubsub_v1.types.PublishResponse: 

606 Response for the Publish method. 

607 """ 

608 # Create or coerce a protobuf request object. 

609 # - Quick check: If we got a request object, we should *not* have 

610 # gotten any keyword arguments that map to the request. 

611 flattened_params = [topic, messages] 

612 has_flattened_params = ( 

613 len([param for param in flattened_params if param is not None]) > 0 

614 ) 

615 if request is not None and has_flattened_params: 

616 raise ValueError( 

617 "If the `request` argument is set, then none of " 

618 "the individual field arguments should be set." 

619 ) 

620 

621 # - Use the request object if provided (there's no risk of modifying the input as 

622 # there are no flattened fields), or create one. 

623 if not isinstance(request, pubsub.PublishRequest): 

624 request = pubsub.PublishRequest(request) 

625 

626 # If we have keyword arguments corresponding to fields on the 

627 # request, apply these. 

628 if topic is not None: 

629 request.topic = topic 

630 if messages: 

631 request.messages.extend(messages) 

632 

633 # Wrap the RPC method; this adds retry and timeout information, 

634 # and friendly error handling. 

635 rpc = self._client._transport._wrapped_methods[self._client._transport.publish] 

636 

637 # Certain fields should be provided within the metadata header; 

638 # add these here. 

639 metadata = tuple(metadata) + ( 

640 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

641 ) 

642 

643 # Validate the universe domain. 

644 self._client._validate_universe_domain() 

645 

646 # Send the request. 

647 response = await rpc( 

648 request, 

649 retry=retry, 

650 timeout=timeout, 

651 metadata=metadata, 

652 ) 

653 

654 # Done; return the response. 

655 return response 

656 

657 async def get_topic( 

658 self, 

659 request: Optional[Union[pubsub.GetTopicRequest, dict]] = None, 

660 *, 

661 topic: Optional[str] = None, 

662 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

663 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

664 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

665 ) -> pubsub.Topic: 

666 r"""Gets the configuration of a topic. 

667 

668 .. code-block:: python 

669 

670 # This snippet has been automatically generated and should be regarded as a 

671 # code template only. 

672 # It will require modifications to work: 

673 # - It may require correct/in-range values for request initialization. 

674 # - It may require specifying regional endpoints when creating the service 

675 # client as shown in: 

676 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

677 from google import pubsub_v1 

678 

679 async def sample_get_topic(): 

680 # Create a client 

681 client = pubsub_v1.PublisherAsyncClient() 

682 

683 # Initialize request argument(s) 

684 request = pubsub_v1.GetTopicRequest( 

685 topic="topic_value", 

686 ) 

687 

688 # Make the request 

689 response = await client.get_topic(request=request) 

690 

691 # Handle the response 

692 print(response) 

693 

694 Args: 

695 request (Optional[Union[google.pubsub_v1.types.GetTopicRequest, dict]]): 

696 The request object. Request for the GetTopic method. 

697 topic (:class:`str`): 

698 Required. The name of the topic to get. Format is 

699 ``projects/{project}/topics/{topic}``. 

700 

701 This corresponds to the ``topic`` field 

702 on the ``request`` instance; if ``request`` is provided, this 

703 should not be set. 

704 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

705 should be retried. 

706 timeout (TimeoutType): 

707 The timeout for this request. 

708 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

709 sent along with the request as metadata. Normally, each value must be of type `str`, 

710 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

711 be of type `bytes`. 

712 

713 Returns: 

714 google.pubsub_v1.types.Topic: 

715 A topic resource. 

716 """ 

717 # Create or coerce a protobuf request object. 

718 # - Quick check: If we got a request object, we should *not* have 

719 # gotten any keyword arguments that map to the request. 

720 flattened_params = [topic] 

721 has_flattened_params = ( 

722 len([param for param in flattened_params if param is not None]) > 0 

723 ) 

724 if request is not None and has_flattened_params: 

725 raise ValueError( 

726 "If the `request` argument is set, then none of " 

727 "the individual field arguments should be set." 

728 ) 

729 

730 # - Use the request object if provided (there's no risk of modifying the input as 

731 # there are no flattened fields), or create one. 

732 if not isinstance(request, pubsub.GetTopicRequest): 

733 request = pubsub.GetTopicRequest(request) 

734 

735 # If we have keyword arguments corresponding to fields on the 

736 # request, apply these. 

737 if topic is not None: 

738 request.topic = topic 

739 

740 # Wrap the RPC method; this adds retry and timeout information, 

741 # and friendly error handling. 

742 rpc = self._client._transport._wrapped_methods[ 

743 self._client._transport.get_topic 

744 ] 

745 

746 # Certain fields should be provided within the metadata header; 

747 # add these here. 

748 metadata = tuple(metadata) + ( 

749 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

750 ) 

751 

752 # Validate the universe domain. 

753 self._client._validate_universe_domain() 

754 

755 # Send the request. 

756 response = await rpc( 

757 request, 

758 retry=retry, 

759 timeout=timeout, 

760 metadata=metadata, 

761 ) 

762 

763 # Done; return the response. 

764 return response 

765 

766 async def list_topics( 

767 self, 

768 request: Optional[Union[pubsub.ListTopicsRequest, dict]] = None, 

769 *, 

770 project: Optional[str] = None, 

771 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

772 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

773 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

774 ) -> pagers.ListTopicsAsyncPager: 

775 r"""Lists matching topics. 

776 

777 .. code-block:: python 

778 

779 # This snippet has been automatically generated and should be regarded as a 

780 # code template only. 

781 # It will require modifications to work: 

782 # - It may require correct/in-range values for request initialization. 

783 # - It may require specifying regional endpoints when creating the service 

784 # client as shown in: 

785 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

786 from google import pubsub_v1 

787 

788 async def sample_list_topics(): 

789 # Create a client 

790 client = pubsub_v1.PublisherAsyncClient() 

791 

792 # Initialize request argument(s) 

793 request = pubsub_v1.ListTopicsRequest( 

794 project="project_value", 

795 ) 

796 

797 # Make the request 

798 page_result = client.list_topics(request=request) 

799 

800 # Handle the response 

801 async for response in page_result: 

802 print(response) 

803 

804 Args: 

805 request (Optional[Union[google.pubsub_v1.types.ListTopicsRequest, dict]]): 

806 The request object. Request for the ``ListTopics`` method. 

807 project (:class:`str`): 

808 Required. The name of the project in which to list 

809 topics. Format is ``projects/{project-id}``. 

810 

811 This corresponds to the ``project`` field 

812 on the ``request`` instance; if ``request`` is provided, this 

813 should not be set. 

814 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

815 should be retried. 

816 timeout (TimeoutType): 

817 The timeout for this request. 

818 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

819 sent along with the request as metadata. Normally, each value must be of type `str`, 

820 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

821 be of type `bytes`. 

822 

823 Returns: 

824 google.pubsub_v1.services.publisher.pagers.ListTopicsAsyncPager: 

825 Response for the ListTopics method. 

826 

827 Iterating over this object will yield results and 

828 resolve additional pages automatically. 

829 

830 """ 

831 # Create or coerce a protobuf request object. 

832 # - Quick check: If we got a request object, we should *not* have 

833 # gotten any keyword arguments that map to the request. 

834 flattened_params = [project] 

835 has_flattened_params = ( 

836 len([param for param in flattened_params if param is not None]) > 0 

837 ) 

838 if request is not None and has_flattened_params: 

839 raise ValueError( 

840 "If the `request` argument is set, then none of " 

841 "the individual field arguments should be set." 

842 ) 

843 

844 # - Use the request object if provided (there's no risk of modifying the input as 

845 # there are no flattened fields), or create one. 

846 if not isinstance(request, pubsub.ListTopicsRequest): 

847 request = pubsub.ListTopicsRequest(request) 

848 

849 # If we have keyword arguments corresponding to fields on the 

850 # request, apply these. 

851 if project is not None: 

852 request.project = project 

853 

854 # Wrap the RPC method; this adds retry and timeout information, 

855 # and friendly error handling. 

856 rpc = self._client._transport._wrapped_methods[ 

857 self._client._transport.list_topics 

858 ] 

859 

860 # Certain fields should be provided within the metadata header; 

861 # add these here. 

862 metadata = tuple(metadata) + ( 

863 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), 

864 ) 

865 

866 # Validate the universe domain. 

867 self._client._validate_universe_domain() 

868 

869 # Send the request. 

870 response = await rpc( 

871 request, 

872 retry=retry, 

873 timeout=timeout, 

874 metadata=metadata, 

875 ) 

876 

877 # This method is paged; wrap the response in a pager, which provides 

878 # an `__aiter__` convenience method. 

879 response = pagers.ListTopicsAsyncPager( 

880 method=rpc, 

881 request=request, 

882 response=response, 

883 retry=retry, 

884 timeout=timeout, 

885 metadata=metadata, 

886 ) 

887 

888 # Done; return the response. 

889 return response 

890 

891 async def list_topic_subscriptions( 

892 self, 

893 request: Optional[Union[pubsub.ListTopicSubscriptionsRequest, dict]] = None, 

894 *, 

895 topic: Optional[str] = None, 

896 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

897 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

898 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

899 ) -> pagers.ListTopicSubscriptionsAsyncPager: 

900 r"""Lists the names of the attached subscriptions on this 

901 topic. 

902 

903 .. code-block:: python 

904 

905 # This snippet has been automatically generated and should be regarded as a 

906 # code template only. 

907 # It will require modifications to work: 

908 # - It may require correct/in-range values for request initialization. 

909 # - It may require specifying regional endpoints when creating the service 

910 # client as shown in: 

911 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

912 from google import pubsub_v1 

913 

914 async def sample_list_topic_subscriptions(): 

915 # Create a client 

916 client = pubsub_v1.PublisherAsyncClient() 

917 

918 # Initialize request argument(s) 

919 request = pubsub_v1.ListTopicSubscriptionsRequest( 

920 topic="topic_value", 

921 ) 

922 

923 # Make the request 

924 page_result = client.list_topic_subscriptions(request=request) 

925 

926 # Handle the response 

927 async for response in page_result: 

928 print(response) 

929 

930 Args: 

931 request (Optional[Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]]): 

932 The request object. Request for the ``ListTopicSubscriptions`` method. 

933 topic (:class:`str`): 

934 Required. The name of the topic that subscriptions are 

935 attached to. Format is 

936 ``projects/{project}/topics/{topic}``. 

937 

938 This corresponds to the ``topic`` field 

939 on the ``request`` instance; if ``request`` is provided, this 

940 should not be set. 

941 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

942 should be retried. 

943 timeout (TimeoutType): 

944 The timeout for this request. 

945 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

946 sent along with the request as metadata. Normally, each value must be of type `str`, 

947 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

948 be of type `bytes`. 

949 

950 Returns: 

951 google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsAsyncPager: 

952 Response for the ListTopicSubscriptions method. 

953 

954 Iterating over this object will yield results and 

955 resolve additional pages automatically. 

956 

957 """ 

958 # Create or coerce a protobuf request object. 

959 # - Quick check: If we got a request object, we should *not* have 

960 # gotten any keyword arguments that map to the request. 

961 flattened_params = [topic] 

962 has_flattened_params = ( 

963 len([param for param in flattened_params if param is not None]) > 0 

964 ) 

965 if request is not None and has_flattened_params: 

966 raise ValueError( 

967 "If the `request` argument is set, then none of " 

968 "the individual field arguments should be set." 

969 ) 

970 

971 # - Use the request object if provided (there's no risk of modifying the input as 

972 # there are no flattened fields), or create one. 

973 if not isinstance(request, pubsub.ListTopicSubscriptionsRequest): 

974 request = pubsub.ListTopicSubscriptionsRequest(request) 

975 

976 # If we have keyword arguments corresponding to fields on the 

977 # request, apply these. 

978 if topic is not None: 

979 request.topic = topic 

980 

981 # Wrap the RPC method; this adds retry and timeout information, 

982 # and friendly error handling. 

983 rpc = self._client._transport._wrapped_methods[ 

984 self._client._transport.list_topic_subscriptions 

985 ] 

986 

987 # Certain fields should be provided within the metadata header; 

988 # add these here. 

989 metadata = tuple(metadata) + ( 

990 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

991 ) 

992 

993 # Validate the universe domain. 

994 self._client._validate_universe_domain() 

995 

996 # Send the request. 

997 response = await rpc( 

998 request, 

999 retry=retry, 

1000 timeout=timeout, 

1001 metadata=metadata, 

1002 ) 

1003 

1004 # This method is paged; wrap the response in a pager, which provides 

1005 # an `__aiter__` convenience method. 

1006 response = pagers.ListTopicSubscriptionsAsyncPager( 

1007 method=rpc, 

1008 request=request, 

1009 response=response, 

1010 retry=retry, 

1011 timeout=timeout, 

1012 metadata=metadata, 

1013 ) 

1014 

1015 # Done; return the response. 

1016 return response 

1017 

1018 async def list_topic_snapshots( 

1019 self, 

1020 request: Optional[Union[pubsub.ListTopicSnapshotsRequest, dict]] = None, 

1021 *, 

1022 topic: Optional[str] = None, 

1023 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1024 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1025 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1026 ) -> pagers.ListTopicSnapshotsAsyncPager: 

1027 r"""Lists the names of the snapshots on this topic. Snapshots are 

1028 used in 

1029 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__ 

1030 operations, which allow you to manage message acknowledgments in 

1031 bulk. That is, you can set the acknowledgment state of messages 

1032 in an existing subscription to the state captured by a snapshot. 

1033 

1034 .. code-block:: python 

1035 

1036 # This snippet has been automatically generated and should be regarded as a 

1037 # code template only. 

1038 # It will require modifications to work: 

1039 # - It may require correct/in-range values for request initialization. 

1040 # - It may require specifying regional endpoints when creating the service 

1041 # client as shown in: 

1042 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1043 from google import pubsub_v1 

1044 

1045 async def sample_list_topic_snapshots(): 

1046 # Create a client 

1047 client = pubsub_v1.PublisherAsyncClient() 

1048 

1049 # Initialize request argument(s) 

1050 request = pubsub_v1.ListTopicSnapshotsRequest( 

1051 topic="topic_value", 

1052 ) 

1053 

1054 # Make the request 

1055 page_result = client.list_topic_snapshots(request=request) 

1056 

1057 # Handle the response 

1058 async for response in page_result: 

1059 print(response) 

1060 

1061 Args: 

1062 request (Optional[Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]]): 

1063 The request object. Request for the ``ListTopicSnapshots`` method. 

1064 topic (:class:`str`): 

1065 Required. The name of the topic that snapshots are 

1066 attached to. Format is 

1067 ``projects/{project}/topics/{topic}``. 

1068 

1069 This corresponds to the ``topic`` field 

1070 on the ``request`` instance; if ``request`` is provided, this 

1071 should not be set. 

1072 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

1073 should be retried. 

1074 timeout (TimeoutType): 

1075 The timeout for this request. 

1076 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1077 sent along with the request as metadata. Normally, each value must be of type `str`, 

1078 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1079 be of type `bytes`. 

1080 

1081 Returns: 

1082 google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsAsyncPager: 

1083 Response for the ListTopicSnapshots method. 

1084 

1085 Iterating over this object will yield results and 

1086 resolve additional pages automatically. 

1087 

1088 """ 

1089 # Create or coerce a protobuf request object. 

1090 # - Quick check: If we got a request object, we should *not* have 

1091 # gotten any keyword arguments that map to the request. 

1092 flattened_params = [topic] 

1093 has_flattened_params = ( 

1094 len([param for param in flattened_params if param is not None]) > 0 

1095 ) 

1096 if request is not None and has_flattened_params: 

1097 raise ValueError( 

1098 "If the `request` argument is set, then none of " 

1099 "the individual field arguments should be set." 

1100 ) 

1101 

1102 # - Use the request object if provided (there's no risk of modifying the input as 

1103 # there are no flattened fields), or create one. 

1104 if not isinstance(request, pubsub.ListTopicSnapshotsRequest): 

1105 request = pubsub.ListTopicSnapshotsRequest(request) 

1106 

1107 # If we have keyword arguments corresponding to fields on the 

1108 # request, apply these. 

1109 if topic is not None: 

1110 request.topic = topic 

1111 

1112 # Wrap the RPC method; this adds retry and timeout information, 

1113 # and friendly error handling. 

1114 rpc = self._client._transport._wrapped_methods[ 

1115 self._client._transport.list_topic_snapshots 

1116 ] 

1117 

1118 # Certain fields should be provided within the metadata header; 

1119 # add these here. 

1120 metadata = tuple(metadata) + ( 

1121 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

1122 ) 

1123 

1124 # Validate the universe domain. 

1125 self._client._validate_universe_domain() 

1126 

1127 # Send the request. 

1128 response = await rpc( 

1129 request, 

1130 retry=retry, 

1131 timeout=timeout, 

1132 metadata=metadata, 

1133 ) 

1134 

1135 # This method is paged; wrap the response in a pager, which provides 

1136 # an `__aiter__` convenience method. 

1137 response = pagers.ListTopicSnapshotsAsyncPager( 

1138 method=rpc, 

1139 request=request, 

1140 response=response, 

1141 retry=retry, 

1142 timeout=timeout, 

1143 metadata=metadata, 

1144 ) 

1145 

1146 # Done; return the response. 

1147 return response 

1148 

1149 async def delete_topic( 

1150 self, 

1151 request: Optional[Union[pubsub.DeleteTopicRequest, dict]] = None, 

1152 *, 

1153 topic: Optional[str] = None, 

1154 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1155 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1156 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1157 ) -> None: 

1158 r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if 

1159 the topic does not exist. After a topic is deleted, a new topic 

1160 may be created with the same name; this is an entirely new topic 

1161 with none of the old configuration or subscriptions. Existing 

1162 subscriptions to this topic are not deleted, but their ``topic`` 

1163 field is set to ``_deleted-topic_``. 

1164 

1165 .. code-block:: python 

1166 

1167 # This snippet has been automatically generated and should be regarded as a 

1168 # code template only. 

1169 # It will require modifications to work: 

1170 # - It may require correct/in-range values for request initialization. 

1171 # - It may require specifying regional endpoints when creating the service 

1172 # client as shown in: 

1173 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1174 from google import pubsub_v1 

1175 

1176 async def sample_delete_topic(): 

1177 # Create a client 

1178 client = pubsub_v1.PublisherAsyncClient() 

1179 

1180 # Initialize request argument(s) 

1181 request = pubsub_v1.DeleteTopicRequest( 

1182 topic="topic_value", 

1183 ) 

1184 

1185 # Make the request 

1186 await client.delete_topic(request=request) 

1187 

1188 Args: 

1189 request (Optional[Union[google.pubsub_v1.types.DeleteTopicRequest, dict]]): 

1190 The request object. Request for the ``DeleteTopic`` method. 

1191 topic (:class:`str`): 

1192 Required. Name of the topic to delete. Format is 

1193 ``projects/{project}/topics/{topic}``. 

1194 

1195 This corresponds to the ``topic`` field 

1196 on the ``request`` instance; if ``request`` is provided, this 

1197 should not be set. 

1198 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

1199 should be retried. 

1200 timeout (TimeoutType): 

1201 The timeout for this request. 

1202 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1203 sent along with the request as metadata. Normally, each value must be of type `str`, 

1204 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1205 be of type `bytes`. 

1206 """ 

1207 # Create or coerce a protobuf request object. 

1208 # - Quick check: If we got a request object, we should *not* have 

1209 # gotten any keyword arguments that map to the request. 

1210 flattened_params = [topic] 

1211 has_flattened_params = ( 

1212 len([param for param in flattened_params if param is not None]) > 0 

1213 ) 

1214 if request is not None and has_flattened_params: 

1215 raise ValueError( 

1216 "If the `request` argument is set, then none of " 

1217 "the individual field arguments should be set." 

1218 ) 

1219 

1220 # - Use the request object if provided (there's no risk of modifying the input as 

1221 # there are no flattened fields), or create one. 

1222 if not isinstance(request, pubsub.DeleteTopicRequest): 

1223 request = pubsub.DeleteTopicRequest(request) 

1224 

1225 # If we have keyword arguments corresponding to fields on the 

1226 # request, apply these. 

1227 if topic is not None: 

1228 request.topic = topic 

1229 

1230 # Wrap the RPC method; this adds retry and timeout information, 

1231 # and friendly error handling. 

1232 rpc = self._client._transport._wrapped_methods[ 

1233 self._client._transport.delete_topic 

1234 ] 

1235 

1236 # Certain fields should be provided within the metadata header; 

1237 # add these here. 

1238 metadata = tuple(metadata) + ( 

1239 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

1240 ) 

1241 

1242 # Validate the universe domain. 

1243 self._client._validate_universe_domain() 

1244 

1245 # Send the request. 

1246 await rpc( 

1247 request, 

1248 retry=retry, 

1249 timeout=timeout, 

1250 metadata=metadata, 

1251 ) 

1252 

1253 async def detach_subscription( 

1254 self, 

1255 request: Optional[Union[pubsub.DetachSubscriptionRequest, dict]] = None, 

1256 *, 

1257 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1258 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1259 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1260 ) -> pubsub.DetachSubscriptionResponse: 

1261 r"""Detaches a subscription from this topic. All messages retained 

1262 in the subscription are dropped. Subsequent ``Pull`` and 

1263 ``StreamingPull`` requests will return FAILED_PRECONDITION. If 

1264 the subscription is a push subscription, pushes to the endpoint 

1265 will stop. 

1266 

1267 .. code-block:: python 

1268 

1269 # This snippet has been automatically generated and should be regarded as a 

1270 # code template only. 

1271 # It will require modifications to work: 

1272 # - It may require correct/in-range values for request initialization. 

1273 # - It may require specifying regional endpoints when creating the service 

1274 # client as shown in: 

1275 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1276 from google import pubsub_v1 

1277 

1278 async def sample_detach_subscription(): 

1279 # Create a client 

1280 client = pubsub_v1.PublisherAsyncClient() 

1281 

1282 # Initialize request argument(s) 

1283 request = pubsub_v1.DetachSubscriptionRequest( 

1284 subscription="subscription_value", 

1285 ) 

1286 

1287 # Make the request 

1288 response = await client.detach_subscription(request=request) 

1289 

1290 # Handle the response 

1291 print(response) 

1292 

1293 Args: 

1294 request (Optional[Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]]): 

1295 The request object. Request for the DetachSubscription 

1296 method. 

1297 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

1298 should be retried. 

1299 timeout (TimeoutType): 

1300 The timeout for this request. 

1301 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1302 sent along with the request as metadata. Normally, each value must be of type `str`, 

1303 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1304 be of type `bytes`. 

1305 

1306 Returns: 

1307 google.pubsub_v1.types.DetachSubscriptionResponse: 

1308 Response for the DetachSubscription 

1309 method. Reserved for future use. 

1310 

1311 """ 

1312 # Create or coerce a protobuf request object. 

1313 # - Use the request object if provided (there's no risk of modifying the input as 

1314 # there are no flattened fields), or create one. 

1315 if not isinstance(request, pubsub.DetachSubscriptionRequest): 

1316 request = pubsub.DetachSubscriptionRequest(request) 

1317 

1318 # Wrap the RPC method; this adds retry and timeout information, 

1319 # and friendly error handling. 

1320 rpc = self._client._transport._wrapped_methods[ 

1321 self._client._transport.detach_subscription 

1322 ] 

1323 

1324 # Certain fields should be provided within the metadata header; 

1325 # add these here. 

1326 metadata = tuple(metadata) + ( 

1327 gapic_v1.routing_header.to_grpc_metadata( 

1328 (("subscription", request.subscription),) 

1329 ), 

1330 ) 

1331 

1332 # Validate the universe domain. 

1333 self._client._validate_universe_domain() 

1334 

1335 # Send the request. 

1336 response = await rpc( 

1337 request, 

1338 retry=retry, 

1339 timeout=timeout, 

1340 metadata=metadata, 

1341 ) 

1342 

1343 # Done; return the response. 

1344 return response 

1345 

1346 async def set_iam_policy( 

1347 self, 

1348 request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, 

1349 *, 

1350 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1351 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1352 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1353 ) -> policy_pb2.Policy: 

1354 r"""Sets the IAM access control policy on the specified function. 

1355 

1356 Replaces any existing policy. 

1357 

1358 Args: 

1359 request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): 

1360 The request object. Request message for `SetIamPolicy` 

1361 method. 

1362 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

1363 should be retried. 

1364 timeout (TimeoutType): 

1365 The timeout for this request. 

1366 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1367 sent along with the request as metadata. Normally, each value must be of type `str`, 

1368 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1369 be of type `bytes`. 

1370 Returns: 

1371 ~.policy_pb2.Policy: 

1372 Defines an Identity and Access Management (IAM) policy. 

1373 It is used to specify access control policies for Cloud 

1374 Platform resources. 

1375 A ``Policy`` is a collection of ``bindings``. A 

1376 ``binding`` binds one or more ``members`` to a single 

1377 ``role``. Members can be user accounts, service 

1378 accounts, Google groups, and domains (such as G Suite). 

1379 A ``role`` is a named list of permissions (defined by 

1380 IAM or configured by users). A ``binding`` can 

1381 optionally specify a ``condition``, which is a logic 

1382 expression that further constrains the role binding 

1383 based on attributes about the request and/or target 

1384 resource. 

1385 

1386 **JSON Example** 

1387 

1388 :: 

1389 

1390 { 

1391 "bindings": [ 

1392 { 

1393 "role": "roles/resourcemanager.organizationAdmin", 

1394 "members": [ 

1395 "user:mike@example.com", 

1396 "group:admins@example.com", 

1397 "domain:google.com", 

1398 "serviceAccount:my-project-id@appspot.gserviceaccount.com" 

1399 ] 

1400 }, 

1401 { 

1402 "role": "roles/resourcemanager.organizationViewer", 

1403 "members": ["user:eve@example.com"], 

1404 "condition": { 

1405 "title": "expirable access", 

1406 "description": "Does not grant access after Sep 2020", 

1407 "expression": "request.time < 

1408 timestamp('2020-10-01T00:00:00.000Z')", 

1409 } 

1410 } 

1411 ] 

1412 } 

1413 

1414 **YAML Example** 

1415 

1416 :: 

1417 

1418 bindings: 

1419 - members: 

1420 - user:mike@example.com 

1421 - group:admins@example.com 

1422 - domain:google.com 

1423 - serviceAccount:my-project-id@appspot.gserviceaccount.com 

1424 role: roles/resourcemanager.organizationAdmin 

1425 - members: 

1426 - user:eve@example.com 

1427 role: roles/resourcemanager.organizationViewer 

1428 condition: 

1429 title: expirable access 

1430 description: Does not grant access after Sep 2020 

1431 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') 

1432 

1433 For a description of IAM and its features, see the `IAM 

1434 developer's 

1435 guide <https://cloud.google.com/iam/docs>`__. 

1436 """ 

1437 # Create or coerce a protobuf request object. 

1438 

1439 # The request isn't a proto-plus wrapped type, 

1440 # so it must be constructed via keyword expansion. 

1441 if isinstance(request, dict): 

1442 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

1443 

1444 # Wrap the RPC method; this adds retry and timeout information, 

1445 # and friendly error handling. 

1446 rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] 

1447 

1448 # Certain fields should be provided within the metadata header; 

1449 # add these here. 

1450 metadata = tuple(metadata) + ( 

1451 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

1452 ) 

1453 

1454 # Validate the universe domain. 

1455 self._client._validate_universe_domain() 

1456 

1457 # Send the request. 

1458 response = await rpc( 

1459 request, 

1460 retry=retry, 

1461 timeout=timeout, 

1462 metadata=metadata, 

1463 ) 

1464 

1465 # Done; return the response. 

1466 return response 

1467 

1468 async def get_iam_policy( 

1469 self, 

1470 request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, 

1471 *, 

1472 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1473 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1474 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1475 ) -> policy_pb2.Policy: 

1476 r"""Gets the IAM access control policy for a function. 

1477 

1478 Returns an empty policy if the function exists and does not have a 

1479 policy set. 

1480 

1481 Args: 

1482 request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): 

1483 The request object. Request message for `GetIamPolicy` 

1484 method. 

1485 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if 

1486 any, should be retried. 

1487 timeout (TimeoutType): 

1488 The timeout for this request. 

1489 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1490 sent along with the request as metadata. Normally, each value must be of type `str`, 

1491 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1492 be of type `bytes`. 

1493 Returns: 

1494 ~.policy_pb2.Policy: 

1495 Defines an Identity and Access Management (IAM) policy. 

1496 It is used to specify access control policies for Cloud 

1497 Platform resources. 

1498 A ``Policy`` is a collection of ``bindings``. A 

1499 ``binding`` binds one or more ``members`` to a single 

1500 ``role``. Members can be user accounts, service 

1501 accounts, Google groups, and domains (such as G Suite). 

1502 A ``role`` is a named list of permissions (defined by 

1503 IAM or configured by users). A ``binding`` can 

1504 optionally specify a ``condition``, which is a logic 

1505 expression that further constrains the role binding 

1506 based on attributes about the request and/or target 

1507 resource. 

1508 

1509 **JSON Example** 

1510 

1511 :: 

1512 

1513 { 

1514 "bindings": [ 

1515 { 

1516 "role": "roles/resourcemanager.organizationAdmin", 

1517 "members": [ 

1518 "user:mike@example.com", 

1519 "group:admins@example.com", 

1520 "domain:google.com", 

1521 "serviceAccount:my-project-id@appspot.gserviceaccount.com" 

1522 ] 

1523 }, 

1524 { 

1525 "role": "roles/resourcemanager.organizationViewer", 

1526 "members": ["user:eve@example.com"], 

1527 "condition": { 

1528 "title": "expirable access", 

1529 "description": "Does not grant access after Sep 2020", 

1530 "expression": "request.time < 

1531 timestamp('2020-10-01T00:00:00.000Z')", 

1532 } 

1533 } 

1534 ] 

1535 } 

1536 

1537 **YAML Example** 

1538 

1539 :: 

1540 

1541 bindings: 

1542 - members: 

1543 - user:mike@example.com 

1544 - group:admins@example.com 

1545 - domain:google.com 

1546 - serviceAccount:my-project-id@appspot.gserviceaccount.com 

1547 role: roles/resourcemanager.organizationAdmin 

1548 - members: 

1549 - user:eve@example.com 

1550 role: roles/resourcemanager.organizationViewer 

1551 condition: 

1552 title: expirable access 

1553 description: Does not grant access after Sep 2020 

1554 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') 

1555 

1556 For a description of IAM and its features, see the `IAM 

1557 developer's 

1558 guide <https://cloud.google.com/iam/docs>`__. 

1559 """ 

1560 # Create or coerce a protobuf request object. 

1561 

1562 # The request isn't a proto-plus wrapped type, 

1563 # so it must be constructed via keyword expansion. 

1564 if isinstance(request, dict): 

1565 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

1566 

1567 # Wrap the RPC method; this adds retry and timeout information, 

1568 # and friendly error handling. 

1569 rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] 

1570 

1571 # Certain fields should be provided within the metadata header; 

1572 # add these here. 

1573 metadata = tuple(metadata) + ( 

1574 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

1575 ) 

1576 

1577 # Validate the universe domain. 

1578 self._client._validate_universe_domain() 

1579 

1580 # Send the request. 

1581 response = await rpc( 

1582 request, 

1583 retry=retry, 

1584 timeout=timeout, 

1585 metadata=metadata, 

1586 ) 

1587 

1588 # Done; return the response. 

1589 return response 

1590 

1591 async def test_iam_permissions( 

1592 self, 

1593 request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, 

1594 *, 

1595 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1596 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1597 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1598 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

1599 r"""Tests the specified IAM permissions against the IAM access control 

1600 policy for a function. 

1601 

1602 If the function does not exist, this will return an empty set 

1603 of permissions, not a NOT_FOUND error. 

1604 

1605 Args: 

1606 request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): 

1607 The request object. Request message for 

1608 `TestIamPermissions` method. 

1609 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, 

1610 if any, should be retried. 

1611 timeout (TimeoutType): 

1612 The timeout for this request. 

1613 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1614 sent along with the request as metadata. Normally, each value must be of type `str`, 

1615 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1616 be of type `bytes`. 

1617 Returns: 

1618 ~.iam_policy_pb2.TestIamPermissionsResponse: 

1619 Response message for ``TestIamPermissions`` method. 

1620 """ 

1621 # Create or coerce a protobuf request object. 

1622 

1623 # The request isn't a proto-plus wrapped type, 

1624 # so it must be constructed via keyword expansion. 

1625 if isinstance(request, dict): 

1626 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

1627 

1628 # Wrap the RPC method; this adds retry and timeout information, 

1629 # and friendly error handling. 

1630 rpc = self.transport._wrapped_methods[ 

1631 self._client._transport.test_iam_permissions 

1632 ] 

1633 

1634 # Certain fields should be provided within the metadata header; 

1635 # add these here. 

1636 metadata = tuple(metadata) + ( 

1637 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

1638 ) 

1639 

1640 # Validate the universe domain. 

1641 self._client._validate_universe_domain() 

1642 

1643 # Send the request. 

1644 response = await rpc( 

1645 request, 

1646 retry=retry, 

1647 timeout=timeout, 

1648 metadata=metadata, 

1649 ) 

1650 

1651 # Done; return the response. 

1652 return response 

1653 

1654 async def __aenter__(self) -> "PublisherAsyncClient": 

1655 return self 

1656 

1657 async def __aexit__(self, exc_type, exc, tb): 

1658 await self.transport.close() 

1659 

1660 

1661DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1662 client_library_version=package_version.__version__ 

1663) 

1664 

1665 

1666__all__ = ("PublisherAsyncClient",)