Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/pubsub_v1/services/publisher/transports/grpc.py: 43%

112 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-26 06:25 +0000

1# -*- coding: utf-8 -*- 

2# Copyright 2022 Google LLC 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# 

8# http://www.apache.org/licenses/LICENSE-2.0 

9# 

10# Unless required by applicable law or agreed to in writing, software 

11# distributed under the License is distributed on an "AS IS" BASIS, 

12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

13# See the License for the specific language governing permissions and 

14# limitations under the License. 

15# 

16import warnings 

17from typing import Callable, Dict, Optional, Sequence, Tuple, Union 

18 

19from google.api_core import grpc_helpers 

20from google.api_core import gapic_v1 

21import google.auth # type: ignore 

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

23from google.auth.transport.grpc import SslCredentials # type: ignore 

24 

25import grpc # type: ignore 

26 

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

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

29from google.protobuf import empty_pb2 # type: ignore 

30from google.pubsub_v1.types import pubsub 

31from .base import PublisherTransport, DEFAULT_CLIENT_INFO 

32 

33 

34class PublisherGrpcTransport(PublisherTransport): 

35 """gRPC backend transport for Publisher. 

36 

37 The service that an application uses to manipulate topics, 

38 and to send messages to a topic. 

39 

40 This class defines the same methods as the primary client, so the 

41 primary client can load the underlying transport implementation 

42 and call it. 

43 

44 It sends protocol buffers over the wire using gRPC (which is built on 

45 top of HTTP/2); the ``grpcio`` package must be installed. 

46 """ 

47 

48 _stubs: Dict[str, Callable] 

49 

50 def __init__( 

51 self, 

52 *, 

53 host: str = "pubsub.googleapis.com", 

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

55 credentials_file: Optional[str] = None, 

56 scopes: Optional[Sequence[str]] = None, 

57 channel: Optional[grpc.Channel] = None, 

58 api_mtls_endpoint: Optional[str] = None, 

59 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, 

60 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, 

61 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, 

62 quota_project_id: Optional[str] = None, 

63 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

64 always_use_jwt_access: Optional[bool] = False, 

65 api_audience: Optional[str] = None, 

66 ) -> None: 

67 """Instantiate the transport. 

68 

69 Args: 

70 host (Optional[str]): 

71 The hostname to connect to. 

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

73 authorization credentials to attach to requests. These 

74 credentials identify the application to the service; if none 

75 are specified, the client will attempt to ascertain the 

76 credentials from the environment. 

77 This argument is ignored if ``channel`` is provided. 

78 credentials_file (Optional[str]): A file with credentials that can 

79 be loaded with :func:`google.auth.load_credentials_from_file`. 

80 This argument is ignored if ``channel`` is provided. 

81 scopes (Optional(Sequence[str])): A list of scopes. This argument is 

82 ignored if ``channel`` is provided. 

83 channel (Optional[grpc.Channel]): A ``Channel`` instance through 

84 which to make calls. 

85 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. 

86 If provided, it overrides the ``host`` argument and tries to create 

87 a mutual TLS channel with client SSL credentials from 

88 ``client_cert_source`` or application default SSL credentials. 

89 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 

90 Deprecated. A callback to provide client SSL certificate bytes and 

91 private key bytes, both in PEM format. It is ignored if 

92 ``api_mtls_endpoint`` is None. 

93 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials 

94 for the grpc channel. It is ignored if ``channel`` is provided. 

95 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): 

96 A callback to provide client certificate bytes and private key bytes, 

97 both in PEM format. It is used to configure a mutual TLS channel. It is 

98 ignored if ``channel`` or ``ssl_channel_credentials`` is provided. 

99 quota_project_id (Optional[str]): An optional project to use for billing 

100 and quota. 

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

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

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

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

105 your own client library. 

106 always_use_jwt_access (Optional[bool]): Whether self signed JWT should 

107 be used for service account credentials. 

108 

109 Raises: 

110 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport 

111 creation failed for any reason. 

112 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` 

113 and ``credentials_file`` are passed. 

114 """ 

115 self._grpc_channel = None 

116 self._ssl_channel_credentials = ssl_channel_credentials 

117 self._stubs: Dict[str, Callable] = {} 

118 

119 if api_mtls_endpoint: 

120 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) 

121 if client_cert_source: 

