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

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

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

119 ErrorGroupServiceClient.from_service_account_info.__func__ # type: ignore 

120 ) 

121 return sa_info_func(ErrorGroupServiceAsyncClient, info, *args, **kwargs) 

122 

123 @classmethod 

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

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

126 file. 

127 

128 Args: 

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

130 file. 

131 args: Additional arguments to pass to the constructor. 

132 kwargs: Additional arguments to pass to the constructor. 

133 

134 Returns: 

135 ErrorGroupServiceAsyncClient: The constructed client. 

136 """ 

137 sa_file_func = ( 

138 ErrorGroupServiceClient.from_service_account_file.__func__ # type: ignore 

139 ) 

140 return sa_file_func(ErrorGroupServiceAsyncClient, filename, *args, **kwargs) 

141 

142 from_service_account_json = from_service_account_file 

143 

144 @classmethod 

145 def get_mtls_endpoint_and_cert_source( 

146 cls, client_options: Optional[ClientOptions] = None 

147 ): 

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

149 

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

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

152 client cert source is None. 

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

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

155 source is None. 

156 

157 The API endpoint is determined in the following order: 

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

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

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

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

162 use the default API endpoint. 

163 

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

165 

166 Args: 

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

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

169 in this method. 

170 

171 Returns: 

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

173 client cert source to use. 

174 

175 Raises: 

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

177 """ 

178 return ErrorGroupServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore 

179 

180 @property 

181 def transport(self) -> ErrorGroupServiceTransport: 

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

183 

184 Returns: 

185 ErrorGroupServiceTransport: The transport used by the client instance. 

186 """ 

187 return self._client.transport 

188 

189 @property 

190 def api_endpoint(self): 

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

192 

193 Returns: 

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

195 """ 

196 return self._client._api_endpoint 

197 

198 @property 

199 def universe_domain(self) -> str: 

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

201 

202 Returns: 

203 str: The universe domain used 

204 by the client instance. 

205 """ 

206 return self._client._universe_domain 

207 

208 get_transport_class = ErrorGroupServiceClient.get_transport_class 

209 

210 def __init__( 

211 self, 

212 *, 

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

214 transport: Optional[ 

215 Union[ 

216 str, 

217 ErrorGroupServiceTransport, 

218 Callable[..., ErrorGroupServiceTransport], 

219 ] 

220 ] = "grpc_asyncio", 

221 client_options: Optional[ClientOptions] = None, 

222 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

223 ) -> None: 

224 """Instantiates the error group service async client. 

225 

226 Args: 

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

228 authorization credentials to attach to requests. These 

229 credentials identify the application to the service; if none 

230 are specified, the client will attempt to ascertain the 

231 credentials from the environment. 

232 transport (Optional[Union[str,ErrorGroupServiceTransport,Callable[..., ErrorGroupServiceTransport]]]): 

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

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

235 arguments as used in the ErrorGroupServiceTransport constructor. 

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

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

238 Custom options for the client. 

239 

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

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

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

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

244 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

245 variable, which have one of the following values: 

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

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

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

249 the default value). 

250 

251 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

253 to provide a client certificate for mTLS transport. If 

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

255 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

256 set, no client certificate will be used. 

257 

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

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

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

261 currently not supported for mTLS. 

262 

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

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

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

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

267 your own client library. 

268 

269 Raises: 

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

271 creation failed for any reason. 

272 """ 

273 self._client = ErrorGroupServiceClient( 

274 credentials=credentials, 

275 transport=transport, 

276 client_options=client_options, 

277 client_info=client_info, 

278 ) 

279 

280 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

281 std_logging.DEBUG 

282 ): # pragma: NO COVER 

283 _LOGGER.debug( 

284 "Created client `google.devtools.clouderrorreporting_v1beta1.ErrorGroupServiceAsyncClient`.", 

285 extra={ 

286 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService", 

287 "universeDomain": getattr( 

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

289 ), 

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

291 "credentialsInfo": getattr( 

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

293 )(), 

294 } 

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

296 else { 

297 "serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService", 

298 "credentialsType": None, 

299 }, 

300 ) 

301 

302 async def get_group( 

303 self, 

304 request: Optional[Union[error_group_service.GetGroupRequest, dict]] = None, 

305 *, 

306 group_name: Optional[str] = None, 

307 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

310 ) -> common.ErrorGroup: 

311 r"""Get the specified group. 

312 

313 .. code-block:: python 

314 

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

316 # code template only. 

317 # It will require modifications to work: 

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

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

320 # client as shown in: 

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

322 from google.cloud import errorreporting_v1beta1 

323 

324 async def sample_get_group(): 

325 # Create a client 

326 client = errorreporting_v1beta1.ErrorGroupServiceAsyncClient() 

327 

328 # Initialize request argument(s) 

329 request = errorreporting_v1beta1.GetGroupRequest( 

330 group_name="group_name_value", 

331 ) 

332 

333 # Make the request 

334 response = await client.get_group(request=request) 

335 

336 # Handle the response 

337 print(response) 

338 

339 Args: 

340 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.GetGroupRequest, dict]]): 

341 The request object. A request to return an individual 

342 group. 

343 group_name (:class:`str`): 

344 Required. The group resource name. Written as either 

345 ``projects/{projectID}/groups/{group_id}`` or 

346 ``projects/{projectID}/locations/{location}/groups/{group_id}``. 

