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 report_errors_service
37from .base import ReportErrorsServiceTransport, DEFAULT_CLIENT_INFO
38from .grpc import ReportErrorsServiceGrpcTransport
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.ReportErrorsService",
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.ReportErrorsService",
109 "rpcName": str(client_call_details.method),
110 "response": grpc_response,
111 "metadata": grpc_response["metadata"],
112 },
113 )
114 return response
115
116
117class ReportErrorsServiceGrpcAsyncIOTransport(ReportErrorsServiceTransport):
118 """gRPC AsyncIO backend transport for ReportErrorsService.
119
120 An API for reporting error events.
121
122 This class defines the same methods as the primary client, so the
123 primary client can load the underlying transport implementation
124 and call it.
125
126 It sends protocol buffers over the wire using gRPC (which is built on
127 top of HTTP/2); the ``grpcio`` package must be installed.
128 """
129
130 _grpc_channel: aio.Channel
131 _stubs: Dict[str, Callable] = {}
132
133 @classmethod
134 def create_channel(
135 cls,
136 host: str = "clouderrorreporting.googleapis.com",
137 credentials: Optional[ga_credentials.Credentials] = None,
138 credentials_file: Optional[str] = None,
139 scopes: Optional[Sequence[str]] = None,
140 quota_project_id: Optional[str] = None,
141 **kwargs,
142 ) -> aio.Channel:
143 """Create and return a gRPC AsyncIO channel object.
144 Args:
145 host (Optional[str]): The host for the channel to use.
146 credentials (Optional[~.Credentials]): The
147 authorization credentials to attach to requests. These
148 credentials identify this application to the service. If
149 none are specified, the client will attempt to ascertain
150 the credentials from the environment.
151 credentials_file (Optional[str]): Deprecated. A file with credentials that can
152 be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be
153 removed in the next major version of this library.
154 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
155 service. These are only used when credentials are not specified and
156 are passed to :func:`google.auth.default`.
157 quota_project_id (Optional[str]): An optional project to use for billing
158 and quota.
159 kwargs (Optional[dict]): Keyword arguments, which are passed to the
160 channel creation.
161 Returns:
162 aio.Channel: A gRPC AsyncIO channel object.
163 """
164
165 return grpc_helpers_async.create_channel(
166 host,
167 credentials=credentials,
168 credentials_file=credentials_file,
169 quota_project_id=quota_project_id,
170 default_scopes=cls.AUTH_SCOPES,
171 scopes=scopes,
172 default_host=cls.DEFAULT_HOST,
173 **kwargs,
174 )
175
176 def __init__(
177 self,
178 *,
179 host: str = "clouderrorreporting.googleapis.com",
180 credentials: Optional[ga_credentials.Credentials] = None,
181 credentials_file: Optional[str] = None,
182 scopes: Optional[Sequence[str]] = None,
183 channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
184 api_mtls_endpoint: Optional[str] = None,
185 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
186 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
187 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
188 quota_project_id: Optional[str] = None,
189 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
190 always_use_jwt_access: Optional[bool] = False,
191 api_audience: Optional[str] = None,
192 ) -> None:
193 """Instantiate the transport.
194
195 Args:
196 host (Optional[str]):
197 The hostname to connect to (default: 'clouderrorreporting.googleapis.com').
198 credentials (Optional[google.auth.credentials.Credentials]): The
199 authorization credentials to attach to requests. These
200 credentials identify the application to the service; if none
201 are specified, the client will attempt to ascertain the
202 credentials from the environment.
203 This argument is ignored if a ``channel`` instance is provided.
204 credentials_file (Optional[str]): Deprecated. A file with credentials that can
205 be loaded with :func:`google.auth.load_credentials_from_file`.
206 This argument is ignored if a ``channel`` instance is provided.
207 This argument will be removed in the next major version of this library.
208 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
209 service. These are only used when credentials are not specified and
210 are passed to :func:`google.auth.default`.
211 channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
212 A ``Channel`` instance through which to make calls, or a Callable
213 that constructs and returns one. If set to None, ``self.create_channel``
214 is used to create the channel. If a Callable is given, it will be called
215 with the same arguments as used in ``self.create_channel``.
216 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
217 If provided, it overrides the ``host`` argument and tries to create
218 a mutual TLS channel with client SSL credentials from
219 ``client_cert_source`` or application default SSL credentials.
220 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
221 Deprecated. A callback to provide client SSL certificate bytes and
222 private key bytes, both in PEM format. It is ignored if
223 ``api_mtls_endpoint`` is None.
224 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
225 for the grpc channel. It is ignored if a ``channel`` instance is provided.
226 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
227 A callback to provide client certificate bytes and private key bytes,
228 both in PEM format. It is used to configure a mutual TLS channel. It is
229 ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
230 quota_project_id (Optional[str]): An optional project to use for billing
231 and quota.
232 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
233 The client info used to send a user-agent string along with
234 API requests. If ``None``, then default info will be used.
235 Generally, you only need to set this if you're developing
236 your own client library.
237 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
238 be used for service account credentials.
239
240 Raises:
241 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
242 creation failed for any reason.
243 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
244 and ``credentials_file`` are passed.
245 """
246 self._grpc_channel = None
247 self._ssl_channel_credentials = ssl_channel_credentials
248 self._stubs: Dict[str, Callable] = {}
249
250 if api_mtls_endpoint:
251 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
252 if client_cert_source:
253 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
254
255 if isinstance(channel, aio.Channel):
256 # Ignore credentials if a channel was passed.
257 credentials = None
258 self._ignore_credentials = True
259 # If a channel was explicitly provided, set it.
260 self._grpc_channel = channel
261 self._ssl_channel_credentials = None
262 else:
263 if api_mtls_endpoint:
264 host = api_mtls_endpoint
265
266 # Create SSL credentials with client_cert_source or application
267 # default SSL credentials.
268 if client_cert_source:
269 cert, key = client_cert_source()
270 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
271 certificate_chain=cert, private_key=key
272 )
273 else:
274 self._ssl_channel_credentials = SslCredentials().ssl_credentials
275
276 else:
277 if client_cert_source_for_mtls and not ssl_channel_credentials:
278 cert, key = client_cert_source_for_mtls()
279 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
280 certificate_chain=cert, private_key=key
281 )
282
283 # The base transport sets the host, credentials and scopes
284 super().__init__(
285 host=host,
286 credentials=credentials,
287 credentials_file=credentials_file,
288 scopes=scopes,
289 quota_project_id=quota_project_id,
290 client_info=client_info,
291 always_use_jwt_access=always_use_jwt_access,
292 api_audience=api_audience,
293 )
294
295 if not self._grpc_channel:
296 # initialize with the provided callable or the default channel
297 channel_init = channel or type(self).create_channel
298 self._grpc_channel = channel_init(
299 self._host,
300 # use the credentials which are saved
301 credentials=self._credentials,
302 # Set ``credentials_file`` to ``None`` here as
303 # the credentials that we saved earlier should be used.
304 credentials_file=None,
305 scopes=self._scopes,
306 ssl_credentials=self._ssl_channel_credentials,
307 quota_project_id=quota_project_id,
308 options=[
309 ("grpc.max_send_message_length", -1),
310 ("grpc.max_receive_message_length", -1),
311 ],
312 )
313
314 self._interceptor = _LoggingClientAIOInterceptor()
315 self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
316 self._logged_channel = self._grpc_channel
317 self._wrap_with_kind = (
318 "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
319 )
320 # Wrap messages. This must be done after self._logged_channel exists
321 self._prep_wrapped_messages(client_info)
322
323 @property
324 def grpc_channel(self) -> aio.Channel:
325 """Create the channel designed to connect to this service.
326
327 This property caches on the instance; repeated calls return
328 the same channel.
329 """
330 # Return the channel from cache.
331 return self._grpc_channel
332
333 @property
334 def report_error_event(
335 self,
336 ) -> Callable[
337 [report_errors_service.ReportErrorEventRequest],
338 Awaitable[report_errors_service.ReportErrorEventResponse],
339 ]:
340 r"""Return a callable for the report error event method over gRPC.
341
342 Report an individual error event and record the event to a log.
343
344 This endpoint accepts **either** an OAuth token, **or** an `API
345 key <https://support.google.com/cloud/answer/6158862>`__ for
346 authentication. To use an API key, append it to the URL as the
347 value of a ``key`` parameter. For example:
348
349 ``POST https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456``
350
351 **Note:** [Error Reporting]
352 (https://cloud.google.com/error-reporting) is a service built on
353 Cloud Logging and can analyze log entries when all of the
354 following are true:
355
356 - Customer-managed encryption keys (CMEK) are disabled on the
357 log bucket.
358 - The log bucket satisfies one of the following:
359
360 - The log bucket is stored in the same project where the logs
361 originated.
362 - The logs were routed to a project, and then that project
363 stored those logs in a log bucket that it owns.
364
365 Returns:
366 Callable[[~.ReportErrorEventRequest],
367 Awaitable[~.ReportErrorEventResponse]]:
368 A function that, when called, will call the underlying RPC
369 on the server.
370 """
371 # Generate a "stub function" on-the-fly which will actually make
372 # the request.
373 # gRPC handles serialization and deserialization, so we just need
374 # to pass in the functions for each.
375 if "report_error_event" not in self._stubs:
376 self._stubs["report_error_event"] = self._logged_channel.unary_unary(
377 "/google.devtools.clouderrorreporting.v1beta1.ReportErrorsService/ReportErrorEvent",
378 request_serializer=report_errors_service.ReportErrorEventRequest.serialize,
379 response_deserializer=report_errors_service.ReportErrorEventResponse.deserialize,
380 )
381 return self._stubs["report_error_event"]
382
383 def _prep_wrapped_messages(self, client_info):
384 """Precompute the wrapped methods, overriding the base class method to use async wrappers."""
385 self._wrapped_methods = {
386 self.report_error_event: self._wrap_method(
387 self.report_error_event,
388 default_timeout=None,
389 client_info=client_info,
390 ),
391 }
392
393 def _wrap_method(self, func, *args, **kwargs):
394 if self._wrap_with_kind: # pragma: NO COVER
395 kwargs["kind"] = self.kind
396 return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
397
398 def close(self):
399 return self._logged_channel.close()
400
401 @property
402 def kind(self) -> str:
403 return "grpc_asyncio"
404
405
406__all__ = ("ReportErrorsServiceGrpcAsyncIOTransport",)