Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/google/cloud/errorreporting_v1beta1/services/report_errors_service/async_client.py: 68%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

84 statements  

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 sa_info_func = ( 

114 ReportErrorsServiceClient.from_service_account_info.__func__ # type: ignore 

115 ) 

116 return sa_info_func(ReportErrorsServiceAsyncClient, info, *args, **kwargs) 

117 

118 @classmethod 

119 def from_service_account_file(cls, filename: str, *args, **kwargs): 

120 """Creates an instance of this client using the provided credentials 

121 file. 

122 

123 Args: 

124 filename (str): The path to the service account private key json 

125 file. 

126 args: Additional arguments to pass to the constructor. 

127 kwargs: Additional arguments to pass to the constructor. 

128 

129 Returns: 

130 ReportErrorsServiceAsyncClient: The constructed client. 

131 """ 

132 sa_file_func = ( 

133 ReportErrorsServiceClient.from_service_account_file.__func__ # type: ignore 

134 ) 

135 return sa_file_func(ReportErrorsServiceAsyncClient, filename, *args, **kwargs) 

136 

137 from_service_account_json = from_service_account_file 

138 

139 @classmethod 

140 def get_mtls_endpoint_and_cert_source( 

141 cls, client_options: Optional[ClientOptions] = None 

142 ): 

143 """Return the API endpoint and client cert source for mutual TLS. 

144 

145 The client cert source is determined in the following order: 

146 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the 

147 client cert source is None. 

148 (2) if `client_options.client_cert_source` is provided, use the provided one; if the 

149 default client cert source exists, use the default one; otherwise the client cert 

150 source is None. 

151 

152 The API endpoint is determined in the following order: 

153 (1) if `client_options.api_endpoint` if provided, use the provided one. 

154 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the 

155 default mTLS endpoint; if the environment variable is "never", use the default API 

156 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise 

157 use the default API endpoint. 

158 

159 More details can be found at https://google.aip.dev/auth/4114. 

160 

161 Args: 

162 client_options (google.api_core.client_options.ClientOptions): Custom options for the 

163 client. Only the `api_endpoint` and `client_cert_source` properties may be used 

164 in this method. 

165 

166 Returns: 

167 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the 

168 client cert source to use. 

169 

170 Raises: 

171 google.auth.exceptions.MutualTLSChannelError: If any errors happen. 

172 """ 

173 return ReportErrorsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore 

174 

175 @property 

176 def transport(self) -> ReportErrorsServiceTransport: 

177 """Returns the transport used by the client instance. 

178 

179 Returns: 

180 ReportErrorsServiceTransport: The transport used by the client instance. 

181 """ 

182 return self._client.transport 

183 

184 @property 

185 def api_endpoint(self): 

186 """Return the API endpoint used by the client instance. 

187 

188 Returns: 

189 str: The API endpoint used by the client instance. 

190 """ 

191 return self._client._api_endpoint 

192 

193 @property 

194 def universe_domain(self) -> str: 

195 """Return the universe domain used by the client instance. 

196 

197 Returns: 

198 str: The universe domain used 

199 by the client instance. 

200 """ 

201 return self._client._universe_domain 

202 

203 get_transport_class = ReportErrorsServiceClient.get_transport_class 

204 

205 def __init__( 

206 self, 

207 *, 

208 credentials: Optional[ga_credentials.Credentials] = None, 

209 transport: Optional[ 

210 Union[ 

211 str, 

212 ReportErrorsServiceTransport, 

213 Callable[..., ReportErrorsServiceTransport], 

214 ] 

215 ] = "grpc_asyncio", 

216 client_options: Optional[ClientOptions] = None, 

217 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

218 ) -> None: 