347 Call [groupStats.list] 

348 [google.devtools.clouderrorreporting.v1beta1.ErrorStatsService.ListGroupStats] 

349 to return a list of groups belonging to this project. 

350 

351 Examples: ``projects/my-project-123/groups/my-group``, 

352 ``projects/my-project-123/locations/global/groups/my-group`` 

353 

354 In the group resource name, the ``group_id`` is a unique 

355 identifier for a particular error group. The identifier 

356 is derived from key parts of the error-log content and 

357 is treated as Service Data. For information about how 

358 Service Data is handled, see `Google Cloud Privacy 

359 Notice <https://cloud.google.com/terms/cloud-privacy-notice>`__. 

360 

361 For a list of supported locations, see `Supported 

362 Regions <https://cloud.google.com/logging/docs/region-support>`__. 

363 ``global`` is the default when unspecified. 

364 

365 This corresponds to the ``group_name`` field 

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

367 should not be set. 

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

369 should be retried. 

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

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

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

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

374 be of type `bytes`. 

375 

376 Returns: 

377 google.cloud.errorreporting_v1beta1.types.ErrorGroup: 

378 Description of a group of similar 

379 error events. 

380 

381 """ 

382 # Create or coerce a protobuf request object. 

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

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

385 flattened_params = [group_name] 

386 has_flattened_params = ( 

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

388 ) 

389 if request is not None and has_flattened_params: 

390 raise ValueError( 

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

392 "the individual field arguments should be set." 

393 ) 

394 

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

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

397 if not isinstance(request, error_group_service.GetGroupRequest): 

398 request = error_group_service.GetGroupRequest(request) 

399 

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

401 # request, apply these. 

402 if group_name is not None: 

403 request.group_name = group_name 

404 

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

406 # and friendly error handling. 

407 rpc = self._client._transport._wrapped_methods[ 

408 self._client._transport.get_group 

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 # Validate the universe domain. 

420 self._client._validate_universe_domain() 

421 

422 # Send the request. 

423 response = await rpc( 

424 request, 

425 retry=retry, 

426 timeout=timeout, 

427 metadata=metadata, 

428 ) 

429 

430 # Done; return the response. 

431 return response 

432 

433 async def update_group( 

434 self, 

435 request: Optional[Union[error_group_service.UpdateGroupRequest, dict]] = None, 

436 *, 

437 group: Optional[common.ErrorGroup] = None, 

438 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

441 ) -> common.ErrorGroup: 

442 r"""Replace the data for the specified group. 

443 Fails if the group does not exist. 

444 

445 .. code-block:: python 

446 

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

448 # code template only. 

449 # It will require modifications to work: 

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

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

452 # client as shown in: 

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

454 from google.cloud import errorreporting_v1beta1 

455 

456 async def sample_update_group(): 

457 # Create a client 

458 client = errorreporting_v1beta1.ErrorGroupServiceAsyncClient() 

459 

460 # Initialize request argument(s) 

461 request = errorreporting_v1beta1.UpdateGroupRequest( 

462 ) 

463 

464 # Make the request 

465 response = await client.update_group(request=request) 

466 

467 # Handle the response 

468 print(response) 

469 

470 Args: 

471 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.UpdateGroupRequest, dict]]): 

472 The request object. A request to replace the existing 

473 data for the given group. 

474 group (:class:`google.cloud.errorreporting_v1beta1.types.ErrorGroup`): 

475 Required. The group which replaces 

476 the resource on the server. 

477 

478 This corresponds to the ``group`` field 

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

480 should not be set. 

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

482 should be retried. 

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

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

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

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

487 be of type `bytes`. 

488 

489 Returns: 

490 google.cloud.errorreporting_v1beta1.types.ErrorGroup: 

491 Description of a group of similar 

492 error events. 

493 

494 """ 

495 # Create or coerce a protobuf request object. 

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

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

498 flattened_params = [group] 

499 has_flattened_params = ( 

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

501 ) 

502 if request is not None and has_flattened_params: 

503 raise ValueError( 

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

505 "the individual field arguments should be set." 

506 ) 

507 

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

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

510 if not isinstance(request, error_group_service.UpdateGroupRequest): 

511 request = error_group_service.UpdateGroupRequest(request) 

512 

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

514 # request, apply these. 

515 if group is not None: 

516 request.group = group 

517 

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

519 # and friendly error handling. 

520 rpc = self._client._transport._wrapped_methods[ 

521 self._client._transport.update_group 

522 ] 

523 

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

525 # add these here. 

526 metadata = tuple(metadata) + ( 

527 gapic_v1.routing_header.to_grpc_metadata( 

528 (("group.name", request.group.name),) 

529 ), 

530 ) 

531 

532 # Validate the universe domain. 

533 self._client._validate_universe_domain() 

534 

535 # Send the request. 

536 response = await rpc( 

537 request, 

538 retry=retry, 

539 timeout=timeout, 

540 metadata=metadata, 

541 ) 

542 

543 # Done; return the response. 

544 return response 

545 

546 async def __aenter__(self) -> "ErrorGroupServiceAsyncClient": 

547 return self 

548 

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

550 await self.transport.close() 

551 

552 

553DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

554 gapic_version=package_version.__version__ 

555) 

556 

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

558 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

559 

560 

561__all__ = ("ErrorGroupServiceAsyncClient",)