122 warnings.warn("client_cert_source is deprecated", DeprecationWarning) 

123 

124 if channel: 

125 # Ignore credentials if a channel was passed. 

126 credentials = False 

127 # If a channel was explicitly provided, set it. 

128 self._grpc_channel = channel 

129 self._ssl_channel_credentials = None 

130 

131 else: 

132 if api_mtls_endpoint: 

133 host = api_mtls_endpoint 

134 

135 # Create SSL credentials with client_cert_source or application 

136 # default SSL credentials. 

137 if client_cert_source: 

138 cert, key = client_cert_source() 

139 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

140 certificate_chain=cert, private_key=key 

141 ) 

142 else: 

143 self._ssl_channel_credentials = SslCredentials().ssl_credentials 

144 

145 else: 

146 if client_cert_source_for_mtls and not ssl_channel_credentials: 

147 cert, key = client_cert_source_for_mtls() 

148 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

149 certificate_chain=cert, private_key=key 

150 ) 

151 

152 # The base transport sets the host, credentials and scopes 

153 super().__init__( 

154 host=host, 

155 credentials=credentials, 

156 credentials_file=credentials_file, 

157 scopes=scopes, 

158 quota_project_id=quota_project_id, 

159 client_info=client_info, 

160 always_use_jwt_access=always_use_jwt_access, 

161 api_audience=api_audience, 

162 ) 

163 

164 if not self._grpc_channel: 

165 self._grpc_channel = type(self).create_channel( 

166 self._host, 

167 # use the credentials which are saved 

168 credentials=self._credentials, 

169 # Set ``credentials_file`` to ``None`` here as 

170 # the credentials that we saved earlier should be used. 

171 credentials_file=None, 

172 scopes=self._scopes, 

173 ssl_credentials=self._ssl_channel_credentials, 

174 quota_project_id=quota_project_id, 

175 options=[ 

176 ("grpc.max_send_message_length", -1), 

177 ("grpc.max_receive_message_length", -1), 

178 ("grpc.max_metadata_size", 4 * 1024 * 1024), 

179 ("grpc.keepalive_time_ms", 30000), 

180 ], 

181 ) 

182 

183 # Wrap messages. This must be done after self._grpc_channel exists 

184 self._prep_wrapped_messages(client_info) 

185 

186 @classmethod 

187 def create_channel( 

188 cls, 

189 host: str = "pubsub.googleapis.com", 

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

191 credentials_file: Optional[str] = None, 

192 scopes: Optional[Sequence[str]] = None, 

193 quota_project_id: Optional[str] = None, 

194 **kwargs, 

195 ) -> grpc.Channel: 

196 """Create and return a gRPC channel object. 

197 Args: 

198 host (Optional[str]): The host for the channel to use. 

199 credentials (Optional[~.Credentials]): The 

200 authorization credentials to attach to requests. These 

201 credentials identify this application to the service. If 

202 none are specified, the client will attempt to ascertain 

203 the credentials from the environment. 

204 credentials_file (Optional[str]): A file with credentials that can 

205 be loaded with :func:`google.auth.load_credentials_from_file`. 

206 This argument is mutually exclusive with credentials. 

207 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this 

208 service. These are only used when credentials are not specified and 

209 are passed to :func:`google.auth.default`. 

210 quota_project_id (Optional[str]): An optional project to use for billing 

211 and quota. 

212 kwargs (Optional[dict]): Keyword arguments, which are passed to the 

213 channel creation. 

214 Returns: 

215 grpc.Channel: A gRPC channel object. 

216 

217 Raises: 

218 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` 

219 and ``credentials_file`` are passed. 

220 """ 

221 

222 return grpc_helpers.create_channel( 

223 host, 

224 credentials=credentials, 

225 credentials_file=credentials_file, 

226 quota_project_id=quota_project_id, 

227 default_scopes=cls.AUTH_SCOPES, 

228 scopes=scopes, 

229 default_host=cls.DEFAULT_HOST, 

230 **kwargs, 

231 ) 

232 

233 @property 

234 def grpc_channel(self) -> grpc.Channel: 

235 """Return the channel designed to connect to this service.""" 

236 return self._grpc_channel 

237 

238 @property 

239 def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: 