219 """Instantiates the report errors service async client. 

220 

221 Args: 

222 credentials (Optional[google.auth.credentials.Credentials]): The 

223 authorization credentials to attach to requests. These 

224 credentials identify the application to the service; if none 

225 are specified, the client will attempt to ascertain the 

226 credentials from the environment. 

227 transport (Optional[Union[str,ReportErrorsServiceTransport,Callable[..., ReportErrorsServiceTransport]]]): 

228 The transport to use, or a Callable that constructs and returns a new transport to use. 

229 If a Callable is given, it will be called with the same set of initialization 

230 arguments as used in the ReportErrorsServiceTransport constructor. 

231 If set to None, a transport is chosen automatically. 

232 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 

233 Custom options for the client. 

234 

235 1. The ``api_endpoint`` property can be used to override the 

236 default endpoint provided by the client when ``transport`` is 

237 not explicitly provided. Only if this property is not set and 

238 ``transport`` was not explicitly provided, the endpoint is 

239 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

240 variable, which have one of the following values: 

241 "always" (always use the default mTLS endpoint), "never" (always 

242 use the default regular endpoint) and "auto" (auto-switch to the 

243 default mTLS endpoint if client certificate is present; this is 

244 the default value). 

245 

246 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

247 is "true", then the ``client_cert_source`` property can be used 

248 to provide a client certificate for mTLS transport. If 

249 not provided, the default SSL client certificate will be used if 

250 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

251 set, no client certificate will be used. 

252 

253 3. The ``universe_domain`` property can be used to override the 

254 default "googleapis.com" universe. Note that ``api_endpoint`` 

255 property still takes precedence; and ``universe_domain`` is 

256 currently not supported for mTLS. 

257 

258 client_info (google.api_core.gapic_v1.client_info.ClientInfo): 

259 The client info used to send a user-agent string along with 

260 API requests. If ``None``, then default info will be used. 

261 Generally, you only need to set this if you're developing 

262 your own client library. 

263 

264 Raises: 

265 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport 

266 creation failed for any reason. 

267 """ 

268 self._client = ReportErrorsServiceClient( 

269 credentials=credentials, 

270 transport=transport, 

271 client_options=client_options, 

272 client_info=client_info, 

273 ) 

274 

275 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

276 std_logging.DEBUG 

277 ): # pragma: NO COVER 

278 _LOGGER.debug( 

279 "Created client `google.devtools.clouderrorreporting_v1beta1.ReportErrorsServiceAsyncClient`.", 

280 extra={ 

281 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ReportErrorsService", 

282 "universeDomain": getattr( 

283 self._client._transport._credentials, "universe_domain", "" 

284 ), 

285 "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", 

286 "credentialsInfo": getattr( 

287 self.transport._credentials, "get_cred_info", lambda: None 

288 )(), 

289 } 

290 if hasattr(self._client._transport, "_credentials") 

291 else { 

292 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ReportErrorsService", 

293 "credentialsType": None, 

294 }, 

295 ) 

296 

297 async def report_error_event( 

298 self, 

299 request: Optional[ 

300 Union[report_errors_service.ReportErrorEventRequest, dict] 

301 ] = None, 

302 *, 

303 project_name: Optional[str] = None, 

304 event: Optional[report_errors_service.ReportedErrorEvent] = None, 

305 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

306 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

307 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

308 ) -> report_errors_service.ReportErrorEventResponse: 

