Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/google/cloud/errorreporting_v1beta1/services/error_group_service/transports/grpc_asyncio.py: 49%

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

85 statements  

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

2# Copyright 2025 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 inspect 

17import json 

18import pickle 

19import logging as std_logging 

20import warnings 

21from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 

22 

23from google.api_core import gapic_v1 

24from google.api_core import grpc_helpers_async 

25from google.api_core import exceptions as core_exceptions 

26from google.api_core import retry_async as retries 

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

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

29from google.protobuf.json_format import MessageToJson 

30import google.protobuf.message 

31 

32import grpc # type: ignore 

33import proto # type: ignore 

34from grpc.experimental import aio # type: ignore 

35 

36from google.cloud.errorreporting_v1beta1.types import common 

37from google.cloud.errorreporting_v1beta1.types import error_group_service 

38from .base import ErrorGroupServiceTransport, DEFAULT_CLIENT_INFO 

39from .grpc import ErrorGroupServiceGrpcTransport 

40 

41try: 

42 from google.api_core import client_logging # type: ignore 

43 

44 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

45except ImportError: # pragma: NO COVER 

46 CLIENT_LOGGING_SUPPORTED = False 

47 

48_LOGGER = std_logging.getLogger(__name__) 

49 

50 

51class _LoggingClientAIOInterceptor( 

52 grpc.aio.UnaryUnaryClientInterceptor 

53): # pragma: NO COVER 

54 async def intercept_unary_unary(self, continuation, client_call_details, request): 

55 logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

56 std_logging.DEBUG 

57 ) 

58 if logging_enabled: # pragma: NO COVER 

59 request_metadata = client_call_details.metadata 

60 if isinstance(request, proto.Message): 

61 request_payload = type(request).to_json(request) 

62 elif isinstance(request, google.protobuf.message.Message): 

63 request_payload = MessageToJson(request) 

64 else: 

65 request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" 

66 

67 request_metadata = { 

68 key: value.decode("utf-8") if isinstance(value, bytes) else value 

69 for key, value in request_metadata 

70 } 

71 grpc_request = { 

72 "payload": request_payload, 

73 "requestMethod": "grpc", 

74 "metadata": dict(request_metadata), 

75 } 

76 _LOGGER.debug( 

77 f"Sending request for {client_call_details.method}", 

78 extra={ 

79 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService", 

80 "rpcName": str(client_call_details.method), 

81 "request": grpc_request, 

82 "metadata": grpc_request["metadata"], 

83 }, 

84 ) 

85 response = await continuation(client_call_details, request) 

86 if logging_enabled: # pragma: NO COVER 

87 response_metadata = await response.trailing_metadata() 

88 # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples 

89 metadata = ( 

90 dict([(k, str(v)) for k, v in response_metadata]) 

91 if response_metadata 

92 else None 

93 ) 

94 result = await response 

95 if isinstance(result, proto.Message): 

96 response_payload = type(result).to_json(result) 

97 elif isinstance(result, google.protobuf.message.Message): 

98 response_payload = MessageToJson(result) 

99 else: 

100 response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" 

101 grpc_response = { 

102 "payload": response_payload, 

103 "metadata": metadata, 

104 "status": "OK", 

105 } 

106 _LOGGER.debug( 

107 f"Received response to rpc {client_call_details.method}.", 

108 extra={ 

109 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService", 

110 "rpcName": str(client_call_details.method), 

111 "response": grpc_response, 

112 "metadata": grpc_response["metadata"], 

113 }, 

114 ) 

115 return response 

116 

117 

118class ErrorGroupServiceGrpcAsyncIOTransport(ErrorGroupServiceTransport): 

119 """gRPC AsyncIO backend transport for ErrorGroupService. 

120 

121 Service for retrieving and updating individual error groups. 

122 

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

124 primary client can load the underlying transport implementation 

125 and call it. 

126 

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

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

129 """ 

130 

131 _grpc_channel: aio.Channel 

132 _stubs: Dict[str, Callable] = {} 

133 

134 @classmethod 

135 def create_channel( 

136 cls, 

137 host: str = "clouderrorreporting.googleapis.com", 

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

139 credentials_file: Optional[str] = None, 

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

141 quota_project_id: Optional[str] = None, 

142 **kwargs, 

143 ) -> aio.Channel: 