240 r"""Return a callable for the create topic method over gRPC. 

241 

242 Creates the given topic with the given name. See the [resource 

243 name rules] 

244 (https://cloud.google.com/pubsub/docs/admin#resource_names). 

245 

246 Returns: 

247 Callable[[~.Topic], 

248 ~.Topic]: 

249 A function that, when called, will call the underlying RPC 

250 on the server. 

251 """ 

252 # Generate a "stub function" on-the-fly which will actually make 

253 # the request. 

254 # gRPC handles serialization and deserialization, so we just need 

255 # to pass in the functions for each. 

256 if "create_topic" not in self._stubs: 

257 self._stubs["create_topic"] = self.grpc_channel.unary_unary( 

258 "/google.pubsub.v1.Publisher/CreateTopic", 

259 request_serializer=pubsub.Topic.serialize, 

260 response_deserializer=pubsub.Topic.deserialize, 

261 ) 

262 return self._stubs["create_topic"] 

263 

264 @property 

265 def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: 

266 r"""Return a callable for the update topic method over gRPC. 

267 

268 Updates an existing topic. Note that certain 

269 properties of a topic are not modifiable. 

270 

271 Returns: 

272 Callable[[~.UpdateTopicRequest], 

273 ~.Topic]: 

274 A function that, when called, will call the underlying RPC 

275 on the server. 

276 """ 

277 # Generate a "stub function" on-the-fly which will actually make 

278 # the request. 

279 # gRPC handles serialization and deserialization, so we just need 

280 # to pass in the functions for each. 

281 if "update_topic" not in self._stubs: 

282 self._stubs["update_topic"] = self.grpc_channel.unary_unary( 

283 "/google.pubsub.v1.Publisher/UpdateTopic", 

284 request_serializer=pubsub.UpdateTopicRequest.serialize, 

285 response_deserializer=pubsub.Topic.deserialize, 

286 ) 

287 return self._stubs["update_topic"] 

288 

289 @property 

290 def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: 

291 r"""Return a callable for the publish method over gRPC. 

292 

293 Adds one or more messages to the topic. Returns ``NOT_FOUND`` if 

294 the topic does not exist. 

295 

296 Returns: 

297 Callable[[~.PublishRequest], 

298 ~.PublishResponse]: 

299 A function that, when called, will call the underlying RPC 

300 on the server. 

301 """ 

302 # Generate a "stub function" on-the-fly which will actually make 

303 # the request. 

304 # gRPC handles serialization and deserialization, so we just need 

305 # to pass in the functions for each. 

306 if "publish" not in self._stubs: 

307 self._stubs["publish"] = self.grpc_channel.unary_unary( 

308 "/google.pubsub.v1.Publisher/Publish", 

309 request_serializer=pubsub.PublishRequest.serialize, 

310 response_deserializer=pubsub.PublishResponse.deserialize, 

311 ) 

312 return self._stubs["publish"] 

313 

314 @property 

315 def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: 

316 r"""Return a callable for the get topic method over gRPC. 

317 

318 Gets the configuration of a topic. 

319 

320 Returns: 

321 Callable[[~.GetTopicRequest], 

322 ~.Topic]: 

323 A function that, when called, will call the underlying RPC 

324 on the server. 

325 """ 

326 # Generate a "stub function" on-the-fly which will actually make 

327 # the request. 

328 # gRPC handles serialization and deserialization, so we just need 

329 # to pass in the functions for each. 

330 if "get_topic" not in self._stubs: 

331 self._stubs["get_topic"] = self.grpc_channel.unary_unary( 

332 "/google.pubsub.v1.Publisher/GetTopic", 

333 request_serializer=pubsub.GetTopicRequest.serialize, 

334 response_deserializer=pubsub.Topic.deserialize, 

335 ) 

336 return self._stubs["get_topic"] 

337 

338 @property 

339 def list_topics( 

340 self, 

341 ) -> Callable[[pubsub.ListTopicsRequest], pubsub.ListTopicsResponse]: 

342 r"""Return a callable for the list topics method over gRPC. 

343 

344 Lists matching topics. 

345 

346 Returns: 

347 Callable[[~.ListTopicsRequest], 

348 ~.ListTopicsResponse]: 

349 A function that, when called, will call the underlying RPC 

350 on the server. 

351 """ 

352 # Generate a "stub function" on-the-fly which will actually make 

353 # the request. 

354 # gRPC handles serialization and deserialization, so we just need 

