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 json
17import logging as std_logging
18import pickle
19import warnings
20from typing import Callable, Dict, Optional, Sequence, Tuple, Union
21
22from google.api_core import grpc_helpers
23from google.api_core import gapic_v1
24import google.auth # type: ignore
25from google.auth import credentials as ga_credentials # type: ignore
26from google.auth.transport.grpc import SslCredentials # type: ignore
27from google.protobuf.json_format import MessageToJson
28import google.protobuf.message
29
30import grpc # type: ignore
31import proto # type: ignore
32
33from google.cloud.errorreporting_v1beta1.types import report_errors_service
34from .base import ReportErrorsServiceTransport, DEFAULT_CLIENT_INFO
35
36try:
37 from google.api_core import client_logging # type: ignore
38
39 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
40except ImportError: # pragma: NO COVER
41 CLIENT_LOGGING_SUPPORTED = False
42
43_LOGGER = std_logging.getLogger(__name__)
44
45
46class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
47 def intercept_unary_unary(self, continuation, client_call_details, request):
48 logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
49 std_logging.DEBUG
50 )
51 if logging_enabled: # pragma: NO COVER
52 request_metadata = client_call_details.metadata
53 if isinstance(request, proto.Message):
54 request_payload = type(request).to_json(request)
55 elif isinstance(request, google.protobuf.message.Message):
56 request_payload = MessageToJson(request)
57 else:
58 request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
59
60 request_metadata = {
61 key: value.decode("utf-8") if isinstance(value, bytes) else value
62 for key, value in request_metadata
63 }
64 grpc_request = {
65 "payload": request_payload,
66 "requestMethod": "grpc",
67 "metadata": dict(request_metadata),
68 }
69 _LOGGER.debug(
70 f"Sending request for {client_call_details.method}",
71 extra={
72 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ReportErrorsService",
73 "rpcName": str(client_call_details.method),
74 "request": grpc_request,
75 "metadata": grpc_request["metadata"],
76 },
77 )
78 response = continuation(client_call_details, request)
79 if logging_enabled: # pragma: NO COVER
80 response_metadata = response.trailing_metadata()
81 # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
82 metadata = (
83 dict([(k, str(v)) for k, v in response_metadata])
84 if response_metadata
85 else None
86 )
87 result = response.result()
88 if isinstance(result, proto.Message):
89 response_payload = type(result).to_json(result)
90 elif isinstance(result, google.protobuf.message.Message):
91 response_payload = MessageToJson(result)
92 else:
93 response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
94 grpc_response = {
95 "payload": response_payload,
96 "metadata": metadata,
97 "status": "OK",
98 }
99 _LOGGER.debug(
100 f"Received response for {client_call_details.method}.",
101 extra={
102 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ReportErrorsService",
103 "rpcName": client_call_details.method,
104 "response": grpc_response,
105 "metadata": grpc_response["metadata"],
106 },
107 )
108 return response
109
110
111class ReportErrorsServiceGrpcTransport(ReportErrorsServiceTransport):
112 """gRPC backend transport for ReportErrorsService.
113
114 An API for reporting error events.
115
116 This class defines the same methods as the primary client, so the
117 primary client can load the underlying transport implementation
118 and call it.
119
120 It sends protocol buffers over the wire using gRPC (which is built on
121 top of HTTP/2); the ``grpcio`` package must be installed.
122 """
123
124 _stubs: Dict[str, Callable]
125
126 def __init__(
127 self,
128 *,
129 host: str = "clouderrorreporting.googleapis.com",
130 credentials: Optional[ga_credentials.Credentials] = None,
131 credentials_file: Optional[str] = None,
132 scopes: Optional[Sequence[str]] = None,
133 channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
134 api_mtls_endpoint: Optional[str] = None,
135 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
136 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
137 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
138 quota_project_id: Optional[str] = None,
139 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
140 always_use_jwt_access: Optional[bool] = False,
141 api_audience: Optional[str] = None,
142 ) -> None:
143 """Instantiate the transport.
144
145 Args:
146 host (Optional[str]):
147 The hostname to connect to (default: 'clouderrorreporting.googleapis.com').
148 credentials (Optional[google.auth.credentials.Credentials]): The
149 authorization credentials to attach to requests. These
150 credentials identify the application to the service; if none
151 are specified, the client will attempt to ascertain the
152 credentials from the environment.
153 This argument is ignored if a ``channel`` instance is provided.
154 credentials_file (Optional[str]): Deprecated. A file with credentials that can
155 be loaded with :func:`google.auth.load_credentials_from_file`.
156 This argument is ignored if a ``channel`` instance is provided.
157 This argument will be removed in the next major version of this library.
158 scopes (Optional(Sequence[str])): A list of scopes. This argument is
159 ignored if a ``channel`` instance is provided.
160 channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
161 A ``Channel`` instance through which to make calls, or a Callable
162 that constructs and returns one. If set to None, ``self.create_channel``
163 is used to create the channel. If a Callable is given, it will be called
164 with the same arguments as used in ``self.create_channel``.
165 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
166 If provided, it overrides the ``host`` argument and tries to create
167 a mutual TLS channel with client SSL credentials from
168 ``client_cert_source`` or application default SSL credentials.
169 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
170 Deprecated. A callback to provide client SSL certificate bytes and
171 private key bytes, both in PEM format. It is ignored if
172 ``api_mtls_endpoint`` is None.
173 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
174 for the grpc channel. It is ignored if a ``channel`` instance is provided.
175 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
176 A callback to provide client certificate bytes and private key bytes,
177 both in PEM format. It is used to configure a mutual TLS channel. It is
178 ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
179 quota_project_id (Optional[str]): An optional project to use for billing
180 and quota.
181 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
182 The client info used to send a user-agent string along with
183 API requests. If ``None``, then default info will be used.
184 Generally, you only need to set this if you're developing
185 your own client library.
186 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
187 be used for service account credentials.
188
189 Raises:
190 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
191 creation failed for any reason.
192 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
193 and ``credentials_file`` are passed.
194 """
195 self._grpc_channel = None
196 self._ssl_channel_credentials = ssl_channel_credentials
197 self._stubs: Dict[str, Callable] = {}
198
199 if api_mtls_endpoint:
200 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
201 if client_cert_source:
202 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
203
204 if isinstance(channel, grpc.Channel):
205 # Ignore credentials if a channel was passed.
206 credentials = None
207 self._ignore_credentials = True
208 # If a channel was explicitly provided, set it.
209 self._grpc_channel = channel
210 self._ssl_channel_credentials = None
211
212 else:
213 if api_mtls_endpoint:
214 host = api_mtls_endpoint
215
216 # Create SSL credentials with client_cert_source or application
217 # default SSL credentials.
218 if client_cert_source:
219 cert, key = client_cert_source()
220 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
221 certificate_chain=cert, private_key=key
222 )
223 else:
224 self._ssl_channel_credentials = SslCredentials().ssl_credentials
225
226 else:
227 if client_cert_source_for_mtls and not ssl_channel_credentials:
228 cert, key = client_cert_source_for_mtls()
229 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
230 certificate_chain=cert, private_key=key
231 )
232
233 # The base transport sets the host, credentials and scopes
234 super().__init__(
235 host=host,
236 credentials=credentials,
237 credentials_file=credentials_file,
238 scopes=scopes,
239 quota_project_id=quota_project_id,
240 client_info=client_info,
241 always_use_jwt_access=always_use_jwt_access,
242 api_audience=api_audience,
243 )
244
245 if not self._grpc_channel:
246 # initialize with the provided callable or the default channel
247 channel_init = channel or type(self).create_channel
248 self._grpc_channel = channel_init(
249 self._host,
250 # use the credentials which are saved
251 credentials=self._credentials,
252 # Set ``credentials_file`` to ``None`` here as
253 # the credentials that we saved earlier should be used.
254 credentials_file=None,
255 scopes=self._scopes,
256 ssl_credentials=self._ssl_channel_credentials,
257 quota_project_id=quota_project_id,
258 options=[
259 ("grpc.max_send_message_length", -1),
260 ("grpc.max_receive_message_length", -1),
261 ],
262 )
263
264 self._interceptor = _LoggingClientInterceptor()
265 self._logged_channel = grpc.intercept_channel(
266 self._grpc_channel, self._interceptor
267 )
268
269 # Wrap messages. This must be done after self._logged_channel exists
270 self._prep_wrapped_messages(client_info)
271
272 @classmethod
273 def create_channel(
274 cls,
275 host: str = "clouderrorreporting.googleapis.com",
276 credentials: Optional[ga_credentials.Credentials] = None,
277 credentials_file: Optional[str] = None,
278 scopes: Optional[Sequence[str]] = None,
279 quota_project_id: Optional[str] = None,
280 **kwargs,
281 ) -> grpc.Channel:
282 """Create and return a gRPC channel object.
283 Args:
284 host (Optional[str]): The host for the channel to use.
285 credentials (Optional[~.Credentials]): The
286 authorization credentials to attach to requests. These
287 credentials identify this application to the service. If
288 none are specified, the client will attempt to ascertain
289 the credentials from the environment.
290 credentials_file (Optional[str]): Deprecated. A file with credentials that can
291 be loaded with :func:`google.auth.load_credentials_from_file`.
292 This argument is mutually exclusive with credentials. This argument will be
293 removed in the next major version of this library.
294 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
295 service. These are only used when credentials are not specified and
296 are passed to :func:`google.auth.default`.
297 quota_project_id (Optional[str]): An optional project to use for billing
298 and quota.
299 kwargs (Optional[dict]): Keyword arguments, which are passed to the
300 channel creation.
301 Returns:
302 grpc.Channel: A gRPC channel object.
303
304 Raises:
305 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
306 and ``credentials_file`` are passed.
307 """
308
309 return grpc_helpers.create_channel(
310 host,
311 credentials=credentials,
312 credentials_file=credentials_file,
313 quota_project_id=quota_project_id,
314 default_scopes=cls.AUTH_SCOPES,
315 scopes=scopes,
316 default_host=cls.DEFAULT_HOST,
317 **kwargs,
318 )
319
320 @property
321 def grpc_channel(self) -> grpc.Channel:
322 """Return the channel designed to connect to this service."""
323 return self._grpc_channel
324
325 @property
326 def report_error_event(
327 self,
328 ) -> Callable[
329 [report_errors_service.ReportErrorEventRequest],
330 report_errors_service.ReportErrorEventResponse,
331 ]:
332 r"""Return a callable for the report error event method over gRPC.
333
334 Report an individual error event and record the event to a log.
335
336 This endpoint accepts **either** an OAuth token, **or** an `API
337 key <https://support.google.com/cloud/answer/6158862>`__ for
338 authentication. To use an API key, append it to the URL as the
339 value of a ``key`` parameter. For example:
340
341 ``POST https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456``
342
343 **Note:** [Error Reporting]
344 (https://cloud.google.com/error-reporting) is a service built on
345 Cloud Logging and can analyze log entries when all of the
346 following are true:
347
348 - Customer-managed encryption keys (CMEK) are disabled on the
349 log bucket.
350 - The log bucket satisfies one of the following:
351
352 - The log bucket is stored in the same project where the logs
353 originated.
354 - The logs were routed to a project, and then that project
355 stored those logs in a log bucket that it owns.
356
357 Returns:
358 Callable[[~.ReportErrorEventRequest],
359 ~.ReportErrorEventResponse]:
360 A function that, when called, will call the underlying RPC
361 on the server.
362 """
363 # Generate a "stub function" on-the-fly which will actually make
364 # the request.
365 # gRPC handles serialization and deserialization, so we just need
366 # to pass in the functions for each.
367 if "report_error_event" not in self._stubs:
368 self._stubs["report_error_event"] = self._logged_channel.unary_unary(
369 "/google.devtools.clouderrorreporting.v1beta1.ReportErrorsService/ReportErrorEvent",
370 request_serializer=report_errors_service.ReportErrorEventRequest.serialize,
371 response_deserializer=report_errors_service.ReportErrorEventResponse.deserialize,
372 )
373 return self._stubs["report_error_event"]
374
375 def close(self):
376 self._logged_channel.close()
377
378 @property
379 def kind(self) -> str:
380 return "grpc"
381
382
383__all__ = ("ReportErrorsServiceGrpcTransport",)