144 """Create and return a gRPC AsyncIO channel object. 

145 Args: 

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

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

148 authorization credentials to attach to requests. These 

149 credentials identify this application to the service. If 

150 none are specified, the client will attempt to ascertain 

151 the credentials from the environment. 

152 credentials_file (Optional[str]): Deprecated. A file with credentials that can 

153 be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be 

154 removed in the next major version of this library. 

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

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

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

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

159 and quota. 

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

161 channel creation. 

162 Returns: 

163 aio.Channel: A gRPC AsyncIO channel object. 

164 """ 

165 

166 return grpc_helpers_async.create_channel( 

167 host, 

168 credentials=credentials, 

169 credentials_file=credentials_file, 

170 quota_project_id=quota_project_id, 

171 default_scopes=cls.AUTH_SCOPES, 

172 scopes=scopes, 

173 default_host=cls.DEFAULT_HOST, 

174 **kwargs, 

175 ) 

176 

177 def __init__( 

178 self, 

179 *, 

180 host: str = "clouderrorreporting.googleapis.com", 

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

182 credentials_file: Optional[str] = None, 

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

184 channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, 

185 api_mtls_endpoint: Optional[str] = None, 

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

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

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

189 quota_project_id: Optional[str] = None, 

190 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

191 always_use_jwt_access: Optional[bool] = False, 

192 api_audience: Optional[str] = None, 

193 ) -> None: 

194 """Instantiate the transport. 

195 

196 Args: 

197 host (Optional[str]): 

198 The hostname to connect to (default: 'clouderrorreporting.googleapis.com'). 

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

200 authorization credentials to attach to requests. These 

201 credentials identify the application to the service; if none 

202 are specified, the client will attempt to ascertain the 

203 credentials from the environment. 

204 This argument is ignored if a ``channel`` instance is provided. 

205 credentials_file (Optional[str]): Deprecated. A file with credentials that can 

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

207 This argument is ignored if a ``channel`` instance is provided. 

208 This argument will be removed in the next major version of this library. 

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

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

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

212 channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): 

213 A ``Channel`` instance through which to make calls, or a Callable 

214 that constructs and returns one. If set to None, ``self.create_channel`` 

215 is used to create the channel. If a Callable is given, it will be called 

216 with the same arguments as used in ``self.create_channel``. 

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

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

219 a mutual TLS channel with client SSL credentials from 

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

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

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

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

224 ``api_mtls_endpoint`` is None. 

225 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials 

226 for the grpc channel. It is ignored if a ``channel`` instance is provided. 

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

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

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

230 ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. 

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

232 and quota. 

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

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

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

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

237 your own client library. 

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

239 be used for service account credentials. 

240 

241 Raises: 

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

243 creation failed for any reason. 

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

245 and ``credentials_file`` are passed. 

246 """ 

247 self._grpc_channel = None 

248 self._ssl_channel_credentials = ssl_channel_credentials 

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

250 

251 if api_mtls_endpoint: 

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

253 if client_cert_source: 

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

255 

256 if isinstance(channel, aio.Channel): 

257 # Ignore credentials if a channel was passed. 

258 credentials = None 

259 self._ignore_credentials = True 

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

261 self._grpc_channel = channel 

262 self._ssl_channel_credentials = None 

263 else: 

264 if api_mtls_endpoint: 

265 host = api_mtls_endpoint 

266 

267 # Create SSL credentials with client_cert_source or application 

268 # default SSL credentials. 

269 if client_cert_source: 

270 cert, key = client_cert_source() 

271 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

272 certificate_chain=cert, private_key=key 

273 ) 

274 else: 

275 self._ssl_channel_credentials = SslCredentials().ssl_credentials 

276 

277 else: 

278 if client_cert_source_for_mtls and not ssl_channel_credentials: 

279 cert, key = client_cert_source_for_mtls() 

280 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

281 certificate_chain=cert, private_key=key 

282 ) 

283 

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

285 super().__init__( 

286 host=host, 

287 credentials=credentials, 

288 credentials_file=credentials_file, 

289 scopes=scopes, 

290 quota_project_id=quota_project_id, 

291 client_info=client_info, 

292 always_use_jwt_access=always_use_jwt_access, 

293 api_audience=api_audience, 

294 ) 