355 # to pass in the functions for each. 

356 if "list_topics" not in self._stubs: 

357 self._stubs["list_topics"] = self.grpc_channel.unary_unary( 

358 "/google.pubsub.v1.Publisher/ListTopics", 

359 request_serializer=pubsub.ListTopicsRequest.serialize, 

360 response_deserializer=pubsub.ListTopicsResponse.deserialize, 

361 ) 

362 return self._stubs["list_topics"] 

363 

364 @property 

365 def list_topic_subscriptions( 

366 self, 

367 ) -> Callable[ 

368 [pubsub.ListTopicSubscriptionsRequest], pubsub.ListTopicSubscriptionsResponse 

369 ]: 

370 r"""Return a callable for the list topic subscriptions method over gRPC. 

371 

372 Lists the names of the attached subscriptions on this 

373 topic. 

374 

375 Returns: 

376 Callable[[~.ListTopicSubscriptionsRequest], 

377 ~.ListTopicSubscriptionsResponse]: 

378 A function that, when called, will call the underlying RPC 

379 on the server. 

380 """ 

381 # Generate a "stub function" on-the-fly which will actually make 

382 # the request. 

383 # gRPC handles serialization and deserialization, so we just need 

384 # to pass in the functions for each. 

385 if "list_topic_subscriptions" not in self._stubs: 

386 self._stubs["list_topic_subscriptions"] = self.grpc_channel.unary_unary( 

387 "/google.pubsub.v1.Publisher/ListTopicSubscriptions", 

388 request_serializer=pubsub.ListTopicSubscriptionsRequest.serialize, 

389 response_deserializer=pubsub.ListTopicSubscriptionsResponse.deserialize, 

390 ) 

391 return self._stubs["list_topic_subscriptions"] 

392 

393 @property 

394 def list_topic_snapshots( 

395 self, 

396 ) -> Callable[ 

397 [pubsub.ListTopicSnapshotsRequest], pubsub.ListTopicSnapshotsResponse 

398 ]: 

399 r"""Return a callable for the list topic snapshots method over gRPC. 

400 

401 Lists the names of the snapshots on this topic. Snapshots are 

402 used in 

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

404 operations, which allow you to manage message acknowledgments in 

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

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

407 

408 Returns: 

409 Callable[[~.ListTopicSnapshotsRequest], 

410 ~.ListTopicSnapshotsResponse]: 

411 A function that, when called, will call the underlying RPC 

412 on the server. 

413 """ 

414 # Generate a "stub function" on-the-fly which will actually make 

415 # the request. 

416 # gRPC handles serialization and deserialization, so we just need 

417 # to pass in the functions for each. 

418 if "list_topic_snapshots" not in self._stubs: 

419 self._stubs["list_topic_snapshots"] = self.grpc_channel.unary_unary( 

420 "/google.pubsub.v1.Publisher/ListTopicSnapshots", 

421 request_serializer=pubsub.ListTopicSnapshotsRequest.serialize, 

422 response_deserializer=pubsub.ListTopicSnapshotsResponse.deserialize, 

423 ) 

424 return self._stubs["list_topic_snapshots"] 

425 

426 @property 

427 def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty_pb2.Empty]: 

428 r"""Return a callable for the delete topic method over gRPC. 

429 

430 Deletes the topic with the given name. Returns ``NOT_FOUND`` if 

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

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

433 with none of the old configuration or subscriptions. Existing 

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

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

436 

437 Returns: 

438 Callable[[~.DeleteTopicRequest], 

439 ~.Empty]: 

440 A function that, when called, will call the underlying RPC 

441 on the server. 

442 """ 

443 # Generate a "stub function" on-the-fly which will actually make 

444 # the request. 

445 # gRPC handles serialization and deserialization, so we just need 

446 # to pass in the functions for each. 

447 if "delete_topic" not in self._stubs: 

448 self._stubs["delete_topic"] = self.grpc_channel.unary_unary( 

449 "/google.pubsub.v1.Publisher/DeleteTopic", 

450 request_serializer=pubsub.DeleteTopicRequest.serialize, 

451 response_deserializer=empty_pb2.Empty.FromString, 

452 ) 

453 return self._stubs["delete_topic"] 

454 

455 @property 

