1# -*- coding: utf-8 -*-
2# Copyright 2023 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_async 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.AsyncRetry, gapic_v1.method._MethodDefault]
42except AttributeError: # pragma: NO COVER
43 OptionalRetry = Union[retries.AsyncRetry, object] # type: ignore
44
45from google.cloud.errorreporting_v1beta1.types import report_errors_service
46from .transports.base import ReportErrorsServiceTransport, DEFAULT_CLIENT_INFO
47from .transports.grpc_asyncio import ReportErrorsServiceGrpcAsyncIOTransport
48from .client import ReportErrorsServiceClient
49
50
51class ReportErrorsServiceAsyncClient:
52 """An API for reporting error events."""
53
54 _client: ReportErrorsServiceClient
55
56 DEFAULT_ENDPOINT = ReportErrorsServiceClient.DEFAULT_ENDPOINT
57 DEFAULT_MTLS_ENDPOINT = ReportErrorsServiceClient.DEFAULT_MTLS_ENDPOINT
58
59 common_billing_account_path = staticmethod(
60 ReportErrorsServiceClient.common_billing_account_path
61 )
62 parse_common_billing_account_path = staticmethod(
63 ReportErrorsServiceClient.parse_common_billing_account_path
64 )
65 common_folder_path = staticmethod(ReportErrorsServiceClient.common_folder_path)
66 parse_common_folder_path = staticmethod(
67 ReportErrorsServiceClient.parse_common_folder_path
68 )
69 common_organization_path = staticmethod(
70 ReportErrorsServiceClient.common_organization_path
71 )
72 parse_common_organization_path = staticmethod(
73 ReportErrorsServiceClient.parse_common_organization_path
74 )
75 common_project_path = staticmethod(ReportErrorsServiceClient.common_project_path)
76 parse_common_project_path = staticmethod(
77 ReportErrorsServiceClient.parse_common_project_path
78 )
79 common_location_path = staticmethod(ReportErrorsServiceClient.common_location_path)
80 parse_common_location_path = staticmethod(
81 ReportErrorsServiceClient.parse_common_location_path
82 )
83
84 @classmethod
85 def from_service_account_info(cls, info: dict, *args, **kwargs):
86 """Creates an instance of this client using the provided credentials
87 info.
88
89 Args:
90 info (dict): The service account private key info.
91 args: Additional arguments to pass to the constructor.
92 kwargs: Additional arguments to pass to the constructor.
93
94 Returns:
95 ReportErrorsServiceAsyncClient: The constructed client.
96 """
97 return ReportErrorsServiceClient.from_service_account_info.__func__(ReportErrorsServiceAsyncClient, info, *args, **kwargs) # type: ignore
98
99 @classmethod
100 def from_service_account_file(cls, filename: str, *args, **kwargs):
101 """Creates an instance of this client using the provided credentials
102 file.
103
104 Args:
105 filename (str): The path to the service account private key json
106 file.
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_file.__func__(ReportErrorsServiceAsyncClient, filename, *args, **kwargs) # type: ignore
114
115 from_service_account_json = from_service_account_file
116
117 @classmethod
118 def get_mtls_endpoint_and_cert_source(
119 cls, client_options: Optional[ClientOptions] = None
120 ):
121 """Return the API endpoint and client cert source for mutual TLS.
122
123 The client cert source is determined in the following order:
124 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
125 client cert source is None.
126 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
127 default client cert source exists, use the default one; otherwise the client cert
128 source is None.
129
130 The API endpoint is determined in the following order:
131 (1) if `client_options.api_endpoint` if provided, use the provided one.
132 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
133 default mTLS endpoint; if the environment variable is "never", use the default API
134 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
135 use the default API endpoint.
136
137 More details can be found at https://google.aip.dev/auth/4114.
138
139 Args:
140 client_options (google.api_core.client_options.ClientOptions): Custom options for the
141 client. Only the `api_endpoint` and `client_cert_source` properties may be used
142 in this method.
143
144 Returns:
145 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
146 client cert source to use.
147
148 Raises:
149 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
150 """
151 return ReportErrorsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
152
153 @property
154 def transport(self) -> ReportErrorsServiceTransport:
155 """Returns the transport used by the client instance.
156
157 Returns:
158 ReportErrorsServiceTransport: The transport used by the client instance.
159 """
160 return self._client.transport
161
162 get_transport_class = functools.partial(
163 type(ReportErrorsServiceClient).get_transport_class,
164 type(ReportErrorsServiceClient),
165 )
166
167 def __init__(
168 self,
169 *,
170 credentials: Optional[ga_credentials.Credentials] = None,
171 transport: Union[str, ReportErrorsServiceTransport] = "grpc_asyncio",
172 client_options: Optional[ClientOptions] = None,
173 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
174 ) -> None:
175 """Instantiates the report errors service client.
176
177 Args:
178 credentials (Optional[google.auth.credentials.Credentials]): The
179 authorization credentials to attach to requests. These
180 credentials identify the application to the service; if none
181 are specified, the client will attempt to ascertain the
182 credentials from the environment.
183 transport (Union[str, ~.ReportErrorsServiceTransport]): The
184 transport to use. If set to None, a transport is chosen
185 automatically.
186 client_options (ClientOptions): Custom options for the client. It
187 won't take effect if a ``transport`` instance is provided.
188 (1) The ``api_endpoint`` property can be used to override the
189 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
190 environment variable can also be used to override the endpoint:
191 "always" (always use the default mTLS endpoint), "never" (always
192 use the default regular endpoint) and "auto" (auto switch to the
193 default mTLS endpoint if client certificate is present, this is
194 the default value). However, the ``api_endpoint`` property takes
195 precedence if provided.
196 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
197 is "true", then the ``client_cert_source`` property can be used
198 to provide client certificate for mutual TLS transport. If
199 not provided, the default SSL client certificate will be used if
200 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
201 set, no client certificate will be used.
202
203 Raises:
204 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
205 creation failed for any reason.
206 """
207 self._client = ReportErrorsServiceClient(
208 credentials=credentials,
209 transport=transport,
210 client_options=client_options,
211 client_info=client_info,
212 )
213
214 async def report_error_event(
215 self,
216 request: Optional[
217 Union[report_errors_service.ReportErrorEventRequest, dict]
218 ] = None,
219 *,
220 project_name: Optional[str] = None,
221 event: Optional[report_errors_service.ReportedErrorEvent] = None,
222 retry: OptionalRetry = gapic_v1.method.DEFAULT,
223 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
224 metadata: Sequence[Tuple[str, str]] = (),
225 ) -> report_errors_service.ReportErrorEventResponse:
226 r"""Report an individual error event and record the event to a log.
227
228 This endpoint accepts **either** an OAuth token, **or** an `API
229 key <https://support.google.com/cloud/answer/6158862>`__ for
230 authentication. To use an API key, append it to the URL as the
231 value of a ``key`` parameter. For example:
232
233 ``POST https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456``
234
235 **Note:** `Error Reporting </error-reporting>`__ is a global
236 service built on Cloud Logging and doesn't analyze logs stored
237 in regional log buckets or logs routed to other Google Cloud
238 projects.
239
240 .. code-block:: python
241
242 # This snippet has been automatically generated and should be regarded as a
243 # code template only.
244 # It will require modifications to work:
245 # - It may require correct/in-range values for request initialization.
246 # - It may require specifying regional endpoints when creating the service
247 # client as shown in:
248 # https://googleapis.dev/python/google-api-core/latest/client_options.html
249 from google.cloud import errorreporting_v1beta1
250
251 async def sample_report_error_event():
252 # Create a client
253 client = errorreporting_v1beta1.ReportErrorsServiceAsyncClient()
254
255 # Initialize request argument(s)
256 event = errorreporting_v1beta1.ReportedErrorEvent()
257 event.message = "message_value"
258
259 request = errorreporting_v1beta1.ReportErrorEventRequest(
260 project_name="project_name_value",
261 event=event,
262 )
263
264 # Make the request
265 response = await client.report_error_event(request=request)
266
267 # Handle the response
268 print(response)
269
270 Args:
271 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.ReportErrorEventRequest, dict]]):
272 The request object. A request for reporting an individual
273 error event.
274 project_name (:class:`str`):
275 Required. The resource name of the Google Cloud Platform
276 project. Written as ``projects/{projectId}``, where
277 ``{projectId}`` is the `Google Cloud Platform project
278 ID <https://support.google.com/cloud/answer/6158840>`__.
279
280 Example: // ``projects/my-project-123``.
281
282 This corresponds to the ``project_name`` field
283 on the ``request`` instance; if ``request`` is provided, this
284 should not be set.
285 event (:class:`google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent`):
286 Required. The error event to be
287 reported.
288
289 This corresponds to the ``event`` field
290 on the ``request`` instance; if ``request`` is provided, this
291 should not be set.
292 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
293 should be retried.
294 timeout (float): The timeout for this request.
295 metadata (Sequence[Tuple[str, str]]): Strings which should be
296 sent along with the request as metadata.
297
298 Returns:
299 google.cloud.errorreporting_v1beta1.types.ReportErrorEventResponse:
300 Response for reporting an individual
301 error event. Data may be added to this
302 message in the future.
303
304 """
305 # Create or coerce a protobuf request object.
306 # Quick check: If we got a request object, we should *not* have
307 # gotten any keyword arguments that map to the request.
308 has_flattened_params = any([project_name, event])
309 if request is not None and has_flattened_params:
310 raise ValueError(
311 "If the `request` argument is set, then none of "
312 "the individual field arguments should be set."
313 )
314
315 request = report_errors_service.ReportErrorEventRequest(request)
316
317 # If we have keyword arguments corresponding to fields on the
318 # request, apply these.
319 if project_name is not None:
320 request.project_name = project_name
321 if event is not None:
322 request.event = event
323
324 # Wrap the RPC method; this adds retry and timeout information,
325 # and friendly error handling.
326 rpc = gapic_v1.method_async.wrap_method(
327 self._client._transport.report_error_event,
328 default_timeout=None,
329 client_info=DEFAULT_CLIENT_INFO,
330 )
331
332 # Certain fields should be provided within the metadata header;
333 # add these here.
334 metadata = tuple(metadata) + (
335 gapic_v1.routing_header.to_grpc_metadata(
336 (("project_name", request.project_name),)
337 ),
338 )
339
340 # Send the request.
341 response = await rpc(
342 request,
343 retry=retry,
344 timeout=timeout,
345 metadata=metadata,
346 )
347
348 # Done; return the response.
349 return response
350
351 async def __aenter__(self) -> "ReportErrorsServiceAsyncClient":
352 return self
353
354 async def __aexit__(self, exc_type, exc, tb):
355 await self.transport.close()
356
357
358DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
359 gapic_version=package_version.__version__
360)
361
362
363__all__ = ("ReportErrorsServiceAsyncClient",)