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 error_stats_service
37from .base import ErrorStatsServiceTransport, DEFAULT_CLIENT_INFO
38from .grpc import ErrorStatsServiceGrpcTransport
39
40try:
41 from google.api_core import client_logging # type: ignore
42
43 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
44except ImportError: # pragma: NO COVER
45 CLIENT_LOGGING_SUPPORTED = False
46
47_LOGGER = std_logging.getLogger(__name__)
48
49
50class _LoggingClientAIOInterceptor(
51 grpc.aio.UnaryUnaryClientInterceptor
52): # pragma: NO COVER
53 async def intercept_unary_unary(self, continuation, client_call_details, request):
54 logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
55 std_logging.DEBUG
56 )
57 if logging_enabled: # pragma: NO COVER
58 request_metadata = client_call_details.metadata
59 if isinstance(request, proto.Message):
60 request_payload = type(request).to_json(request)
61 elif isinstance(request, google.protobuf.message.Message):
62 request_payload = MessageToJson(request)
63 else:
64 request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
65
66 request_metadata = {
67 key: value.decode("utf-8") if isinstance(value, bytes) else value
68 for key, value in request_metadata
69 }
70 grpc_request = {
71 "payload": request_payload,
72 "requestMethod": "grpc",
73 "metadata": dict(request_metadata),
74 }
75 _LOGGER.debug(
76 f"Sending request for {client_call_details.method}",
77 extra={
78 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorStatsService",
79 "rpcName": str(client_call_details.method),
80 "request": grpc_request,
81 "metadata": grpc_request["metadata"],
82 },
83 )
84 response = await continuation(client_call_details, request)
85 if logging_enabled: # pragma: NO COVER
86 response_metadata = await response.trailing_metadata()
87 # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
88 metadata = (
89 dict([(k, str(v)) for k, v in response_metadata])
90 if response_metadata
91 else None
92 )
93 result = await response
94 if isinstance(result, proto.Message):
95 response_payload = type(result).to_json(result)
96 elif isinstance(result, google.protobuf.message.Message):
97 response_payload = MessageToJson(result)
98 else:
99 response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
100 grpc_response = {
101 "payload": response_payload,
102 "metadata": metadata,
103 "status": "OK",
104 }
105 _LOGGER.debug(
106 f"Received response to rpc {client_call_details.method}.",
107 extra={
108 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorStatsService",
109 "rpcName": str(client_call_details.method),
110 "response": grpc_response,
111 "metadata": grpc_response["metadata"],
112 },
113 )
114 return response
115
116
117class ErrorStatsServiceGrpcAsyncIOTransport(ErrorStatsServiceTransport):
118 """gRPC AsyncIO backend transport for ErrorStatsService.
119
120 An API for retrieving and managing error statistics as well
121 as data for individual events.
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 list_group_stats(
336 self,
337 ) -> Callable[
338 [error_stats_service.ListGroupStatsRequest],
339 Awaitable[error_stats_service.ListGroupStatsResponse],
340 ]:
341 r"""Return a callable for the list group stats method over gRPC.
342
343 Lists the specified groups.
344
345 Returns:
346 Callable[[~.ListGroupStatsRequest],
347 Awaitable[~.ListGroupStatsResponse]]:
348 A function that, when called, will call the underlying RPC
349 on the server.
350 """
351 # Generate a "stub function" on-the-fly which will actually make
352 # the request.
353 # gRPC handles serialization and deserialization, so we just need
354 # to pass in the functions for each.
355 if "list_group_stats" not in self._stubs:
356 self._stubs["list_group_stats"] = self._logged_channel.unary_unary(
357 "/google.devtools.clouderrorreporting.v1beta1.ErrorStatsService/ListGroupStats",
358 request_serializer=error_stats_service.ListGroupStatsRequest.serialize,
359 response_deserializer=error_stats_service.ListGroupStatsResponse.deserialize,
360 )
361 return self._stubs["list_group_stats"]
362
363 @property
364 def list_events(
365 self,
366 ) -> Callable[
367 [error_stats_service.ListEventsRequest],
368 Awaitable[error_stats_service.ListEventsResponse],
369 ]:
370 r"""Return a callable for the list events method over gRPC.
371
372 Lists the specified events.
373
374 Returns:
375 Callable[[~.ListEventsRequest],
376 Awaitable[~.ListEventsResponse]]:
377 A function that, when called, will call the underlying RPC
378 on the server.
379 """
380 # Generate a "stub function" on-the-fly which will actually make
381 # the request.
382 # gRPC handles serialization and deserialization, so we just need
383 # to pass in the functions for each.
384 if "list_events" not in self._stubs:
385 self._stubs["list_events"] = self._logged_channel.unary_unary(
386 "/google.devtools.clouderrorreporting.v1beta1.ErrorStatsService/ListEvents",
387 request_serializer=error_stats_service.ListEventsRequest.serialize,
388 response_deserializer=error_stats_service.ListEventsResponse.deserialize,
389 )
390 return self._stubs["list_events"]
391
392 @property
393 def delete_events(
394 self,
395 ) -> Callable[
396 [error_stats_service.DeleteEventsRequest],
397 Awaitable[error_stats_service.DeleteEventsResponse],
398 ]:
399 r"""Return a callable for the delete events method over gRPC.
400
401 Deletes all error events of a given project.
402
403 Returns:
404 Callable[[~.DeleteEventsRequest],
405 Awaitable[~.DeleteEventsResponse]]:
406 A function that, when called, will call the underlying RPC
407 on the server.
408 """
409 # Generate a "stub function" on-the-fly which will actually make
410 # the request.
411 # gRPC handles serialization and deserialization, so we just need
412 # to pass in the functions for each.
413 if "delete_events" not in self._stubs:
414 self._stubs["delete_events"] = self._logged_channel.unary_unary(
415 "/google.devtools.clouderrorreporting.v1beta1.ErrorStatsService/DeleteEvents",
416 request_serializer=error_stats_service.DeleteEventsRequest.serialize,
417 response_deserializer=error_stats_service.DeleteEventsResponse.deserialize,
418 )
419 return self._stubs["delete_events"]
420
421 def _prep_wrapped_messages(self, client_info):
422 """Precompute the wrapped methods, overriding the base class method to use async wrappers."""
423 self._wrapped_methods = {
424 self.list_group_stats: self._wrap_method(
425 self.list_group_stats,
426 default_timeout=None,
427 client_info=client_info,
428 ),
429 self.list_events: self._wrap_method(
430 self.list_events,
431 default_timeout=None,
432 client_info=client_info,
433 ),
434 self.delete_events: self._wrap_method(
435 self.delete_events,
436 default_timeout=None,
437 client_info=client_info,
438 ),
439 }
440
441 def _wrap_method(self, func, *args, **kwargs):
442 if self._wrap_with_kind: # pragma: NO COVER
443 kwargs["kind"] = self.kind
444 return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
445
446 def close(self):
447 return self._logged_channel.close()
448
449 @property
450 def kind(self) -> str:
451 return "grpc_asyncio"
452
453
454__all__ = ("ErrorStatsServiceGrpcAsyncIOTransport",)