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 common
49from google.cloud.errorreporting_v1beta1.types import error_group_service
50from .transports.base import ErrorGroupServiceTransport, DEFAULT_CLIENT_INFO
51from .transports.grpc_asyncio import ErrorGroupServiceGrpcAsyncIOTransport
52from .client import ErrorGroupServiceClient
53
54try:
55 from google.api_core import client_logging # type: ignore
56
57 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
58except ImportError: # pragma: NO COVER
59 CLIENT_LOGGING_SUPPORTED = False
60
61_LOGGER = std_logging.getLogger(__name__)
62
63
64class ErrorGroupServiceAsyncClient:
65 """Service for retrieving and updating individual error groups."""
66
67 _client: ErrorGroupServiceClient
68
69 # Copy defaults from the synchronous client for use here.
70 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
71 DEFAULT_ENDPOINT = ErrorGroupServiceClient.DEFAULT_ENDPOINT
72 DEFAULT_MTLS_ENDPOINT = ErrorGroupServiceClient.DEFAULT_MTLS_ENDPOINT
73 _DEFAULT_ENDPOINT_TEMPLATE = ErrorGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE
74 _DEFAULT_UNIVERSE = ErrorGroupServiceClient._DEFAULT_UNIVERSE
75
76 error_group_path = staticmethod(ErrorGroupServiceClient.error_group_path)
77 parse_error_group_path = staticmethod(
78 ErrorGroupServiceClient.parse_error_group_path
79 )
80 common_billing_account_path = staticmethod(
81 ErrorGroupServiceClient.common_billing_account_path
82 )
83 parse_common_billing_account_path = staticmethod(
84 ErrorGroupServiceClient.parse_common_billing_account_path
85 )
86 common_folder_path = staticmethod(ErrorGroupServiceClient.common_folder_path)
87 parse_common_folder_path = staticmethod(
88 ErrorGroupServiceClient.parse_common_folder_path
89 )
90 common_organization_path = staticmethod(
91 ErrorGroupServiceClient.common_organization_path
92 )
93 parse_common_organization_path = staticmethod(
94 ErrorGroupServiceClient.parse_common_organization_path
95 )
96 common_project_path = staticmethod(ErrorGroupServiceClient.common_project_path)
97 parse_common_project_path = staticmethod(
98 ErrorGroupServiceClient.parse_common_project_path
99 )
100 common_location_path = staticmethod(ErrorGroupServiceClient.common_location_path)
101 parse_common_location_path = staticmethod(
102 ErrorGroupServiceClient.parse_common_location_path
103 )
104
105 @classmethod
106 def from_service_account_info(cls, info: dict, *args, **kwargs):
107 """Creates an instance of this client using the provided credentials
108 info.
109
110 Args:
111 info (dict): The service account private key info.
112 args: Additional arguments to pass to the constructor.
113 kwargs: Additional arguments to pass to the constructor.
114
115 Returns:
116 ErrorGroupServiceAsyncClient: The constructed client.
117 """
118 return ErrorGroupServiceClient.from_service_account_info.__func__(ErrorGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore
119
120 @classmethod
121 def from_service_account_file(cls, filename: str, *args, **kwargs):
122 """Creates an instance of this client using the provided credentials
123 file.
124
125 Args:
126 filename (str): The path to the service account private key json
127 file.
128 args: Additional arguments to pass to the constructor.
129 kwargs: Additional arguments to pass to the constructor.
130
131 Returns:
132 ErrorGroupServiceAsyncClient: The constructed client.
133 """
134 return ErrorGroupServiceClient.from_service_account_file.__func__(ErrorGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore
135
136 from_service_account_json = from_service_account_file
137
138 @classmethod
139 def get_mtls_endpoint_and_cert_source(
140 cls, client_options: Optional[ClientOptions] = None
141 ):
142 """Return the API endpoint and client cert source for mutual TLS.
143
144 The client cert source is determined in the following order:
145 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
146 client cert source is None.
147 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
148 default client cert source exists, use the default one; otherwise the client cert
149 source is None.
150
151 The API endpoint is determined in the following order:
152 (1) if `client_options.api_endpoint` if provided, use the provided one.
153 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
154 default mTLS endpoint; if the environment variable is "never", use the default API
155 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
156 use the default API endpoint.
157
158 More details can be found at https://google.aip.dev/auth/4114.
159
160 Args:
161 client_options (google.api_core.client_options.ClientOptions): Custom options for the
162 client. Only the `api_endpoint` and `client_cert_source` properties may be used
163 in this method.
164
165 Returns:
166 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
167 client cert source to use.
168
169 Raises:
170 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
171 """
172 return ErrorGroupServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
173
174 @property
175 def transport(self) -> ErrorGroupServiceTransport:
176 """Returns the transport used by the client instance.
177
178 Returns:
179 ErrorGroupServiceTransport: The transport used by the client instance.
180 """
181 return self._client.transport
182
183 @property
184 def api_endpoint(self):
185 """Return the API endpoint used by the client instance.
186
187 Returns:
188 str: The API endpoint used by the client instance.
189 """
190 return self._client._api_endpoint
191
192 @property
193 def universe_domain(self) -> str:
194 """Return the universe domain used by the client instance.
195
196 Returns:
197 str: The universe domain used
198 by the client instance.
199 """
200 return self._client._universe_domain
201
202 get_transport_class = ErrorGroupServiceClient.get_transport_class
203
204 def __init__(
205 self,
206 *,
207 credentials: Optional[ga_credentials.Credentials] = None,
208 transport: Optional[
209 Union[
210 str,
211 ErrorGroupServiceTransport,
212 Callable[..., ErrorGroupServiceTransport],
213 ]
214 ] = "grpc_asyncio",
215 client_options: Optional[ClientOptions] = None,
216 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
217 ) -> None:
218 """Instantiates the error group service async client.
219
220 Args:
221 credentials (Optional[google.auth.credentials.Credentials]): The
222 authorization credentials to attach to requests. These
223 credentials identify the application to the service; if none
224 are specified, the client will attempt to ascertain the
225 credentials from the environment.
226 transport (Optional[Union[str,ErrorGroupServiceTransport,Callable[..., ErrorGroupServiceTransport]]]):
227 The transport to use, or a Callable that constructs and returns a new transport to use.
228 If a Callable is given, it will be called with the same set of initialization
229 arguments as used in the ErrorGroupServiceTransport constructor.
230 If set to None, a transport is chosen automatically.
231 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
232 Custom options for the client.
233
234 1. The ``api_endpoint`` property can be used to override the
235 default endpoint provided by the client when ``transport`` is
236 not explicitly provided. Only if this property is not set and
237 ``transport`` was not explicitly provided, the endpoint is
238 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
239 variable, which have one of the following values:
240 "always" (always use the default mTLS endpoint), "never" (always
241 use the default regular endpoint) and "auto" (auto-switch to the
242 default mTLS endpoint if client certificate is present; this is
243 the default value).
244
245 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
246 is "true", then the ``client_cert_source`` property can be used
247 to provide a client certificate for mTLS transport. If
248 not provided, the default SSL client certificate will be used if
249 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
250 set, no client certificate will be used.
251
252 3. The ``universe_domain`` property can be used to override the
253 default "googleapis.com" universe. Note that ``api_endpoint``
254 property still takes precedence; and ``universe_domain`` is
255 currently not supported for mTLS.
256
257 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
258 The client info used to send a user-agent string along with
259 API requests. If ``None``, then default info will be used.
260 Generally, you only need to set this if you're developing
261 your own client library.
262
263 Raises:
264 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
265 creation failed for any reason.
266 """
267 self._client = ErrorGroupServiceClient(
268 credentials=credentials,
269 transport=transport,
270 client_options=client_options,
271 client_info=client_info,
272 )
273
274 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
275 std_logging.DEBUG
276 ): # pragma: NO COVER
277 _LOGGER.debug(
278 "Created client `google.devtools.clouderrorreporting_v1beta1.ErrorGroupServiceAsyncClient`.",
279 extra={
280 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService",
281 "universeDomain": getattr(
282 self._client._transport._credentials, "universe_domain", ""
283 ),
284 "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
285 "credentialsInfo": getattr(
286 self.transport._credentials, "get_cred_info", lambda: None
287 )(),
288 }
289 if hasattr(self._client._transport, "_credentials")
290 else {
291 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService",
292 "credentialsType": None,
293 },
294 )
295
296 async def get_group(
297 self,
298 request: Optional[Union[error_group_service.GetGroupRequest, dict]] = None,
299 *,
300 group_name: Optional[str] = None,
301 retry: OptionalRetry = gapic_v1.method.DEFAULT,
302 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
303 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
304 ) -> common.ErrorGroup:
305 r"""Get the specified group.
306
307 .. code-block:: python
308
309 # This snippet has been automatically generated and should be regarded as a
310 # code template only.
311 # It will require modifications to work:
312 # - It may require correct/in-range values for request initialization.
313 # - It may require specifying regional endpoints when creating the service
314 # client as shown in:
315 # https://googleapis.dev/python/google-api-core/latest/client_options.html
316 from google.cloud import errorreporting_v1beta1
317
318 async def sample_get_group():
319 # Create a client
320 client = errorreporting_v1beta1.ErrorGroupServiceAsyncClient()
321
322 # Initialize request argument(s)
323 request = errorreporting_v1beta1.GetGroupRequest(
324 group_name="group_name_value",
325 )
326
327 # Make the request
328 response = await client.get_group(request=request)
329
330 # Handle the response
331 print(response)
332
333 Args:
334 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.GetGroupRequest, dict]]):
335 The request object. A request to return an individual
336 group.
337 group_name (:class:`str`):
338 Required. The group resource name. Written as either
339 ``projects/{projectID}/groups/{group_id}`` or
340 ``projects/{projectID}/locations/{location}/groups/{group_id}``.
341 Call [groupStats.list]
342 [google.devtools.clouderrorreporting.v1beta1.ErrorStatsService.ListGroupStats]
343 to return a list of groups belonging to this project.
344
345 Examples: ``projects/my-project-123/groups/my-group``,
346 ``projects/my-project-123/locations/global/groups/my-group``
347
348 In the group resource name, the ``group_id`` is a unique
349 identifier for a particular error group. The identifier
350 is derived from key parts of the error-log content and
351 is treated as Service Data. For information about how
352 Service Data is handled, see `Google Cloud Privacy
353 Notice <https://cloud.google.com/terms/cloud-privacy-notice>`__.
354
355 For a list of supported locations, see `Supported
356 Regions <https://cloud.google.com/logging/docs/region-support>`__.
357 ``global`` is the default when unspecified.
358
359 This corresponds to the ``group_name`` field
360 on the ``request`` instance; if ``request`` is provided, this
361 should not be set.
362 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
363 should be retried.
364 timeout (float): The timeout for this request.
365 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
366 sent along with the request as metadata. Normally, each value must be of type `str`,
367 but for metadata keys ending with the suffix `-bin`, the corresponding values must
368 be of type `bytes`.
369
370 Returns:
371 google.cloud.errorreporting_v1beta1.types.ErrorGroup:
372 Description of a group of similar
373 error events.
374
375 """
376 # Create or coerce a protobuf request object.
377 # - Quick check: If we got a request object, we should *not* have
378 # gotten any keyword arguments that map to the request.
379 flattened_params = [group_name]
380 has_flattened_params = (
381 len([param for param in flattened_params if param is not None]) > 0
382 )
383 if request is not None and has_flattened_params:
384 raise ValueError(
385 "If the `request` argument is set, then none of "
386 "the individual field arguments should be set."
387 )
388
389 # - Use the request object if provided (there's no risk of modifying the input as
390 # there are no flattened fields), or create one.
391 if not isinstance(request, error_group_service.GetGroupRequest):
392 request = error_group_service.GetGroupRequest(request)
393
394 # If we have keyword arguments corresponding to fields on the
395 # request, apply these.
396 if group_name is not None:
397 request.group_name = group_name
398
399 # Wrap the RPC method; this adds retry and timeout information,
400 # and friendly error handling.
401 rpc = self._client._transport._wrapped_methods[
402 self._client._transport.get_group
403 ]
404
405 # Certain fields should be provided within the metadata header;
406 # add these here.
407 metadata = tuple(metadata) + (
408 gapic_v1.routing_header.to_grpc_metadata(
409 (("group_name", request.group_name),)
410 ),
411 )
412
413 # Validate the universe domain.
414 self._client._validate_universe_domain()
415
416 # Send the request.
417 response = await rpc(
418 request,
419 retry=retry,
420 timeout=timeout,
421 metadata=metadata,
422 )
423
424 # Done; return the response.
425 return response
426
427 async def update_group(
428 self,
429 request: Optional[Union[error_group_service.UpdateGroupRequest, dict]] = None,
430 *,
431 group: Optional[common.ErrorGroup] = None,
432 retry: OptionalRetry = gapic_v1.method.DEFAULT,
433 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
434 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
435 ) -> common.ErrorGroup:
436 r"""Replace the data for the specified group.
437 Fails if the group does not exist.
438
439 .. code-block:: python
440
441 # This snippet has been automatically generated and should be regarded as a
442 # code template only.
443 # It will require modifications to work:
444 # - It may require correct/in-range values for request initialization.
445 # - It may require specifying regional endpoints when creating the service
446 # client as shown in:
447 # https://googleapis.dev/python/google-api-core/latest/client_options.html
448 from google.cloud import errorreporting_v1beta1
449
450 async def sample_update_group():
451 # Create a client
452 client = errorreporting_v1beta1.ErrorGroupServiceAsyncClient()
453
454 # Initialize request argument(s)
455 request = errorreporting_v1beta1.UpdateGroupRequest(
456 )
457
458 # Make the request
459 response = await client.update_group(request=request)
460
461 # Handle the response
462 print(response)
463
464 Args:
465 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.UpdateGroupRequest, dict]]):
466 The request object. A request to replace the existing
467 data for the given group.
468 group (:class:`google.cloud.errorreporting_v1beta1.types.ErrorGroup`):
469 Required. The group which replaces
470 the resource on the server.
471
472 This corresponds to the ``group`` field
473 on the ``request`` instance; if ``request`` is provided, this
474 should not be set.
475 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
476 should be retried.
477 timeout (float): The timeout for this request.
478 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
479 sent along with the request as metadata. Normally, each value must be of type `str`,
480 but for metadata keys ending with the suffix `-bin`, the corresponding values must
481 be of type `bytes`.
482
483 Returns:
484 google.cloud.errorreporting_v1beta1.types.ErrorGroup:
485 Description of a group of similar
486 error events.
487
488 """
489 # Create or coerce a protobuf request object.
490 # - Quick check: If we got a request object, we should *not* have
491 # gotten any keyword arguments that map to the request.
492 flattened_params = [group]
493 has_flattened_params = (
494 len([param for param in flattened_params if param is not None]) > 0
495 )
496 if request is not None and has_flattened_params:
497 raise ValueError(
498 "If the `request` argument is set, then none of "
499 "the individual field arguments should be set."
500 )
501
502 # - Use the request object if provided (there's no risk of modifying the input as
503 # there are no flattened fields), or create one.
504 if not isinstance(request, error_group_service.UpdateGroupRequest):
505 request = error_group_service.UpdateGroupRequest(request)
506
507 # If we have keyword arguments corresponding to fields on the
508 # request, apply these.
509 if group is not None:
510 request.group = group
511
512 # Wrap the RPC method; this adds retry and timeout information,
513 # and friendly error handling.
514 rpc = self._client._transport._wrapped_methods[
515 self._client._transport.update_group
516 ]
517
518 # Certain fields should be provided within the metadata header;
519 # add these here.
520 metadata = tuple(metadata) + (
521 gapic_v1.routing_header.to_grpc_metadata(
522 (("group.name", request.group.name),)
523 ),
524 )
525
526 # Validate the universe domain.
527 self._client._validate_universe_domain()
528
529 # Send the request.
530 response = await rpc(
531 request,
532 retry=retry,
533 timeout=timeout,
534 metadata=metadata,
535 )
536
537 # Done; return the response.
538 return response
539
540 async def __aenter__(self) -> "ErrorGroupServiceAsyncClient":
541 return self
542
543 async def __aexit__(self, exc_type, exc, tb):
544 await self.transport.close()
545
546
547DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
548 gapic_version=package_version.__version__
549)
550
551if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
552 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
553
554
555__all__ = ("ErrorGroupServiceAsyncClient",)