309 r"""Report an individual error event and record the event to a log. 

310 

311 This endpoint accepts **either** an OAuth token, **or** an `API 

312 key <https://support.google.com/cloud/answer/6158862>`__ for 

313 authentication. To use an API key, append it to the URL as the 

314 value of a ``key`` parameter. For example: 

315 

316 ``POST https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`` 

317 

318 **Note:** [Error Reporting] 

319 (https://cloud.google.com/error-reporting) is a service built on 

320 Cloud Logging and can analyze log entries when all of the 

321 following are true: 

322 

323 - Customer-managed encryption keys (CMEK) are disabled on the 

324 log bucket. 

325 - The log bucket satisfies one of the following: 

326 

327 - The log bucket is stored in the same project where the logs 

328 originated. 

329 - The logs were routed to a project, and then that project 

330 stored those logs in a log bucket that it owns. 

331 

332 .. code-block:: python 

333 

334 # This snippet has been automatically generated and should be regarded as a 

335 # code template only. 

336 # It will require modifications to work: 

337 # - It may require correct/in-range values for request initialization. 

338 # - It may require specifying regional endpoints when creating the service 

339 # client as shown in: 

340 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

341 from google.cloud import errorreporting_v1beta1 

342 

343 async def sample_report_error_event(): 

344 # Create a client 

345 client = errorreporting_v1beta1.ReportErrorsServiceAsyncClient() 

346 

347 # Initialize request argument(s) 

348 event = errorreporting_v1beta1.ReportedErrorEvent() 

349 event.message = "message_value" 

350 

351 request = errorreporting_v1beta1.ReportErrorEventRequest( 

352 project_name="project_name_value", 

353 event=event, 

354 ) 

355 

356 # Make the request 

357 response = await client.report_error_event(request=request) 

358 

359 # Handle the response 

360 print(response) 

361 

362 Args: 

363 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.ReportErrorEventRequest, dict]]): 

364 The request object. A request for reporting an individual 

365 error event. 

366 project_name (:class:`str`): 

367 Required. The resource name of the Google Cloud Platform 

368 project. Written as ``projects/{projectId}``, where 

369 ``{projectId}`` is the `Google Cloud Platform project 

370 ID <https://support.google.com/cloud/answer/6158840>`__. 

371 

372 Example: // ``projects/my-project-123``. 

373 

374 This corresponds to the ``project_name`` field 

375 on the ``request`` instance; if ``request`` is provided, this 

376 should not be set. 

377 event (:class:`google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent`): 

378 Required. The error event to be 

379 reported. 

380 

381 This corresponds to the ``event`` field 

382 on the ``request`` instance; if ``request`` is provided, this 

383 should not be set. 

384 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

385 should be retried. 

386 timeout (float): The timeout for this request. 

387 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

388 sent along with the request as metadata. Normally, each value must be of type `str`, 

389 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

390 be of type `bytes`. 

391 

392 Returns: 

393 google.cloud.errorreporting_v1beta1.types.ReportErrorEventResponse: 

394 Response for reporting an individual 

395 error event. Data may be added to this 

396 message in the future. 

397 

398 """ 

399 # Create or coerce a protobuf request object. 

400 # - Quick check: If we got a request object, we should *not* have 

401 # gotten any keyword arguments that map to the request. 

402 flattened_params = [project_name, event] 

403 has_flattened_params = ( 

404 len([param for param in flattened_params if param is not None]) > 0 

405 ) 

406 if request is not None and has_flattened_params: 

407 raise ValueError( 

408 "If the `request` argument is set, then none of " 

409 "the individual field arguments should be set." 

410 ) 

411 

412 # - Use the request object if provided (there's no risk of modifying the input as 

413 # there are no flattened fields), or create one. 

414 if not isinstance(request, report_errors_service.ReportErrorEventRequest): 

415 request = report_errors_service.ReportErrorEventRequest(request) 

416 

417 # If we have keyword arguments corresponding to fields on the 

418 # request, apply these. 

419 if project_name is not None: 

420 request.project_name = project_name 

421 if event is not None: 

422 request.event = event 

423 

424 # Wrap the RPC method; this adds retry and timeout information, 

425 # and friendly error handling. 

426 rpc = self._client._transport._wrapped_methods[ 

427 self._client._transport.report_error_event 

428 ] 

429 

430 # Certain fields should be provided within the metadata header; 

431 # add these here. 

432 metadata = tuple(metadata) + ( 

433 gapic_v1.routing_header.to_grpc_metadata( 

434 (("project_name", request.project_name),) 

435 ), 

436 ) 

437 

438 # Validate the universe domain. 

439 self._client._validate_universe_domain() 

440 

441 # Send the request. 

442 response = await rpc( 

443 request, 

444 retry=retry, 

445 timeout=timeout, 

446 metadata=metadata, 

447 ) 

448 

449 # Done; return the response. 

450 return response 

451 

452 async def __aenter__(self) -> "ReportErrorsServiceAsyncClient": 

453 return self 

454 

455 async def __aexit__(self, exc_type, exc, tb): 

456 await self.transport.close() 

457 

458 

459DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

460 gapic_version=package_version.__version__ 

461) 

462 

463if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER 

464 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

465 

466 

467__all__ = ("ReportErrorsServiceAsyncClient",)