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#
16import warnings
17from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
18
19from google.api_core import gapic_v1
20from google.api_core import grpc_helpers_async
21from google.auth import credentials as ga_credentials # type: ignore
22from google.auth.transport.grpc import SslCredentials # type: ignore
23
24import grpc # type: ignore
25from grpc.experimental import aio # type: ignore
26
27from google.cloud.errorreporting_v1beta1.types import report_errors_service
28from .base import ReportErrorsServiceTransport, DEFAULT_CLIENT_INFO
29from .grpc import ReportErrorsServiceGrpcTransport
30
31
32class ReportErrorsServiceGrpcAsyncIOTransport(ReportErrorsServiceTransport):
33 """gRPC AsyncIO backend transport for ReportErrorsService.
34
35 An API for reporting error events.
36
37 This class defines the same methods as the primary client, so the
38 primary client can load the underlying transport implementation
39 and call it.
40
41 It sends protocol buffers over the wire using gRPC (which is built on
42 top of HTTP/2); the ``grpcio`` package must be installed.
43 """
44
45 _grpc_channel: aio.Channel
46 _stubs: Dict[str, Callable] = {}
47
48 @classmethod
49 def create_channel(
50 cls,
51 host: str = "clouderrorreporting.googleapis.com",
52 credentials: Optional[ga_credentials.Credentials] = None,
53 credentials_file: Optional[str] = None,
54 scopes: Optional[Sequence[str]] = None,
55 quota_project_id: Optional[str] = None,
56 **kwargs,
57 ) -> aio.Channel:
58 """Create and return a gRPC AsyncIO channel object.
59 Args:
60 host (Optional[str]): The host for the channel to use.
61 credentials (Optional[~.Credentials]): The
62 authorization credentials to attach to requests. These
63 credentials identify this application to the service. If
64 none are specified, the client will attempt to ascertain
65 the credentials from the environment.
66 credentials_file (Optional[str]): A file with credentials that can
67 be loaded with :func:`google.auth.load_credentials_from_file`.
68 This argument is ignored if ``channel`` is provided.
69 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
70 service. These are only used when credentials are not specified and
71 are passed to :func:`google.auth.default`.
72 quota_project_id (Optional[str]): An optional project to use for billing
73 and quota.
74 kwargs (Optional[dict]): Keyword arguments, which are passed to the
75 channel creation.
76 Returns:
77 aio.Channel: A gRPC AsyncIO channel object.
78 """
79
80 return grpc_helpers_async.create_channel(
81 host,
82 credentials=credentials,
83 credentials_file=credentials_file,
84 quota_project_id=quota_project_id,
85 default_scopes=cls.AUTH_SCOPES,
86 scopes=scopes,
87 default_host=cls.DEFAULT_HOST,
88 **kwargs,
89 )
90
91 def __init__(
92 self,
93 *,
94 host: str = "clouderrorreporting.googleapis.com",
95 credentials: Optional[ga_credentials.Credentials] = None,
96 credentials_file: Optional[str] = None,
97 scopes: Optional[Sequence[str]] = None,
98 channel: Optional[aio.Channel] = None,
99 api_mtls_endpoint: Optional[str] = None,
100 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
101 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
102 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
103 quota_project_id: Optional[str] = None,
104 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
105 always_use_jwt_access: Optional[bool] = False,
106 api_audience: Optional[str] = None,
107 ) -> None:
108 """Instantiate the transport.
109
110 Args:
111 host (Optional[str]):
112 The hostname to connect to.
113 credentials (Optional[google.auth.credentials.Credentials]): The
114 authorization credentials to attach to requests. These
115 credentials identify the application to the service; if none
116 are specified, the client will attempt to ascertain the
117 credentials from the environment.
118 This argument is ignored if ``channel`` is provided.
119 credentials_file (Optional[str]): A file with credentials that can
120 be loaded with :func:`google.auth.load_credentials_from_file`.
121 This argument is ignored if ``channel`` is provided.
122 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
123 service. These are only used when credentials are not specified and
124 are passed to :func:`google.auth.default`.
125 channel (Optional[aio.Channel]): A ``Channel`` instance through
126 which to make calls.
127 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
128 If provided, it overrides the ``host`` argument and tries to create
129 a mutual TLS channel with client SSL credentials from
130 ``client_cert_source`` or application default SSL credentials.
131 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
132 Deprecated. A callback to provide client SSL certificate bytes and
133 private key bytes, both in PEM format. It is ignored if
134 ``api_mtls_endpoint`` is None.
135 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
136 for the grpc channel. It is ignored if ``channel`` is provided.
137 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
138 A callback to provide client certificate bytes and private key bytes,
139 both in PEM format. It is used to configure a mutual TLS channel. It is
140 ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
141 quota_project_id (Optional[str]): An optional project to use for billing
142 and quota.
143 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
144 The client info used to send a user-agent string along with
145 API requests. If ``None``, then default info will be used.
146 Generally, you only need to set this if you're developing
147 your own client library.
148 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
149 be used for service account credentials.
150
151 Raises:
152 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
153 creation failed for any reason.
154 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
155 and ``credentials_file`` are passed.
156 """
157 self._grpc_channel = None
158 self._ssl_channel_credentials = ssl_channel_credentials
159 self._stubs: Dict[str, Callable] = {}
160
161 if api_mtls_endpoint:
162 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
163 if client_cert_source:
164 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
165
166 if channel:
167 # Ignore credentials if a channel was passed.
168 credentials = False
169 # If a channel was explicitly provided, set it.
170 self._grpc_channel = channel
171 self._ssl_channel_credentials = None
172 else:
173 if api_mtls_endpoint:
174 host = api_mtls_endpoint
175
176 # Create SSL credentials with client_cert_source or application
177 # default SSL credentials.
178 if client_cert_source:
179 cert, key = client_cert_source()
180 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
181 certificate_chain=cert, private_key=key
182 )
183 else:
184 self._ssl_channel_credentials = SslCredentials().ssl_credentials
185
186 else:
187 if client_cert_source_for_mtls and not ssl_channel_credentials:
188 cert, key = client_cert_source_for_mtls()
189 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
190 certificate_chain=cert, private_key=key
191 )
192
193 # The base transport sets the host, credentials and scopes
194 super().__init__(
195 host=host,
196 credentials=credentials,
197 credentials_file=credentials_file,
198 scopes=scopes,
199 quota_project_id=quota_project_id,
200 client_info=client_info,
201 always_use_jwt_access=always_use_jwt_access,
202 api_audience=api_audience,
203 )
204
205 if not self._grpc_channel:
206 self._grpc_channel = type(self).create_channel(
207 self._host,
208 # use the credentials which are saved
209 credentials=self._credentials,
210 # Set ``credentials_file`` to ``None`` here as
211 # the credentials that we saved earlier should be used.
212 credentials_file=None,
213 scopes=self._scopes,
214 ssl_credentials=self._ssl_channel_credentials,
215 quota_project_id=quota_project_id,
216 options=[
217 ("grpc.max_send_message_length", -1),
218 ("grpc.max_receive_message_length", -1),
219 ],
220 )
221
222 # Wrap messages. This must be done after self._grpc_channel exists
223 self._prep_wrapped_messages(client_info)
224
225 @property
226 def grpc_channel(self) -> aio.Channel:
227 """Create the channel designed to connect to this service.
228
229 This property caches on the instance; repeated calls return
230 the same channel.
231 """
232 # Return the channel from cache.
233 return self._grpc_channel
234
235 @property
236 def report_error_event(
237 self,
238 ) -> Callable[
239 [report_errors_service.ReportErrorEventRequest],
240 Awaitable[report_errors_service.ReportErrorEventResponse],
241 ]:
242 r"""Return a callable for the report error event method over gRPC.
243
244 Report an individual error event and record the event to a log.
245
246 This endpoint accepts **either** an OAuth token, **or** an `API
247 key <https://support.google.com/cloud/answer/6158862>`__ for
248 authentication. To use an API key, append it to the URL as the
249 value of a ``key`` parameter. For example:
250
251 ``POST https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456``
252
253 **Note:** `Error Reporting </error-reporting>`__ is a global
254 service built on Cloud Logging and doesn't analyze logs stored
255 in regional log buckets or logs routed to other Google Cloud
256 projects.
257
258 Returns:
259 Callable[[~.ReportErrorEventRequest],
260 Awaitable[~.ReportErrorEventResponse]]:
261 A function that, when called, will call the underlying RPC
262 on the server.
263 """
264 # Generate a "stub function" on-the-fly which will actually make
265 # the request.
266 # gRPC handles serialization and deserialization, so we just need
267 # to pass in the functions for each.
268 if "report_error_event" not in self._stubs:
269 self._stubs["report_error_event"] = self.grpc_channel.unary_unary(
270 "/google.devtools.clouderrorreporting.v1beta1.ReportErrorsService/ReportErrorEvent",
271 request_serializer=report_errors_service.ReportErrorEventRequest.serialize,
272 response_deserializer=report_errors_service.ReportErrorEventResponse.deserialize,
273 )
274 return self._stubs["report_error_event"]
275
276 def close(self):
277 return self.grpc_channel.close()
278
279
280__all__ = ("ReportErrorsServiceGrpcAsyncIOTransport",)