456 def detach_subscription( 

457 self, 

458 ) -> Callable[ 

459 [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse 

460 ]: 

461 r"""Return a callable for the detach subscription method over gRPC. 

462 

463 Detaches a subscription from this topic. All messages retained 

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

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

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

467 will stop. 

468 

469 Returns: 

470 Callable[[~.DetachSubscriptionRequest], 

471 ~.DetachSubscriptionResponse]: 

472 A function that, when called, will call the underlying RPC 

473 on the server. 

474 """ 

475 # Generate a "stub function" on-the-fly which will actually make 

476 # the request. 

477 # gRPC handles serialization and deserialization, so we just need 

478 # to pass in the functions for each. 

479 if "detach_subscription" not in self._stubs: 

480 self._stubs["detach_subscription"] = self.grpc_channel.unary_unary( 

481 "/google.pubsub.v1.Publisher/DetachSubscription", 

482 request_serializer=pubsub.DetachSubscriptionRequest.serialize, 

483 response_deserializer=pubsub.DetachSubscriptionResponse.deserialize, 

484 ) 

485 return self._stubs["detach_subscription"] 

486 

487 @property 

488 def set_iam_policy( 

489 self, 

490 ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: 

491 r"""Return a callable for the set iam policy method over gRPC. 

492 Sets the IAM access control policy on the specified 

493 function. Replaces any existing policy. 

494 Returns: 

495 Callable[[~.SetIamPolicyRequest], 

496 ~.Policy]: 

497 A function that, when called, will call the underlying RPC 

498 on the server. 

499 """ 

500 # Generate a "stub function" on-the-fly which will actually make 

501 # the request. 

502 # gRPC handles serialization and deserialization, so we just need 

503 # to pass in the functions for each. 

504 if "set_iam_policy" not in self._stubs: 

505 self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( 

506 "/google.iam.v1.IAMPolicy/SetIamPolicy", 

507 request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, 

508 response_deserializer=policy_pb2.Policy.FromString, 

509 ) 

510 return self._stubs["set_iam_policy"] 

511 

512 @property 

513 def get_iam_policy( 

514 self, 

515 ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: 

516 r"""Return a callable for the get iam policy method over gRPC. 

517 Gets the IAM access control policy for a function. 

518 Returns an empty policy if the function exists and does 

519 not have a policy set. 

520 Returns: 

521 Callable[[~.GetIamPolicyRequest], 

522 ~.Policy]: 

523 A function that, when called, will call the underlying RPC 

524 on the server. 

525 """ 

526 # Generate a "stub function" on-the-fly which will actually make 

527 # the request. 

528 # gRPC handles serialization and deserialization, so we just need 

529 # to pass in the functions for each. 

530 if "get_iam_policy" not in self._stubs: 

531 self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( 

532 "/google.iam.v1.IAMPolicy/GetIamPolicy", 

533 request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, 

534 response_deserializer=policy_pb2.Policy.FromString, 

535 ) 

536 return self._stubs["get_iam_policy"] 

537 

538 @property 

539 def test_iam_permissions( 

540 self, 

541 ) -> Callable[ 

542 [iam_policy_pb2.TestIamPermissionsRequest], 

543 iam_policy_pb2.TestIamPermissionsResponse, 

544 ]: 

545 r"""Return a callable for the test iam permissions method over gRPC. 

546 Tests the specified permissions against the IAM access control 

547 policy for a function. If the function does not exist, this will 

548 return an empty set of permissions, not a NOT_FOUND error. 

549 Returns: 

550 Callable[[~.TestIamPermissionsRequest], 

551 ~.TestIamPermissionsResponse]: 

552 A function that, when called, will call the underlying RPC 

553 on the server. 

554 """ 

555 # Generate a "stub function" on-the-fly which will actually make 

556 # the request. 

557 # gRPC handles serialization and deserialization, so we just need 

558 # to pass in the functions for each. 

559 if "test_iam_permissions" not in self._stubs: 

560 self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( 

561 "/google.iam.v1.IAMPolicy/TestIamPermissions", 

562 request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, 

563 response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, 

564 ) 

565 return self._stubs["test_iam_permissions"] 

566 

567 def close(self): 

568 self.grpc_channel.close() 

569 

570 @property 

571 def kind(self) -> str: 

572 return "grpc" 

573 

574 

575__all__ = ("PublisherGrpcTransport",)