1# -*- coding: utf-8 -*-
2# Copyright 2022 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#
16from collections import OrderedDict
17import functools
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 Sequence,
26 Tuple,
27 Type,
28 Union,
29)
30
31from google.cloud.errorreporting_v1beta1 import gapic_version as package_version
32
33from google.api_core.client_options import ClientOptions
34from google.api_core import exceptions as core_exceptions
35from google.api_core import gapic_v1
36from google.api_core import retry as retries
37from google.auth import credentials as ga_credentials # type: ignore
38from google.oauth2 import service_account # type: ignore
39
40try:
41 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
42except AttributeError: # pragma: NO COVER
43 OptionalRetry = Union[retries.Retry, object] # type: ignore
44
45from google.cloud.errorreporting_v1beta1.types import common
46from google.cloud.errorreporting_v1beta1.types import error_group_service
47from .transports.base import ErrorGroupServiceTransport, DEFAULT_CLIENT_INFO
48from .transports.grpc_asyncio import ErrorGroupServiceGrpcAsyncIOTransport
49from .client import ErrorGroupServiceClient
50
51
52class ErrorGroupServiceAsyncClient:
53 """Service for retrieving and updating individual error groups."""
54
55 _client: ErrorGroupServiceClient
56
57 DEFAULT_ENDPOINT = ErrorGroupServiceClient.DEFAULT_ENDPOINT
58 DEFAULT_MTLS_ENDPOINT = ErrorGroupServiceClient.DEFAULT_MTLS_ENDPOINT
59
60 error_group_path = staticmethod(ErrorGroupServiceClient.error_group_path)
61 parse_error_group_path = staticmethod(
62 ErrorGroupServiceClient.parse_error_group_path
63 )
64 common_billing_account_path = staticmethod(
65 ErrorGroupServiceClient.common_billing_account_path
66 )
67 parse_common_billing_account_path = staticmethod(
68 ErrorGroupServiceClient.parse_common_billing_account_path
69 )
70 common_folder_path = staticmethod(ErrorGroupServiceClient.common_folder_path)
71 parse_common_folder_path = staticmethod(
72 ErrorGroupServiceClient.parse_common_folder_path
73 )
74 common_organization_path = staticmethod(
75 ErrorGroupServiceClient.common_organization_path
76 )
77 parse_common_organization_path = staticmethod(
78 ErrorGroupServiceClient.parse_common_organization_path
79 )
80 common_project_path = staticmethod(ErrorGroupServiceClient.common_project_path)
81 parse_common_project_path = staticmethod(
82 ErrorGroupServiceClient.parse_common_project_path
83 )
84 common_location_path = staticmethod(ErrorGroupServiceClient.common_location_path)
85 parse_common_location_path = staticmethod(
86 ErrorGroupServiceClient.parse_common_location_path
87 )
88
89 @classmethod
90 def from_service_account_info(cls, info: dict, *args, **kwargs):
91 """Creates an instance of this client using the provided credentials
92 info.
93
94 Args:
95 info (dict): The service account private key info.
96 args: Additional arguments to pass to the constructor.
97 kwargs: Additional arguments to pass to the constructor.
98
99 Returns:
100 ErrorGroupServiceAsyncClient: The constructed client.
101 """
102 return ErrorGroupServiceClient.from_service_account_info.__func__(ErrorGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore
103
104 @classmethod
105 def from_service_account_file(cls, filename: str, *args, **kwargs):
106 """Creates an instance of this client using the provided credentials
107 file.
108
109 Args:
110 filename (str): The path to the service account private key json
111 file.
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_file.__func__(ErrorGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore
119
120 from_service_account_json = from_service_account_file
121
122 @classmethod
123 def get_mtls_endpoint_and_cert_source(
124 cls, client_options: Optional[ClientOptions] = None
125 ):
126 """Return the API endpoint and client cert source for mutual TLS.
127
128 The client cert source is determined in the following order:
129 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
130 client cert source is None.
131 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
132 default client cert source exists, use the default one; otherwise the client cert
133 source is None.
134
135 The API endpoint is determined in the following order:
136 (1) if `client_options.api_endpoint` if provided, use the provided one.
137 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
138 default mTLS endpoint; if the environment variable is "never", use the default API
139 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
140 use the default API endpoint.
141
142 More details can be found at https://google.aip.dev/auth/4114.
143
144 Args:
145 client_options (google.api_core.client_options.ClientOptions): Custom options for the
146 client. Only the `api_endpoint` and `client_cert_source` properties may be used
147 in this method.
148
149 Returns:
150 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
151 client cert source to use.
152
153 Raises:
154 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
155 """
156 return ErrorGroupServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
157
158 @property
159 def transport(self) -> ErrorGroupServiceTransport:
160 """Returns the transport used by the client instance.
161
162 Returns:
163 ErrorGroupServiceTransport: The transport used by the client instance.
164 """
165 return self._client.transport
166
167 get_transport_class = functools.partial(
168 type(ErrorGroupServiceClient).get_transport_class, type(ErrorGroupServiceClient)
169 )
170
171 def __init__(
172 self,
173 *,
174 credentials: Optional[ga_credentials.Credentials] = None,
175 transport: Union[str, ErrorGroupServiceTransport] = "grpc_asyncio",
176 client_options: Optional[ClientOptions] = None,
177 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
178 ) -> None:
179 """Instantiates the error group service client.
180
181 Args:
182 credentials (Optional[google.auth.credentials.Credentials]): The
183 authorization credentials to attach to requests. These
184 credentials identify the application to the service; if none
185 are specified, the client will attempt to ascertain the
186 credentials from the environment.
187 transport (Union[str, ~.ErrorGroupServiceTransport]): The
188 transport to use. If set to None, a transport is chosen
189 automatically.
190 client_options (ClientOptions): Custom options for the client. It
191 won't take effect if a ``transport`` instance is provided.
192 (1) The ``api_endpoint`` property can be used to override the
193 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
194 environment variable can also be used to override the endpoint:
195 "always" (always use the default mTLS endpoint), "never" (always
196 use the default regular endpoint) and "auto" (auto switch to the
197 default mTLS endpoint if client certificate is present, this is
198 the default value). However, the ``api_endpoint`` property takes
199 precedence if provided.
200 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
201 is "true", then the ``client_cert_source`` property can be used
202 to provide client certificate for mutual TLS transport. If
203 not provided, the default SSL client certificate will be used if
204 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
205 set, no client certificate will be used.
206
207 Raises:
208 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
209 creation failed for any reason.
210 """
211 self._client = ErrorGroupServiceClient(
212 credentials=credentials,
213 transport=transport,
214 client_options=client_options,
215 client_info=client_info,
216 )
217
218 async def get_group(
219 self,
220 request: Optional[Union[error_group_service.GetGroupRequest, dict]] = None,
221 *,
222 group_name: Optional[str] = None,
223 retry: OptionalRetry = gapic_v1.method.DEFAULT,
224 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
225 metadata: Sequence[Tuple[str, str]] = (),
226 ) -> common.ErrorGroup:
227 r"""Get the specified group.
228
229 .. code-block:: python
230
231 # This snippet has been automatically generated and should be regarded as a
232 # code template only.
233 # It will require modifications to work:
234 # - It may require correct/in-range values for request initialization.
235 # - It may require specifying regional endpoints when creating the service
236 # client as shown in:
237 # https://googleapis.dev/python/google-api-core/latest/client_options.html
238 from google.cloud import errorreporting_v1beta1
239
240 async def sample_get_group():
241 # Create a client
242 client = errorreporting_v1beta1.ErrorGroupServiceAsyncClient()
243
244 # Initialize request argument(s)
245 request = errorreporting_v1beta1.GetGroupRequest(
246 group_name="group_name_value",
247 )
248
249 # Make the request
250 response = await client.get_group(request=request)
251
252 # Handle the response
253 print(response)
254
255 Args:
256 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.GetGroupRequest, dict]]):
257 The request object. A request to return an individual
258 group.
259 group_name (:class:`str`):
260 Required. The group resource name. Written as
261 ``projects/{projectID}/groups/{group_name}``. Call
262 ```groupStats.list`` <https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.groupStats/list>`__
263 to return a list of groups belonging to this project.
264
265 Example: ``projects/my-project-123/groups/my-group``
266
267 This corresponds to the ``group_name`` field
268 on the ``request`` instance; if ``request`` is provided, this
269 should not be set.
270 retry (google.api_core.retry.Retry): Designation of what errors, if any,
271 should be retried.
272 timeout (float): The timeout for this request.
273 metadata (Sequence[Tuple[str, str]]): Strings which should be
274 sent along with the request as metadata.
275
276 Returns:
277 google.cloud.errorreporting_v1beta1.types.ErrorGroup:
278 Description of a group of similar
279 error events.
280
281 """
282 # Create or coerce a protobuf request object.
283 # Quick check: If we got a request object, we should *not* have
284 # gotten any keyword arguments that map to the request.
285 has_flattened_params = any([group_name])
286 if request is not None and has_flattened_params:
287 raise ValueError(
288 "If the `request` argument is set, then none of "
289 "the individual field arguments should be set."
290 )
291
292 request = error_group_service.GetGroupRequest(request)
293
294 # If we have keyword arguments corresponding to fields on the
295 # request, apply these.
296 if group_name is not None:
297 request.group_name = group_name
298
299 # Wrap the RPC method; this adds retry and timeout information,
300 # and friendly error handling.
301 rpc = gapic_v1.method_async.wrap_method(
302 self._client._transport.get_group,
303 default_timeout=None,
304 client_info=DEFAULT_CLIENT_INFO,
305 )
306
307 # Certain fields should be provided within the metadata header;
308 # add these here.
309 metadata = tuple(metadata) + (
310 gapic_v1.routing_header.to_grpc_metadata(
311 (("group_name", request.group_name),)
312 ),
313 )
314
315 # Send the request.
316 response = await rpc(
317 request,
318 retry=retry,
319 timeout=timeout,
320 metadata=metadata,
321 )
322
323 # Done; return the response.
324 return response
325
326 async def update_group(
327 self,
328 request: Optional[Union[error_group_service.UpdateGroupRequest, dict]] = None,
329 *,
330 group: Optional[common.ErrorGroup] = None,
331 retry: OptionalRetry = gapic_v1.method.DEFAULT,
332 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
333 metadata: Sequence[Tuple[str, str]] = (),
334 ) -> common.ErrorGroup:
335 r"""Replace the data for the specified group.
336 Fails if the group does not exist.
337
338 .. code-block:: python
339
340 # This snippet has been automatically generated and should be regarded as a
341 # code template only.
342 # It will require modifications to work:
343 # - It may require correct/in-range values for request initialization.
344 # - It may require specifying regional endpoints when creating the service
345 # client as shown in:
346 # https://googleapis.dev/python/google-api-core/latest/client_options.html
347 from google.cloud import errorreporting_v1beta1
348
349 async def sample_update_group():
350 # Create a client
351 client = errorreporting_v1beta1.ErrorGroupServiceAsyncClient()
352
353 # Initialize request argument(s)
354 request = errorreporting_v1beta1.UpdateGroupRequest(
355 )
356
357 # Make the request
358 response = await client.update_group(request=request)
359
360 # Handle the response
361 print(response)
362
363 Args:
364 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.UpdateGroupRequest, dict]]):
365 The request object. A request to replace the existing
366 data for the given group.
367 group (:class:`google.cloud.errorreporting_v1beta1.types.ErrorGroup`):
368 Required. The group which replaces
369 the resource on the server.
370
371 This corresponds to the ``group`` field
372 on the ``request`` instance; if ``request`` is provided, this
373 should not be set.
374 retry (google.api_core.retry.Retry): Designation of what errors, if any,
375 should be retried.
376 timeout (float): The timeout for this request.
377 metadata (Sequence[Tuple[str, str]]): Strings which should be
378 sent along with the request as metadata.
379
380 Returns:
381 google.cloud.errorreporting_v1beta1.types.ErrorGroup:
382 Description of a group of similar
383 error events.
384
385 """
386 # Create or coerce a protobuf request object.
387 # Quick check: If we got a request object, we should *not* have
388 # gotten any keyword arguments that map to the request.
389 has_flattened_params = any([group])
390 if request is not None and has_flattened_params:
391 raise ValueError(
392 "If the `request` argument is set, then none of "
393 "the individual field arguments should be set."
394 )
395
396 request = error_group_service.UpdateGroupRequest(request)
397
398 # If we have keyword arguments corresponding to fields on the
399 # request, apply these.
400 if group is not None:
401 request.group = group
402
403 # Wrap the RPC method; this adds retry and timeout information,
404 # and friendly error handling.
405 rpc = gapic_v1.method_async.wrap_method(
406 self._client._transport.update_group,
407 default_timeout=None,
408 client_info=DEFAULT_CLIENT_INFO,
409 )
410
411 # Certain fields should be provided within the metadata header;
412 # add these here.
413 metadata = tuple(metadata) + (
414 gapic_v1.routing_header.to_grpc_metadata(
415 (("group.name", request.group.name),)
416 ),
417 )
418
419 # Send the request.
420 response = await rpc(
421 request,
422 retry=retry,
423 timeout=timeout,
424 metadata=metadata,
425 )
426
427 # Done; return the response.
428 return response
429
430 async def __aenter__(self):
431 return self
432
433 async def __aexit__(self, exc_type, exc, tb):
434 await self.transport.close()
435
436
437DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
438 gapic_version=package_version.__version__
439)
440
441
442__all__ = ("ErrorGroupServiceAsyncClient",)