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 logging as std_logging
17from collections import OrderedDict
18import re
19from typing import (
20 Dict,
21 Callable,
22 Mapping,
23 MutableMapping,
24 MutableSequence,
25 Optional,
26 Sequence,
27 Tuple,
28 Type,
29 Union,
30)
31
32from google.cloud.errorreporting_v1beta1 import gapic_version as package_version
33
34from google.api_core.client_options import ClientOptions
35from google.api_core import exceptions as core_exceptions
36from google.api_core import gapic_v1
37from google.api_core import retry_async as retries
38from google.auth import credentials as ga_credentials # type: ignore
39from google.oauth2 import service_account # type: ignore
40import google.protobuf
41
42
43try:
44 OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
45except AttributeError: # pragma: NO COVER
46 OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
47
48from google.cloud.errorreporting_v1beta1.types import report_errors_service
49from .transports.base import ReportErrorsServiceTransport, DEFAULT_CLIENT_INFO
50from .transports.grpc_asyncio import ReportErrorsServiceGrpcAsyncIOTransport
51from .client import ReportErrorsServiceClient
52
53try:
54 from google.api_core import client_logging # type: ignore
55
56 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
57except ImportError: # pragma: NO COVER
58 CLIENT_LOGGING_SUPPORTED = False
59
60_LOGGER = std_logging.getLogger(__name__)
61
62
63class ReportErrorsServiceAsyncClient:
64 """An API for reporting error events."""
65
66 _client: ReportErrorsServiceClient
67
68 # Copy defaults from the synchronous client for use here.
69 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
70 DEFAULT_ENDPOINT = ReportErrorsServiceClient.DEFAULT_ENDPOINT
71 DEFAULT_MTLS_ENDPOINT = ReportErrorsServiceClient.DEFAULT_MTLS_ENDPOINT
72 _DEFAULT_ENDPOINT_TEMPLATE = ReportErrorsServiceClient._DEFAULT_ENDPOINT_TEMPLATE
73 _DEFAULT_UNIVERSE = ReportErrorsServiceClient._DEFAULT_UNIVERSE
74
75 common_billing_account_path = staticmethod(
76 ReportErrorsServiceClient.common_billing_account_path
77 )
78 parse_common_billing_account_path = staticmethod(
79 ReportErrorsServiceClient.parse_common_billing_account_path
80 )
81 common_folder_path = staticmethod(ReportErrorsServiceClient.common_folder_path)
82 parse_common_folder_path = staticmethod(
83 ReportErrorsServiceClient.parse_common_folder_path
84 )
85 common_organization_path = staticmethod(
86 ReportErrorsServiceClient.common_organization_path
87 )
88 parse_common_organization_path = staticmethod(
89 ReportErrorsServiceClient.parse_common_organization_path
90 )
91 common_project_path = staticmethod(ReportErrorsServiceClient.common_project_path)
92 parse_common_project_path = staticmethod(
93 ReportErrorsServiceClient.parse_common_project_path
94 )
95 common_location_path = staticmethod(ReportErrorsServiceClient.common_location_path)
96 parse_common_location_path = staticmethod(
97 ReportErrorsServiceClient.parse_common_location_path
98 )
99
100 @classmethod
101 def from_service_account_info(cls, info: dict, *args, **kwargs):
102 """Creates an instance of this client using the provided credentials
103 info.
104
105 Args:
106 info (dict): The service account private key info.
107 args: Additional arguments to pass to the constructor.
108 kwargs: Additional arguments to pass to the constructor.
109
110 Returns:
111 ReportErrorsServiceAsyncClient: The constructed client.
112 """
113 return ReportErrorsServiceClient.from_service_account_info.__func__(ReportErrorsServiceAsyncClient, info, *args, **kwargs) # type: ignore
114
115 @classmethod
116 def from_service_account_file(cls, filename: str, *args, **kwargs):
117 """Creates an instance of this client using the provided credentials
118 file.
119
120 Args:
121 filename (str): The path to the service account private key json
122 file.
123 args: Additional arguments to pass to the constructor.
124 kwargs: Additional arguments to pass to the constructor.
125
126 Returns:
127 ReportErrorsServiceAsyncClient: The constructed client.
128 """
129 return ReportErrorsServiceClient.from_service_account_file.__func__(ReportErrorsServiceAsyncClient, filename, *args, **kwargs) # type: ignore
130
131 from_service_account_json = from_service_account_file
132
133 @classmethod
134 def get_mtls_endpoint_and_cert_source(
135 cls, client_options: Optional[ClientOptions] = None
136 ):
137 """Return the API endpoint and client cert source for mutual TLS.
138
139 The client cert source is determined in the following order:
140 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
141 client cert source is None.
142 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
143 default client cert source exists, use the default one; otherwise the client cert
144 source is None.
145
146 The API endpoint is determined in the following order:
147 (1) if `client_options.api_endpoint` if provided, use the provided one.
148 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
149 default mTLS endpoint; if the environment variable is "never", use the default API
150 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
151 use the default API endpoint.
152
153 More details can be found at https://google.aip.dev/auth/4114.
154
155 Args:
156 client_options (google.api_core.client_options.ClientOptions): Custom options for the
157 client. Only the `api_endpoint` and `client_cert_source` properties may be used
158 in this method.
159
160 Returns:
161 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
162 client cert source to use.
163
164 Raises:
165 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
166 """
167 return ReportErrorsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
168
169 @property
170 def transport(self) -> ReportErrorsServiceTransport:
171 """Returns the transport used by the client instance.
172
173 Returns:
174 ReportErrorsServiceTransport: The transport used by the client instance.
175 """
176 return self._client.transport
177
178 @property
179 def api_endpoint(self):
180 """Return the API endpoint used by the client instance.
181
182 Returns:
183 str: The API endpoint used by the client instance.
184 """
185 return self._client._api_endpoint
186
187 @property
188 def universe_domain(self) -> str:
189 """Return the universe domain used by the client instance.
190
191 Returns:
192 str: The universe domain used
193 by the client instance.
194 """
195 return self._client._universe_domain
196
197 get_transport_class = ReportErrorsServiceClient.get_transport_class
198
199 def __init__(
200 self,
201 *,
202 credentials: Optional[ga_credentials.Credentials] = None,
203 transport: Optional[
204 Union[
205 str,
206 ReportErrorsServiceTransport,
207 Callable[..., ReportErrorsServiceTransport],
208 ]
209 ] = "grpc_asyncio",
210 client_options: Optional[ClientOptions] = None,
211 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
212 ) -> None:
213 """Instantiates the report errors service async client.
214
215 Args:
216 credentials (Optional[google.auth.credentials.Credentials]): The
217 authorization credentials to attach to requests. These
218 credentials identify the application to the service; if none
219 are specified, the client will attempt to ascertain the
220 credentials from the environment.
221 transport (Optional[Union[str,ReportErrorsServiceTransport,Callable[..., ReportErrorsServiceTransport]]]):
222 The transport to use, or a Callable that constructs and returns a new transport to use.
223 If a Callable is given, it will be called with the same set of initialization
224 arguments as used in the ReportErrorsServiceTransport constructor.
225 If set to None, a transport is chosen automatically.
226 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
227 Custom options for the client.
228
229 1. The ``api_endpoint`` property can be used to override the
230 default endpoint provided by the client when ``transport`` is
231 not explicitly provided. Only if this property is not set and
232 ``transport`` was not explicitly provided, the endpoint is
233 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
234 variable, which have one of the following values:
235 "always" (always use the default mTLS endpoint), "never" (always
236 use the default regular endpoint) and "auto" (auto-switch to the
237 default mTLS endpoint if client certificate is present; this is
238 the default value).
239
240 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
241 is "true", then the ``client_cert_source`` property can be used
242 to provide a client certificate for mTLS transport. If
243 not provided, the default SSL client certificate will be used if
244 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
245 set, no client certificate will be used.
246
247 3. The ``universe_domain`` property can be used to override the
248 default "googleapis.com" universe. Note that ``api_endpoint``
249 property still takes precedence; and ``universe_domain`` is
250 currently not supported for mTLS.
251
252 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
253 The client info used to send a user-agent string along with
254 API requests. If ``None``, then default info will be used.
255 Generally, you only need to set this if you're developing
256 your own client library.
257
258 Raises:
259 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
260 creation failed for any reason.
261 """
262 self._client = ReportErrorsServiceClient(
263 credentials=credentials,
264 transport=transport,
265 client_options=client_options,
266 client_info=client_info,
267 )
268
269 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
270 std_logging.DEBUG
271 ): # pragma: NO COVER
272 _LOGGER.debug(
273 "Created client `google.devtools.clouderrorreporting_v1beta1.ReportErrorsServiceAsyncClient`.",
274 extra={
275 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ReportErrorsService",
276 "universeDomain": getattr(
277 self._client._transport._credentials, "universe_domain", ""
278 ),
279 "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
280 "credentialsInfo": getattr(
281 self.transport._credentials, "get_cred_info", lambda: None
282 )(),
283 }
284 if hasattr(self._client._transport, "_credentials")
285 else {
286 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ReportErrorsService",
287 "credentialsType": None,
288 },
289 )
290
291 async def report_error_event(
292 self,
293 request: Optional[
294 Union[report_errors_service.ReportErrorEventRequest, dict]
295 ] = None,
296 *,
297 project_name: Optional[str] = None,
298 event: Optional[report_errors_service.ReportedErrorEvent] = None,
299 retry: OptionalRetry = gapic_v1.method.DEFAULT,
300 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
301 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
302 ) -> report_errors_service.ReportErrorEventResponse:
303 r"""Report an individual error event and record the event to a log.
304
305 This endpoint accepts **either** an OAuth token, **or** an `API
306 key <https://support.google.com/cloud/answer/6158862>`__ for
307 authentication. To use an API key, append it to the URL as the
308 value of a ``key`` parameter. For example:
309
310 ``POST https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456``
311
312 **Note:** [Error Reporting]
313 (https://cloud.google.com/error-reporting) is a service built on
314 Cloud Logging and can analyze log entries when all of the
315 following are true:
316
317 - Customer-managed encryption keys (CMEK) are disabled on the
318 log bucket.
319 - The log bucket satisfies one of the following:
320
321 - The log bucket is stored in the same project where the
322 logs originated.
323 - The logs were routed to a project, and then that project
324 stored those logs in a log bucket that it owns.
325
326 .. code-block:: python
327
328 # This snippet has been automatically generated and should be regarded as a
329 # code template only.
330 # It will require modifications to work:
331 # - It may require correct/in-range values for request initialization.
332 # - It may require specifying regional endpoints when creating the service
333 # client as shown in:
334 # https://googleapis.dev/python/google-api-core/latest/client_options.html
335 from google.cloud import errorreporting_v1beta1
336
337 async def sample_report_error_event():
338 # Create a client
339 client = errorreporting_v1beta1.ReportErrorsServiceAsyncClient()
340
341 # Initialize request argument(s)
342 event = errorreporting_v1beta1.ReportedErrorEvent()
343 event.message = "message_value"
344
345 request = errorreporting_v1beta1.ReportErrorEventRequest(
346 project_name="project_name_value",
347 event=event,
348 )
349
350 # Make the request
351 response = await client.report_error_event(request=request)
352
353 # Handle the response
354 print(response)
355
356 Args:
357 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.ReportErrorEventRequest, dict]]):
358 The request object. A request for reporting an individual
359 error event.
360 project_name (:class:`str`):
361 Required. The resource name of the Google Cloud Platform
362 project. Written as ``projects/{projectId}``, where
363 ``{projectId}`` is the `Google Cloud Platform project
364 ID <https://support.google.com/cloud/answer/6158840>`__.
365
366 Example: // ``projects/my-project-123``.
367
368 This corresponds to the ``project_name`` field
369 on the ``request`` instance; if ``request`` is provided, this
370 should not be set.
371 event (:class:`google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent`):
372 Required. The error event to be
373 reported.
374
375 This corresponds to the ``event`` field
376 on the ``request`` instance; if ``request`` is provided, this
377 should not be set.
378 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
379 should be retried.
380 timeout (float): The timeout for this request.
381 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
382 sent along with the request as metadata. Normally, each value must be of type `str`,
383 but for metadata keys ending with the suffix `-bin`, the corresponding values must
384 be of type `bytes`.
385
386 Returns:
387 google.cloud.errorreporting_v1beta1.types.ReportErrorEventResponse:
388 Response for reporting an individual
389 error event. Data may be added to this
390 message in the future.
391
392 """
393 # Create or coerce a protobuf request object.
394 # - Quick check: If we got a request object, we should *not* have
395 # gotten any keyword arguments that map to the request.
396 flattened_params = [project_name, event]
397 has_flattened_params = (
398 len([param for param in flattened_params if param is not None]) > 0
399 )
400 if request is not None and has_flattened_params:
401 raise ValueError(
402 "If the `request` argument is set, then none of "
403 "the individual field arguments should be set."
404 )
405
406 # - Use the request object if provided (there's no risk of modifying the input as
407 # there are no flattened fields), or create one.
408 if not isinstance(request, report_errors_service.ReportErrorEventRequest):
409 request = report_errors_service.ReportErrorEventRequest(request)
410
411 # If we have keyword arguments corresponding to fields on the
412 # request, apply these.
413 if project_name is not None:
414 request.project_name = project_name
415 if event is not None:
416 request.event = event
417
418 # Wrap the RPC method; this adds retry and timeout information,
419 # and friendly error handling.
420 rpc = self._client._transport._wrapped_methods[
421 self._client._transport.report_error_event
422 ]
423
424 # Certain fields should be provided within the metadata header;
425 # add these here.
426 metadata = tuple(metadata) + (
427 gapic_v1.routing_header.to_grpc_metadata(
428 (("project_name", request.project_name),)
429 ),
430 )
431
432 # Validate the universe domain.
433 self._client._validate_universe_domain()
434
435 # Send the request.
436 response = await rpc(
437 request,
438 retry=retry,
439 timeout=timeout,
440 metadata=metadata,
441 )
442
443 # Done; return the response.
444 return response
445
446 async def __aenter__(self) -> "ReportErrorsServiceAsyncClient":
447 return self
448
449 async def __aexit__(self, exc_type, exc, tb):
450 await self.transport.close()
451
452
453DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
454 gapic_version=package_version.__version__
455)
456
457if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
458 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
459
460
461__all__ = ("ReportErrorsServiceAsyncClient",)