google_servicecontrol2/api.rs
1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16 /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
17 CloudPlatform,
18
19 /// Manage your Google Service Control data
20 Full,
21}
22
23impl AsRef<str> for Scope {
24 fn as_ref(&self) -> &str {
25 match *self {
26 Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
27 Scope::Full => "https://www.googleapis.com/auth/servicecontrol",
28 }
29 }
30}
31
32#[allow(clippy::derivable_impls)]
33impl Default for Scope {
34 fn default() -> Scope {
35 Scope::CloudPlatform
36 }
37}
38
39// ########
40// HUB ###
41// ######
42
43/// Central instance to access all ServiceControl related resource activities
44///
45/// # Examples
46///
47/// Instantiate a new hub
48///
49/// ```test_harness,no_run
50/// extern crate hyper;
51/// extern crate hyper_rustls;
52/// extern crate google_servicecontrol2 as servicecontrol2;
53/// use servicecontrol2::api::CheckRequest;
54/// use servicecontrol2::{Result, Error};
55/// # async fn dox() {
56/// use servicecontrol2::{ServiceControl, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
57///
58/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
59/// // `client_secret`, among other things.
60/// let secret: yup_oauth2::ApplicationSecret = Default::default();
61/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
62/// // unless you replace `None` with the desired Flow.
63/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
64/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
65/// // retrieve them from storage.
66/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
67/// .with_native_roots()
68/// .unwrap()
69/// .https_only()
70/// .enable_http2()
71/// .build();
72///
73/// let executor = hyper_util::rt::TokioExecutor::new();
74/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
75/// secret,
76/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
77/// yup_oauth2::client::CustomHyperClientBuilder::from(
78/// hyper_util::client::legacy::Client::builder(executor).build(connector),
79/// ),
80/// ).build().await.unwrap();
81///
82/// let client = hyper_util::client::legacy::Client::builder(
83/// hyper_util::rt::TokioExecutor::new()
84/// )
85/// .build(
86/// hyper_rustls::HttpsConnectorBuilder::new()
87/// .with_native_roots()
88/// .unwrap()
89/// .https_or_http()
90/// .enable_http2()
91/// .build()
92/// );
93/// let mut hub = ServiceControl::new(client, auth);
94/// // As the method needs a request, you would usually fill it with the desired information
95/// // into the respective structure. Some of the parts shown here might not be applicable !
96/// // Values shown here are possibly random and not representative !
97/// let mut req = CheckRequest::default();
98///
99/// // You can configure optional parameters by calling the respective setters at will, and
100/// // execute the final call using `doit()`.
101/// // Values shown here are possibly random and not representative !
102/// let result = hub.services().check(req, "serviceName")
103/// .doit().await;
104///
105/// match result {
106/// Err(e) => match e {
107/// // The Error enum provides details about what exactly happened.
108/// // You can also just use its `Debug`, `Display` or `Error` traits
109/// Error::HttpError(_)
110/// |Error::Io(_)
111/// |Error::MissingAPIKey
112/// |Error::MissingToken(_)
113/// |Error::Cancelled
114/// |Error::UploadSizeLimitExceeded(_, _)
115/// |Error::Failure(_)
116/// |Error::BadRequest(_)
117/// |Error::FieldClash(_)
118/// |Error::JsonDecodeError(_, _) => println!("{}", e),
119/// },
120/// Ok(res) => println!("Success: {:?}", res),
121/// }
122/// # }
123/// ```
124#[derive(Clone)]
125pub struct ServiceControl<C> {
126 pub client: common::Client<C>,
127 pub auth: Box<dyn common::GetToken>,
128 _user_agent: String,
129 _base_url: String,
130 _root_url: String,
131}
132
133impl<C> common::Hub for ServiceControl<C> {}
134
135impl<'a, C> ServiceControl<C> {
136 pub fn new<A: 'static + common::GetToken>(
137 client: common::Client<C>,
138 auth: A,
139 ) -> ServiceControl<C> {
140 ServiceControl {
141 client,
142 auth: Box::new(auth),
143 _user_agent: "google-api-rust-client/7.0.0".to_string(),
144 _base_url: "https://servicecontrol.googleapis.com/".to_string(),
145 _root_url: "https://servicecontrol.googleapis.com/".to_string(),
146 }
147 }
148
149 pub fn services(&'a self) -> ServiceMethods<'a, C> {
150 ServiceMethods { hub: self }
151 }
152
153 /// Set the user-agent header field to use in all requests to the server.
154 /// It defaults to `google-api-rust-client/7.0.0`.
155 ///
156 /// Returns the previously set user-agent.
157 pub fn user_agent(&mut self, agent_name: String) -> String {
158 std::mem::replace(&mut self._user_agent, agent_name)
159 }
160
161 /// Set the base url to use in all requests to the server.
162 /// It defaults to `https://servicecontrol.googleapis.com/`.
163 ///
164 /// Returns the previously set base url.
165 pub fn base_url(&mut self, new_base_url: String) -> String {
166 std::mem::replace(&mut self._base_url, new_base_url)
167 }
168
169 /// Set the root url to use in all requests to the server.
170 /// It defaults to `https://servicecontrol.googleapis.com/`.
171 ///
172 /// Returns the previously set root url.
173 pub fn root_url(&mut self, new_root_url: String) -> String {
174 std::mem::replace(&mut self._root_url, new_root_url)
175 }
176}
177
178// ############
179// SCHEMAS ###
180// ##########
181/// This message defines attributes associated with API operations, such as a network API request. The terminology is based on the conventions used by Google APIs, Istio, and OpenAPI.
182///
183/// This type is not used in any activity, and only used as *part* of another schema.
184///
185#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
186#[serde_with::serde_as]
187#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
188pub struct Api {
189 /// The API operation name. For gRPC requests, it is the fully qualified API method name, such as "google.pubsub.v1.Publisher.Publish". For OpenAPI requests, it is the `operationId`, such as "getPet".
190 pub operation: Option<String>,
191 /// The API protocol used for sending the request, such as "http", "https", "grpc", or "internal".
192 pub protocol: Option<String>,
193 /// The API service name. It is a logical identifier for a networked API, such as "pubsub.googleapis.com". The naming syntax depends on the API management system being used for handling the request.
194 pub service: Option<String>,
195 /// The API version associated with the API operation above, such as "v1" or "v1alpha1".
196 pub version: Option<String>,
197}
198
199impl common::Part for Api {}
200
201/// This message defines the standard attribute vocabulary for Google APIs. An attribute is a piece of metadata that describes an activity on a network service. For example, the size of an HTTP request, or the status code of an HTTP response. Each attribute has a type and a name, which is logically defined as a proto message field in `AttributeContext`. The field type becomes the attribute type, and the field path becomes the attribute name. For example, the attribute `source.ip` maps to field `AttributeContext.source.ip`. This message definition is guaranteed not to have any wire breaking change. So you can use it directly for passing attributes across different systems. NOTE: Different system may generate different subset of attributes. Please verify the system specification before relying on an attribute generated a system.
202///
203/// This type is not used in any activity, and only used as *part* of another schema.
204///
205#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
206#[serde_with::serde_as]
207#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
208pub struct AttributeContext {
209 /// Represents an API operation that is involved to a network activity.
210 pub api: Option<Api>,
211 /// The destination of a network activity, such as accepting a TCP connection. In a multi hop network activity, the destination represents the receiver of the last hop.
212 pub destination: Option<Peer>,
213 /// Supports extensions for advanced use cases, such as logs and metrics.
214 pub extensions: Option<Vec<HashMap<String, serde_json::Value>>>,
215 /// The origin of a network activity. In a multi hop network activity, the origin represents the sender of the first hop. For the first hop, the `source` and the `origin` must have the same content.
216 pub origin: Option<Peer>,
217 /// Represents a network request, such as an HTTP request.
218 pub request: Option<Request>,
219 /// Represents a target resource that is involved with a network activity. If multiple resources are involved with an activity, this must be the primary one.
220 pub resource: Option<Resource>,
221 /// Represents a network response, such as an HTTP response.
222 pub response: Option<Response>,
223 /// The source of a network activity, such as starting a TCP connection. In a multi hop network activity, the source represents the sender of the last hop.
224 pub source: Option<Peer>,
225}
226
227impl common::Part for AttributeContext {}
228
229/// This message defines request authentication attributes. Terminology is based on the JSON Web Token (JWT) standard, but the terms also correlate to concepts in other standards.
230///
231/// This type is not used in any activity, and only used as *part* of another schema.
232///
233#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
234#[serde_with::serde_as]
235#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
236pub struct Auth {
237 /// A list of access level resource names that allow resources to be accessed by authenticated requester. It is part of Secure GCP processing for the incoming request. An access level string has the format: "//{api_service_name}/accessPolicies/{policy_id}/accessLevels/{short_name}" Example: "//accesscontextmanager.googleapis.com/accessPolicies/MY_POLICY_ID/accessLevels/MY_LEVEL"
238 #[serde(rename = "accessLevels")]
239 pub access_levels: Option<Vec<String>>,
240 /// The intended audience(s) for this authentication information. Reflects the audience (`aud`) claim within a JWT. The audience value(s) depends on the `issuer`, but typically include one or more of the following pieces of information: * The services intended to receive the credential. For example, ["https://pubsub.googleapis.com/", "https://storage.googleapis.com/"]. * A set of service-based scopes. For example, ["https://www.googleapis.com/auth/cloud-platform"]. * The client id of an app, such as the Firebase project id for JWTs from Firebase Auth. Consult the documentation for the credential issuer to determine the information provided.
241 pub audiences: Option<Vec<String>>,
242 /// Structured claims presented with the credential. JWTs include `{key: value}` pairs for standard and private claims. The following is a subset of the standard required and optional claims that would typically be presented for a Google-based JWT: {'iss': 'accounts.google.com', 'sub': '113289723416554971153', 'aud': ['123456789012', 'pubsub.googleapis.com'], 'azp': '123456789012.apps.googleusercontent.com', 'email': 'jsmith@example.com', 'iat': 1353601026, 'exp': 1353604926} SAML assertions are similarly specified, but with an identity provider dependent structure.
243 pub claims: Option<HashMap<String, serde_json::Value>>,
244 /// Attributes of the OAuth token associated with the request.
245 pub oauth: Option<Oauth>,
246 /// The authorized presenter of the credential. Reflects the optional Authorized Presenter (`azp`) claim within a JWT or the OAuth client id. For example, a Google Cloud Platform client id looks as follows: "123456789012.apps.googleusercontent.com".
247 pub presenter: Option<String>,
248 /// The authenticated principal. Reflects the issuer (`iss`) and subject (`sub`) claims within a JWT. The issuer and subject should be `/` delimited, with `/` percent-encoded within the subject fragment. For Google accounts, the principal format is: "https://accounts.google.com/{id}"
249 pub principal: Option<String>,
250}
251
252impl common::Part for Auth {}
253
254/// Request message for the Check method.
255///
256/// # Activities
257///
258/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
259/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
260///
261/// * [check services](ServiceCheckCall) (request)
262#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
263#[serde_with::serde_as]
264#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
265pub struct CheckRequest {
266 /// Describes attributes about the operation being executed by the service.
267 pub attributes: Option<AttributeContext>,
268 /// Optional. Contains a comma-separated list of flags.
269 pub flags: Option<String>,
270 /// Describes the resources and the policies applied to each resource.
271 pub resources: Option<Vec<ResourceInfo>>,
272 /// Specifies the version of the service configuration that should be used to process the request. Must not be empty. Set this field to 'latest' to specify using the latest configuration.
273 #[serde(rename = "serviceConfigId")]
274 pub service_config_id: Option<String>,
275}
276
277impl common::RequestValue for CheckRequest {}
278
279/// Response message for the Check method.
280///
281/// # Activities
282///
283/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
284/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
285///
286/// * [check services](ServiceCheckCall) (response)
287#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
288#[serde_with::serde_as]
289#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
290pub struct CheckResponse {
291 /// Optional response metadata that will be emitted as dynamic metadata to be consumed by the caller of ServiceController. For compatibility with the ext_authz interface.
292 #[serde(rename = "dynamicMetadata")]
293 pub dynamic_metadata: Option<HashMap<String, serde_json::Value>>,
294 /// Returns a set of request contexts generated from the `CheckRequest`.
295 pub headers: Option<HashMap<String, String>>,
296 /// Operation is allowed when this field is not set. Any non-'OK' status indicates a denial; google.rpc.Status.details would contain additional details about the denial.
297 pub status: Option<Status>,
298}
299
300impl common::ResponseResult for CheckResponse {}
301
302/// This message defines attributes associated with OAuth credentials.
303///
304/// This type is not used in any activity, and only used as *part* of another schema.
305///
306#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
307#[serde_with::serde_as]
308#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
309pub struct Oauth {
310 /// The optional OAuth client ID. This is the unique public identifier issued by an authorization server to a registered client application. Empty string is equivalent to no oauth client id. WARNING: This is for MCP tools/call and tools/list authorization and not for general use.
311 #[serde(rename = "clientId")]
312 pub client_id: Option<String>,
313}
314
315impl common::Part for Oauth {}
316
317/// This message defines attributes for a node that handles a network request. The node can be either a service or an application that sends, forwards, or receives the request. Service peers should fill in `principal` and `labels` as appropriate.
318///
319/// This type is not used in any activity, and only used as *part* of another schema.
320///
321#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
322#[serde_with::serde_as]
323#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
324pub struct Peer {
325 /// The IP address of the peer.
326 pub ip: Option<String>,
327 /// The labels associated with the peer.
328 pub labels: Option<HashMap<String, String>>,
329 /// The network port of the peer.
330 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
331 pub port: Option<i64>,
332 /// The identity of this peer. Similar to `Request.auth.principal`, but relative to the peer instead of the request. For example, the identity associated with a load balancer that forwarded the request.
333 pub principal: Option<String>,
334 /// The CLDR country/region code associated with the above IP address. If the IP address is private, the `region_code` should reflect the physical location where this peer is running.
335 #[serde(rename = "regionCode")]
336 pub region_code: Option<String>,
337}
338
339impl common::Part for Peer {}
340
341/// Request message for the Report method.
342///
343/// # Activities
344///
345/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
346/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
347///
348/// * [report services](ServiceReportCall) (request)
349#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
350#[serde_with::serde_as]
351#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
352pub struct ReportRequest {
353 /// Describes the list of operations to be reported. Each operation is represented as an AttributeContext, and contains all attributes around an API access.
354 pub operations: Option<Vec<AttributeContext>>,
355 /// Specifies the version of the service configuration that should be used to process the request. Must not be empty. Set this field to 'latest' to specify using the latest configuration.
356 #[serde(rename = "serviceConfigId")]
357 pub service_config_id: Option<String>,
358}
359
360impl common::RequestValue for ReportRequest {}
361
362/// Response message for the Report method.
363///
364/// # Activities
365///
366/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
367/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
368///
369/// * [report services](ServiceReportCall) (response)
370#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
371#[serde_with::serde_as]
372#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
373pub struct ReportResponse {
374 /// The extension field to store serialized OTel responses. e.g. ExportLogsServiceResponse, ExportMetricsServiceResponse.
375 pub extensions: Option<HashMap<String, serde_json::Value>>,
376}
377
378impl common::ResponseResult for ReportResponse {}
379
380/// This message defines attributes for an HTTP request. If the actual request is not an HTTP request, the runtime system should try to map the actual request to an equivalent HTTP request.
381///
382/// This type is not used in any activity, and only used as *part* of another schema.
383///
384#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
385#[serde_with::serde_as]
386#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
387pub struct Request {
388 /// The request authentication. May be absent for unauthenticated requests. Derived from the HTTP request `Authorization` header or equivalent.
389 pub auth: Option<Auth>,
390 /// The HTTP request headers. If multiple headers share the same key, they must be merged according to the HTTP spec. All header keys must be lowercased, because HTTP header keys are case-insensitive.
391 pub headers: Option<HashMap<String, String>>,
392 /// The HTTP request `Host` header value.
393 pub host: Option<String>,
394 /// The unique ID for a request, which can be propagated to downstream systems. The ID should have low probability of collision within a single day for a specific service.
395 pub id: Option<String>,
396 /// The HTTP request method, such as `GET`, `POST`.
397 pub method: Option<String>,
398 /// The values from Origin header from the HTTP request, such as "https://console.cloud.google.com". Modern browsers can only have one origin. Special browsers and/or HTTP clients may require multiple origins.
399 pub origin: Option<String>,
400 /// The HTTP URL path, excluding the query parameters.
401 pub path: Option<String>,
402 /// The network protocol used with the request, such as "http/1.1", "spdy/3", "h2", "h2c", "webrtc", "tcp", "udp", "quic". See https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids for details.
403 pub protocol: Option<String>,
404 /// The HTTP URL query in the format of `name1=value1&name2=value2`, as it appears in the first line of the HTTP request. No decoding is performed.
405 pub query: Option<String>,
406 /// A special parameter for request reason. It is used by security systems to associate auditing information with a request.
407 pub reason: Option<String>,
408 /// The HTTP URL scheme, such as `http` and `https`.
409 pub scheme: Option<String>,
410 /// The HTTP request size in bytes. If unknown, it must be -1.
411 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
412 pub size: Option<i64>,
413 /// The timestamp when the `destination` service receives the last byte of the request.
414 pub time: Option<chrono::DateTime<chrono::offset::Utc>>,
415}
416
417impl common::Part for Request {}
418
419/// This message defines core attributes for a resource. A resource is an addressable (named) entity provided by the destination service. For example, a file stored on a network storage service.
420///
421/// This type is not used in any activity, and only used as *part* of another schema.
422///
423#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
424#[serde_with::serde_as]
425#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
426pub struct Resource {
427 /// Annotations is an unstructured key-value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/
428 pub annotations: Option<HashMap<String, String>>,
429 /// Output only. The timestamp when the resource was created. This may be either the time creation was initiated or when it was completed.
430 #[serde(rename = "createTime")]
431 pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
432 /// Output only. The timestamp when the resource was deleted. If the resource is not deleted, this must be empty.
433 #[serde(rename = "deleteTime")]
434 pub delete_time: Option<chrono::DateTime<chrono::offset::Utc>>,
435 /// Mutable. The display name set by clients. Must be <= 63 characters.
436 #[serde(rename = "displayName")]
437 pub display_name: Option<String>,
438 /// Output only. An opaque value that uniquely identifies a version or generation of a resource. It can be used to confirm that the client and server agree on the ordering of a resource being written.
439 pub etag: Option<String>,
440 /// The labels or tags on the resource, such as AWS resource tags and Kubernetes resource labels.
441 pub labels: Option<HashMap<String, String>>,
442 /// Immutable. The location of the resource. The location encoding is specific to the service provider, and new encoding may be introduced as the service evolves. For Google Cloud products, the encoding is what is used by Google Cloud APIs, such as `us-east1`, `aws-us-east-1`, and `azure-eastus2`. The semantics of `location` is identical to the `cloud.googleapis.com/location` label used by some Google Cloud APIs.
443 pub location: Option<String>,
444 /// The stable identifier (name) of a resource on the `service`. A resource can be logically identified as "//{resource.service}/{resource.name}". The differences between a resource name and a URI are: * Resource name is a logical identifier, independent of network protocol and API version. For example, `//pubsub.googleapis.com/projects/123/topics/news-feed`. * URI often includes protocol and version information, so it can be used directly by applications. For example, `https://pubsub.googleapis.com/v1/projects/123/topics/news-feed`. See https://cloud.google.com/apis/design/resource_names for details.
445 pub name: Option<String>,
446 /// The name of the service that this resource belongs to, such as `pubsub.googleapis.com`. The service may be different from the DNS hostname that actually serves the request.
447 pub service: Option<String>,
448 /// The type of the resource. The syntax is platform-specific because different platforms define their resources differently. For Google APIs, the type format must be "{service}/{kind}", such as "pubsub.googleapis.com/Topic".
449 #[serde(rename = "type")]
450 pub type_: Option<String>,
451 /// The unique identifier of the resource. UID is unique in the time and space for this resource within the scope of the service. It is typically generated by the server on successful creation of a resource and must not be changed. UID is used to uniquely identify resources with resource name reuses. This should be a UUID4.
452 pub uid: Option<String>,
453 /// Output only. The timestamp when the resource was last updated. Any change to the resource made by users must refresh this value. Changes to a resource made by the service should refresh this value.
454 #[serde(rename = "updateTime")]
455 pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
456}
457
458impl common::Part for Resource {}
459
460/// Describes a resource referenced in the request.
461///
462/// This type is not used in any activity, and only used as *part* of another schema.
463///
464#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
465#[serde_with::serde_as]
466#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
467pub struct ResourceInfo {
468 /// Optional. The identifier of the container of this resource. For Google Cloud APIs, the resource container must be one of the following formats: - `projects/` - `folders/` - `organizations/` Required for the policy enforcement on the container level (e.g. VPCSC, Location Policy check, Org Policy check).
469 pub container: Option<String>,
470 /// Optional. The location of the resource, it must be a valid zone, region or multiregion, for example: "europe-west4", "northamerica-northeast1-a". Required for location policy check.
471 pub location: Option<String>,
472 /// The name of the resource referenced in the request.
473 pub name: Option<String>,
474 /// The resource permission needed for this request. The format must be "{service}/{plural}.{verb}".
475 pub permission: Option<String>,
476 /// The resource type in the format of "{service}/{kind}".
477 #[serde(rename = "type")]
478 pub type_: Option<String>,
479}
480
481impl common::Part for ResourceInfo {}
482
483/// This message defines attributes for a typical network response. It generally models semantics of an HTTP response.
484///
485/// This type is not used in any activity, and only used as *part* of another schema.
486///
487#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
488#[serde_with::serde_as]
489#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
490pub struct Response {
491 /// The amount of time it takes the backend service to fully respond to a request. Measured from when the destination service starts to send the request to the backend until when the destination service receives the complete response from the backend.
492 #[serde(rename = "backendLatency")]
493 #[serde_as(as = "Option<common::serde::duration::Wrapper>")]
494 pub backend_latency: Option<chrono::Duration>,
495 /// The HTTP response status code, such as `200` and `404`.
496 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
497 pub code: Option<i64>,
498 /// The HTTP response headers. If multiple headers share the same key, they must be merged according to HTTP spec. All header keys must be lowercased, because HTTP header keys are case-insensitive.
499 pub headers: Option<HashMap<String, String>>,
500 /// The HTTP response size in bytes. If unknown, it must be -1.
501 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
502 pub size: Option<i64>,
503 /// The timestamp when the `destination` service sends the last byte of the response.
504 pub time: Option<chrono::DateTime<chrono::offset::Utc>>,
505}
506
507impl common::Part for Response {}
508
509/// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
510///
511/// This type is not used in any activity, and only used as *part* of another schema.
512///
513#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
514#[serde_with::serde_as]
515#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
516pub struct Status {
517 /// The status code, which should be an enum value of google.rpc.Code.
518 pub code: Option<i32>,
519 /// A list of messages that carry the error details. There is a common set of message types for APIs to use.
520 pub details: Option<Vec<HashMap<String, serde_json::Value>>>,
521 /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
522 pub message: Option<String>,
523}
524
525impl common::Part for Status {}
526
527// ###################
528// MethodBuilders ###
529// #################
530
531/// A builder providing access to all methods supported on *service* resources.
532/// It is not used directly, but through the [`ServiceControl`] hub.
533///
534/// # Example
535///
536/// Instantiate a resource builder
537///
538/// ```test_harness,no_run
539/// extern crate hyper;
540/// extern crate hyper_rustls;
541/// extern crate google_servicecontrol2 as servicecontrol2;
542///
543/// # async fn dox() {
544/// use servicecontrol2::{ServiceControl, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
545///
546/// let secret: yup_oauth2::ApplicationSecret = Default::default();
547/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
548/// .with_native_roots()
549/// .unwrap()
550/// .https_only()
551/// .enable_http2()
552/// .build();
553///
554/// let executor = hyper_util::rt::TokioExecutor::new();
555/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
556/// secret,
557/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
558/// yup_oauth2::client::CustomHyperClientBuilder::from(
559/// hyper_util::client::legacy::Client::builder(executor).build(connector),
560/// ),
561/// ).build().await.unwrap();
562///
563/// let client = hyper_util::client::legacy::Client::builder(
564/// hyper_util::rt::TokioExecutor::new()
565/// )
566/// .build(
567/// hyper_rustls::HttpsConnectorBuilder::new()
568/// .with_native_roots()
569/// .unwrap()
570/// .https_or_http()
571/// .enable_http2()
572/// .build()
573/// );
574/// let mut hub = ServiceControl::new(client, auth);
575/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
576/// // like `check(...)` and `report(...)`
577/// // to build up your call.
578/// let rb = hub.services();
579/// # }
580/// ```
581pub struct ServiceMethods<'a, C>
582where
583 C: 'a,
584{
585 hub: &'a ServiceControl<C>,
586}
587
588impl<'a, C> common::MethodsBuilder for ServiceMethods<'a, C> {}
589
590impl<'a, C> ServiceMethods<'a, C> {
591 /// Create a builder to help you perform the following task:
592 ///
593 /// This method provides admission control for services that are integrated with [Service Infrastructure](https://cloud.google.com/service-infrastructure). It checks whether an operation should be allowed based on the service configuration and relevant policies. It must be called before the operation is executed. For more information, see [Admission Control](https://cloud.google.com/service-infrastructure/docs/admission-control). NOTE: The admission control has an expected policy propagation delay of 60s. The caller **must** not depend on the most recent policy changes. NOTE: The admission control has a hard limit of 1 referenced resources per call. If an operation refers to more than 1 resources, the caller must call the Check method multiple times. This method requires the `servicemanagement.services.check` permission on the specified service. For more information, see [Service Control API Access Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control).
594 ///
595 /// # Arguments
596 ///
597 /// * `request` - No description provided.
598 /// * `serviceName` - The service name as specified in its service configuration. For example, `"pubsub.googleapis.com"`. See [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) for the definition of a service name.
599 pub fn check(&self, request: CheckRequest, service_name: &str) -> ServiceCheckCall<'a, C> {
600 ServiceCheckCall {
601 hub: self.hub,
602 _request: request,
603 _service_name: service_name.to_string(),
604 _delegate: Default::default(),
605 _additional_params: Default::default(),
606 _scopes: Default::default(),
607 }
608 }
609
610 /// Create a builder to help you perform the following task:
611 ///
612 /// This method provides telemetry reporting for services that are integrated with [Service Infrastructure](https://cloud.google.com/service-infrastructure). It reports a list of operations that have occurred on a service. It must be called after the operations have been executed. For more information, see [Telemetry Reporting](https://cloud.google.com/service-infrastructure/docs/telemetry-reporting). NOTE: The telemetry reporting has a hard limit of 100 operations and 1MB per Report call. This method requires the `servicemanagement.services.report` permission on the specified service. For more information, see [Service Control API Access Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control).
613 ///
614 /// # Arguments
615 ///
616 /// * `request` - No description provided.
617 /// * `serviceName` - The service name as specified in its service configuration. For example, `"pubsub.googleapis.com"`. See [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) for the definition of a service name.
618 pub fn report(&self, request: ReportRequest, service_name: &str) -> ServiceReportCall<'a, C> {
619 ServiceReportCall {
620 hub: self.hub,
621 _request: request,
622 _service_name: service_name.to_string(),
623 _delegate: Default::default(),
624 _additional_params: Default::default(),
625 _scopes: Default::default(),
626 }
627 }
628}
629
630// ###################
631// CallBuilders ###
632// #################
633
634/// This method provides admission control for services that are integrated with [Service Infrastructure](https://cloud.google.com/service-infrastructure). It checks whether an operation should be allowed based on the service configuration and relevant policies. It must be called before the operation is executed. For more information, see [Admission Control](https://cloud.google.com/service-infrastructure/docs/admission-control). NOTE: The admission control has an expected policy propagation delay of 60s. The caller **must** not depend on the most recent policy changes. NOTE: The admission control has a hard limit of 1 referenced resources per call. If an operation refers to more than 1 resources, the caller must call the Check method multiple times. This method requires the `servicemanagement.services.check` permission on the specified service. For more information, see [Service Control API Access Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control).
635///
636/// A builder for the *check* method supported by a *service* resource.
637/// It is not used directly, but through a [`ServiceMethods`] instance.
638///
639/// # Example
640///
641/// Instantiate a resource method builder
642///
643/// ```test_harness,no_run
644/// # extern crate hyper;
645/// # extern crate hyper_rustls;
646/// # extern crate google_servicecontrol2 as servicecontrol2;
647/// use servicecontrol2::api::CheckRequest;
648/// # async fn dox() {
649/// # use servicecontrol2::{ServiceControl, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
650///
651/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
652/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
653/// # .with_native_roots()
654/// # .unwrap()
655/// # .https_only()
656/// # .enable_http2()
657/// # .build();
658///
659/// # let executor = hyper_util::rt::TokioExecutor::new();
660/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
661/// # secret,
662/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
663/// # yup_oauth2::client::CustomHyperClientBuilder::from(
664/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
665/// # ),
666/// # ).build().await.unwrap();
667///
668/// # let client = hyper_util::client::legacy::Client::builder(
669/// # hyper_util::rt::TokioExecutor::new()
670/// # )
671/// # .build(
672/// # hyper_rustls::HttpsConnectorBuilder::new()
673/// # .with_native_roots()
674/// # .unwrap()
675/// # .https_or_http()
676/// # .enable_http2()
677/// # .build()
678/// # );
679/// # let mut hub = ServiceControl::new(client, auth);
680/// // As the method needs a request, you would usually fill it with the desired information
681/// // into the respective structure. Some of the parts shown here might not be applicable !
682/// // Values shown here are possibly random and not representative !
683/// let mut req = CheckRequest::default();
684///
685/// // You can configure optional parameters by calling the respective setters at will, and
686/// // execute the final call using `doit()`.
687/// // Values shown here are possibly random and not representative !
688/// let result = hub.services().check(req, "serviceName")
689/// .doit().await;
690/// # }
691/// ```
692pub struct ServiceCheckCall<'a, C>
693where
694 C: 'a,
695{
696 hub: &'a ServiceControl<C>,
697 _request: CheckRequest,
698 _service_name: String,
699 _delegate: Option<&'a mut dyn common::Delegate>,
700 _additional_params: HashMap<String, String>,
701 _scopes: BTreeSet<String>,
702}
703
704impl<'a, C> common::CallBuilder for ServiceCheckCall<'a, C> {}
705
706impl<'a, C> ServiceCheckCall<'a, C>
707where
708 C: common::Connector,
709{
710 /// Perform the operation you have build so far.
711 pub async fn doit(mut self) -> common::Result<(common::Response, CheckResponse)> {
712 use std::borrow::Cow;
713 use std::io::{Read, Seek};
714
715 use common::{url::Params, ToParts};
716 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
717
718 let mut dd = common::DefaultDelegate;
719 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
720 dlg.begin(common::MethodInfo {
721 id: "servicecontrol.services.check",
722 http_method: hyper::Method::POST,
723 });
724
725 for &field in ["alt", "serviceName"].iter() {
726 if self._additional_params.contains_key(field) {
727 dlg.finished(false);
728 return Err(common::Error::FieldClash(field));
729 }
730 }
731
732 let mut params = Params::with_capacity(4 + self._additional_params.len());
733 params.push("serviceName", self._service_name);
734
735 params.extend(self._additional_params.iter());
736
737 params.push("alt", "json");
738 let mut url = self.hub._base_url.clone() + "v2/services/{serviceName}:check";
739 if self._scopes.is_empty() {
740 self._scopes
741 .insert(Scope::CloudPlatform.as_ref().to_string());
742 }
743
744 #[allow(clippy::single_element_loop)]
745 for &(find_this, param_name) in [("{serviceName}", "serviceName")].iter() {
746 url = params.uri_replacement(url, param_name, find_this, false);
747 }
748 {
749 let to_remove = ["serviceName"];
750 params.remove_params(&to_remove);
751 }
752
753 let url = params.parse_with_url(&url);
754
755 let mut json_mime_type = mime::APPLICATION_JSON;
756 let mut request_value_reader = {
757 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
758 common::remove_json_null_values(&mut value);
759 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
760 serde_json::to_writer(&mut dst, &value).unwrap();
761 dst
762 };
763 let request_size = request_value_reader
764 .seek(std::io::SeekFrom::End(0))
765 .unwrap();
766 request_value_reader
767 .seek(std::io::SeekFrom::Start(0))
768 .unwrap();
769
770 loop {
771 let token = match self
772 .hub
773 .auth
774 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
775 .await
776 {
777 Ok(token) => token,
778 Err(e) => match dlg.token(e) {
779 Ok(token) => token,
780 Err(e) => {
781 dlg.finished(false);
782 return Err(common::Error::MissingToken(e));
783 }
784 },
785 };
786 request_value_reader
787 .seek(std::io::SeekFrom::Start(0))
788 .unwrap();
789 let mut req_result = {
790 let client = &self.hub.client;
791 dlg.pre_request();
792 let mut req_builder = hyper::Request::builder()
793 .method(hyper::Method::POST)
794 .uri(url.as_str())
795 .header(USER_AGENT, self.hub._user_agent.clone());
796
797 if let Some(token) = token.as_ref() {
798 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
799 }
800
801 let request = req_builder
802 .header(CONTENT_TYPE, json_mime_type.to_string())
803 .header(CONTENT_LENGTH, request_size as u64)
804 .body(common::to_body(
805 request_value_reader.get_ref().clone().into(),
806 ));
807
808 client.request(request.unwrap()).await
809 };
810
811 match req_result {
812 Err(err) => {
813 if let common::Retry::After(d) = dlg.http_error(&err) {
814 sleep(d).await;
815 continue;
816 }
817 dlg.finished(false);
818 return Err(common::Error::HttpError(err));
819 }
820 Ok(res) => {
821 let (mut parts, body) = res.into_parts();
822 let mut body = common::Body::new(body);
823 if !parts.status.is_success() {
824 let bytes = common::to_bytes(body).await.unwrap_or_default();
825 let error = serde_json::from_str(&common::to_string(&bytes));
826 let response = common::to_response(parts, bytes.into());
827
828 if let common::Retry::After(d) =
829 dlg.http_failure(&response, error.as_ref().ok())
830 {
831 sleep(d).await;
832 continue;
833 }
834
835 dlg.finished(false);
836
837 return Err(match error {
838 Ok(value) => common::Error::BadRequest(value),
839 _ => common::Error::Failure(response),
840 });
841 }
842 let response = {
843 let bytes = common::to_bytes(body).await.unwrap_or_default();
844 let encoded = common::to_string(&bytes);
845 match serde_json::from_str(&encoded) {
846 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
847 Err(error) => {
848 dlg.response_json_decode_error(&encoded, &error);
849 return Err(common::Error::JsonDecodeError(
850 encoded.to_string(),
851 error,
852 ));
853 }
854 }
855 };
856
857 dlg.finished(true);
858 return Ok(response);
859 }
860 }
861 }
862 }
863
864 ///
865 /// Sets the *request* property to the given value.
866 ///
867 /// Even though the property as already been set when instantiating this call,
868 /// we provide this method for API completeness.
869 pub fn request(mut self, new_value: CheckRequest) -> ServiceCheckCall<'a, C> {
870 self._request = new_value;
871 self
872 }
873 /// The service name as specified in its service configuration. For example, `"pubsub.googleapis.com"`. See [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) for the definition of a service name.
874 ///
875 /// Sets the *service name* path property to the given value.
876 ///
877 /// Even though the property as already been set when instantiating this call,
878 /// we provide this method for API completeness.
879 pub fn service_name(mut self, new_value: &str) -> ServiceCheckCall<'a, C> {
880 self._service_name = new_value.to_string();
881 self
882 }
883 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
884 /// while executing the actual API request.
885 ///
886 /// ````text
887 /// It should be used to handle progress information, and to implement a certain level of resilience.
888 /// ````
889 ///
890 /// Sets the *delegate* property to the given value.
891 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ServiceCheckCall<'a, C> {
892 self._delegate = Some(new_value);
893 self
894 }
895
896 /// Set any additional parameter of the query string used in the request.
897 /// It should be used to set parameters which are not yet available through their own
898 /// setters.
899 ///
900 /// Please note that this method must not be used to set any of the known parameters
901 /// which have their own setter method. If done anyway, the request will fail.
902 ///
903 /// # Additional Parameters
904 ///
905 /// * *$.xgafv* (query-string) - V1 error format.
906 /// * *access_token* (query-string) - OAuth access token.
907 /// * *alt* (query-string) - Data format for response.
908 /// * *callback* (query-string) - JSONP
909 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
910 /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
911 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
912 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
913 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
914 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
915 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
916 pub fn param<T>(mut self, name: T, value: T) -> ServiceCheckCall<'a, C>
917 where
918 T: AsRef<str>,
919 {
920 self._additional_params
921 .insert(name.as_ref().to_string(), value.as_ref().to_string());
922 self
923 }
924
925 /// Identifies the authorization scope for the method you are building.
926 ///
927 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
928 /// [`Scope::CloudPlatform`].
929 ///
930 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
931 /// tokens for more than one scope.
932 ///
933 /// Usually there is more than one suitable scope to authorize an operation, some of which may
934 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
935 /// sufficient, a read-write scope will do as well.
936 pub fn add_scope<St>(mut self, scope: St) -> ServiceCheckCall<'a, C>
937 where
938 St: AsRef<str>,
939 {
940 self._scopes.insert(String::from(scope.as_ref()));
941 self
942 }
943 /// Identifies the authorization scope(s) for the method you are building.
944 ///
945 /// See [`Self::add_scope()`] for details.
946 pub fn add_scopes<I, St>(mut self, scopes: I) -> ServiceCheckCall<'a, C>
947 where
948 I: IntoIterator<Item = St>,
949 St: AsRef<str>,
950 {
951 self._scopes
952 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
953 self
954 }
955
956 /// Removes all scopes, and no default scope will be used either.
957 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
958 /// for details).
959 pub fn clear_scopes(mut self) -> ServiceCheckCall<'a, C> {
960 self._scopes.clear();
961 self
962 }
963}
964
965/// This method provides telemetry reporting for services that are integrated with [Service Infrastructure](https://cloud.google.com/service-infrastructure). It reports a list of operations that have occurred on a service. It must be called after the operations have been executed. For more information, see [Telemetry Reporting](https://cloud.google.com/service-infrastructure/docs/telemetry-reporting). NOTE: The telemetry reporting has a hard limit of 100 operations and 1MB per Report call. This method requires the `servicemanagement.services.report` permission on the specified service. For more information, see [Service Control API Access Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control).
966///
967/// A builder for the *report* method supported by a *service* resource.
968/// It is not used directly, but through a [`ServiceMethods`] instance.
969///
970/// # Example
971///
972/// Instantiate a resource method builder
973///
974/// ```test_harness,no_run
975/// # extern crate hyper;
976/// # extern crate hyper_rustls;
977/// # extern crate google_servicecontrol2 as servicecontrol2;
978/// use servicecontrol2::api::ReportRequest;
979/// # async fn dox() {
980/// # use servicecontrol2::{ServiceControl, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
981///
982/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
983/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
984/// # .with_native_roots()
985/// # .unwrap()
986/// # .https_only()
987/// # .enable_http2()
988/// # .build();
989///
990/// # let executor = hyper_util::rt::TokioExecutor::new();
991/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
992/// # secret,
993/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
994/// # yup_oauth2::client::CustomHyperClientBuilder::from(
995/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
996/// # ),
997/// # ).build().await.unwrap();
998///
999/// # let client = hyper_util::client::legacy::Client::builder(
1000/// # hyper_util::rt::TokioExecutor::new()
1001/// # )
1002/// # .build(
1003/// # hyper_rustls::HttpsConnectorBuilder::new()
1004/// # .with_native_roots()
1005/// # .unwrap()
1006/// # .https_or_http()
1007/// # .enable_http2()
1008/// # .build()
1009/// # );
1010/// # let mut hub = ServiceControl::new(client, auth);
1011/// // As the method needs a request, you would usually fill it with the desired information
1012/// // into the respective structure. Some of the parts shown here might not be applicable !
1013/// // Values shown here are possibly random and not representative !
1014/// let mut req = ReportRequest::default();
1015///
1016/// // You can configure optional parameters by calling the respective setters at will, and
1017/// // execute the final call using `doit()`.
1018/// // Values shown here are possibly random and not representative !
1019/// let result = hub.services().report(req, "serviceName")
1020/// .doit().await;
1021/// # }
1022/// ```
1023pub struct ServiceReportCall<'a, C>
1024where
1025 C: 'a,
1026{
1027 hub: &'a ServiceControl<C>,
1028 _request: ReportRequest,
1029 _service_name: String,
1030 _delegate: Option<&'a mut dyn common::Delegate>,
1031 _additional_params: HashMap<String, String>,
1032 _scopes: BTreeSet<String>,
1033}
1034
1035impl<'a, C> common::CallBuilder for ServiceReportCall<'a, C> {}
1036
1037impl<'a, C> ServiceReportCall<'a, C>
1038where
1039 C: common::Connector,
1040{
1041 /// Perform the operation you have build so far.
1042 pub async fn doit(mut self) -> common::Result<(common::Response, ReportResponse)> {
1043 use std::borrow::Cow;
1044 use std::io::{Read, Seek};
1045
1046 use common::{url::Params, ToParts};
1047 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1048
1049 let mut dd = common::DefaultDelegate;
1050 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1051 dlg.begin(common::MethodInfo {
1052 id: "servicecontrol.services.report",
1053 http_method: hyper::Method::POST,
1054 });
1055
1056 for &field in ["alt", "serviceName"].iter() {
1057 if self._additional_params.contains_key(field) {
1058 dlg.finished(false);
1059 return Err(common::Error::FieldClash(field));
1060 }
1061 }
1062
1063 let mut params = Params::with_capacity(4 + self._additional_params.len());
1064 params.push("serviceName", self._service_name);
1065
1066 params.extend(self._additional_params.iter());
1067
1068 params.push("alt", "json");
1069 let mut url = self.hub._base_url.clone() + "v2/services/{serviceName}:report";
1070 if self._scopes.is_empty() {
1071 self._scopes
1072 .insert(Scope::CloudPlatform.as_ref().to_string());
1073 }
1074
1075 #[allow(clippy::single_element_loop)]
1076 for &(find_this, param_name) in [("{serviceName}", "serviceName")].iter() {
1077 url = params.uri_replacement(url, param_name, find_this, false);
1078 }
1079 {
1080 let to_remove = ["serviceName"];
1081 params.remove_params(&to_remove);
1082 }
1083
1084 let url = params.parse_with_url(&url);
1085
1086 let mut json_mime_type = mime::APPLICATION_JSON;
1087 let mut request_value_reader = {
1088 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1089 common::remove_json_null_values(&mut value);
1090 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1091 serde_json::to_writer(&mut dst, &value).unwrap();
1092 dst
1093 };
1094 let request_size = request_value_reader
1095 .seek(std::io::SeekFrom::End(0))
1096 .unwrap();
1097 request_value_reader
1098 .seek(std::io::SeekFrom::Start(0))
1099 .unwrap();
1100
1101 loop {
1102 let token = match self
1103 .hub
1104 .auth
1105 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1106 .await
1107 {
1108 Ok(token) => token,
1109 Err(e) => match dlg.token(e) {
1110 Ok(token) => token,
1111 Err(e) => {
1112 dlg.finished(false);
1113 return Err(common::Error::MissingToken(e));
1114 }
1115 },
1116 };
1117 request_value_reader
1118 .seek(std::io::SeekFrom::Start(0))
1119 .unwrap();
1120 let mut req_result = {
1121 let client = &self.hub.client;
1122 dlg.pre_request();
1123 let mut req_builder = hyper::Request::builder()
1124 .method(hyper::Method::POST)
1125 .uri(url.as_str())
1126 .header(USER_AGENT, self.hub._user_agent.clone());
1127
1128 if let Some(token) = token.as_ref() {
1129 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1130 }
1131
1132 let request = req_builder
1133 .header(CONTENT_TYPE, json_mime_type.to_string())
1134 .header(CONTENT_LENGTH, request_size as u64)
1135 .body(common::to_body(
1136 request_value_reader.get_ref().clone().into(),
1137 ));
1138
1139 client.request(request.unwrap()).await
1140 };
1141
1142 match req_result {
1143 Err(err) => {
1144 if let common::Retry::After(d) = dlg.http_error(&err) {
1145 sleep(d).await;
1146 continue;
1147 }
1148 dlg.finished(false);
1149 return Err(common::Error::HttpError(err));
1150 }
1151 Ok(res) => {
1152 let (mut parts, body) = res.into_parts();
1153 let mut body = common::Body::new(body);
1154 if !parts.status.is_success() {
1155 let bytes = common::to_bytes(body).await.unwrap_or_default();
1156 let error = serde_json::from_str(&common::to_string(&bytes));
1157 let response = common::to_response(parts, bytes.into());
1158
1159 if let common::Retry::After(d) =
1160 dlg.http_failure(&response, error.as_ref().ok())
1161 {
1162 sleep(d).await;
1163 continue;
1164 }
1165
1166 dlg.finished(false);
1167
1168 return Err(match error {
1169 Ok(value) => common::Error::BadRequest(value),
1170 _ => common::Error::Failure(response),
1171 });
1172 }
1173 let response = {
1174 let bytes = common::to_bytes(body).await.unwrap_or_default();
1175 let encoded = common::to_string(&bytes);
1176 match serde_json::from_str(&encoded) {
1177 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1178 Err(error) => {
1179 dlg.response_json_decode_error(&encoded, &error);
1180 return Err(common::Error::JsonDecodeError(
1181 encoded.to_string(),
1182 error,
1183 ));
1184 }
1185 }
1186 };
1187
1188 dlg.finished(true);
1189 return Ok(response);
1190 }
1191 }
1192 }
1193 }
1194
1195 ///
1196 /// Sets the *request* property to the given value.
1197 ///
1198 /// Even though the property as already been set when instantiating this call,
1199 /// we provide this method for API completeness.
1200 pub fn request(mut self, new_value: ReportRequest) -> ServiceReportCall<'a, C> {
1201 self._request = new_value;
1202 self
1203 }
1204 /// The service name as specified in its service configuration. For example, `"pubsub.googleapis.com"`. See [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) for the definition of a service name.
1205 ///
1206 /// Sets the *service name* path property to the given value.
1207 ///
1208 /// Even though the property as already been set when instantiating this call,
1209 /// we provide this method for API completeness.
1210 pub fn service_name(mut self, new_value: &str) -> ServiceReportCall<'a, C> {
1211 self._service_name = new_value.to_string();
1212 self
1213 }
1214 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1215 /// while executing the actual API request.
1216 ///
1217 /// ````text
1218 /// It should be used to handle progress information, and to implement a certain level of resilience.
1219 /// ````
1220 ///
1221 /// Sets the *delegate* property to the given value.
1222 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ServiceReportCall<'a, C> {
1223 self._delegate = Some(new_value);
1224 self
1225 }
1226
1227 /// Set any additional parameter of the query string used in the request.
1228 /// It should be used to set parameters which are not yet available through their own
1229 /// setters.
1230 ///
1231 /// Please note that this method must not be used to set any of the known parameters
1232 /// which have their own setter method. If done anyway, the request will fail.
1233 ///
1234 /// # Additional Parameters
1235 ///
1236 /// * *$.xgafv* (query-string) - V1 error format.
1237 /// * *access_token* (query-string) - OAuth access token.
1238 /// * *alt* (query-string) - Data format for response.
1239 /// * *callback* (query-string) - JSONP
1240 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1241 /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1242 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1243 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1244 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1245 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1246 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1247 pub fn param<T>(mut self, name: T, value: T) -> ServiceReportCall<'a, C>
1248 where
1249 T: AsRef<str>,
1250 {
1251 self._additional_params
1252 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1253 self
1254 }
1255
1256 /// Identifies the authorization scope for the method you are building.
1257 ///
1258 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1259 /// [`Scope::CloudPlatform`].
1260 ///
1261 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1262 /// tokens for more than one scope.
1263 ///
1264 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1265 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1266 /// sufficient, a read-write scope will do as well.
1267 pub fn add_scope<St>(mut self, scope: St) -> ServiceReportCall<'a, C>
1268 where
1269 St: AsRef<str>,
1270 {
1271 self._scopes.insert(String::from(scope.as_ref()));
1272 self
1273 }
1274 /// Identifies the authorization scope(s) for the method you are building.
1275 ///
1276 /// See [`Self::add_scope()`] for details.
1277 pub fn add_scopes<I, St>(mut self, scopes: I) -> ServiceReportCall<'a, C>
1278 where
1279 I: IntoIterator<Item = St>,
1280 St: AsRef<str>,
1281 {
1282 self._scopes
1283 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1284 self
1285 }
1286
1287 /// Removes all scopes, and no default scope will be used either.
1288 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1289 /// for details).
1290 pub fn clear_scopes(mut self) -> ServiceReportCall<'a, C> {
1291 self._scopes.clear();
1292 self
1293 }
1294}