295 

296 if not self._grpc_channel: 

297 # initialize with the provided callable or the default channel 

298 channel_init = channel or type(self).create_channel 

299 self._grpc_channel = channel_init( 

300 self._host, 

301 # use the credentials which are saved 

302 credentials=self._credentials, 

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

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

305 credentials_file=None, 

306 scopes=self._scopes, 

307 ssl_credentials=self._ssl_channel_credentials, 

308 quota_project_id=quota_project_id, 

309 options=[ 

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

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

312 ], 

313 ) 

314 

315 self._interceptor = _LoggingClientAIOInterceptor() 

316 self._grpc_channel._unary_unary_interceptors.append(self._interceptor) 

317 self._logged_channel = self._grpc_channel 

318 self._wrap_with_kind = ( 

319 "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters 

320 ) 

321 # Wrap messages. This must be done after self._logged_channel exists 

322 self._prep_wrapped_messages(client_info) 

323 

324 @property 

325 def grpc_channel(self) -> aio.Channel: 

326 """Create the channel designed to connect to this service. 

327 

328 This property caches on the instance; repeated calls return 

329 the same channel. 

330 """ 

331 # Return the channel from cache. 

332 return self._grpc_channel 

333 

334 @property 

335 def get_group( 

336 self, 

337 ) -> Callable[[error_group_service.GetGroupRequest], Awaitable[common.ErrorGroup]]: 

338 r"""Return a callable for the get group method over gRPC. 

339 

340 Get the specified group. 

341 

342 Returns: 

343 Callable[[~.GetGroupRequest], 

344 Awaitable[~.ErrorGroup]]: 

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

346 on the server. 

347 """ 

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

349 # the request. 

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

351 # to pass in the functions for each. 

352 if "get_group" not in self._stubs: 

353 self._stubs["get_group"] = self._logged_channel.unary_unary( 

354 "/google.devtools.clouderrorreporting.v1beta1.ErrorGroupService/GetGroup", 

355 request_serializer=error_group_service.GetGroupRequest.serialize, 

356 response_deserializer=common.ErrorGroup.deserialize, 

357 ) 

358 return self._stubs["get_group"] 

359 

360 @property 

361 def update_group( 

362 self, 

363 ) -> Callable[ 

364 [error_group_service.UpdateGroupRequest], Awaitable[common.ErrorGroup] 

365 ]: 

366 r"""Return a callable for the update group method over gRPC. 

367 

368 Replace the data for the specified group. 

369 Fails if the group does not exist. 

370 

371 Returns: 

372 Callable[[~.UpdateGroupRequest], 

373 Awaitable[~.ErrorGroup]]: 

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

375 on the server. 

376 """ 

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

378 # the request. 

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

380 # to pass in the functions for each. 

381 if "update_group" not in self._stubs: 

382 self._stubs["update_group"] = self._logged_channel.unary_unary( 

383 "/google.devtools.clouderrorreporting.v1beta1.ErrorGroupService/UpdateGroup", 

384 request_serializer=error_group_service.UpdateGroupRequest.serialize, 

385 response_deserializer=common.ErrorGroup.deserialize, 

386 ) 

387 return self._stubs["update_group"] 

388 

389 def _prep_wrapped_messages(self, client_info): 

390 """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" 

391 self._wrapped_methods = { 

392 self.get_group: self._wrap_method( 

393 self.get_group, 

394 default_timeout=None, 

395 client_info=client_info, 

396 ), 

397 self.update_group: self._wrap_method( 

398 self.update_group, 

399 default_timeout=None, 

400 client_info=client_info, 

401 ), 

402 } 

403 

404 def _wrap_method(self, func, *args, **kwargs): 

405 if self._wrap_with_kind: # pragma: NO COVER 

406 kwargs["kind"] = self.kind 

407 return gapic_v1.method_async.wrap_method(func, *args, **kwargs) 

408 

409 def close(self): 

410 return self._logged_channel.close() 

411 

412 @property 

413 def kind(self) -> str: 

414 return "grpc_asyncio" 

415 

416 

417__all__ = ("ErrorGroupServiceGrpcAsyncIOTransport",)