google_cloudprofiler2/
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    /// View and write monitoring data for all of your Google and third-party Cloud and API projects
20    Monitoring,
21
22    /// Publish metric data to your Google Cloud projects
23    MonitoringWrite,
24}
25
26impl AsRef<str> for Scope {
27    fn as_ref(&self) -> &str {
28        match *self {
29            Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
30            Scope::Monitoring => "https://www.googleapis.com/auth/monitoring",
31            Scope::MonitoringWrite => "https://www.googleapis.com/auth/monitoring.write",
32        }
33    }
34}
35
36#[allow(clippy::derivable_impls)]
37impl Default for Scope {
38    fn default() -> Scope {
39        Scope::Monitoring
40    }
41}
42
43// ########
44// HUB ###
45// ######
46
47/// Central instance to access all CloudProfiler related resource activities
48///
49/// # Examples
50///
51/// Instantiate a new hub
52///
53/// ```test_harness,no_run
54/// extern crate hyper;
55/// extern crate hyper_rustls;
56/// extern crate google_cloudprofiler2 as cloudprofiler2;
57/// use cloudprofiler2::api::Profile;
58/// use cloudprofiler2::{Result, Error};
59/// # async fn dox() {
60/// use cloudprofiler2::{CloudProfiler, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
61///
62/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
63/// // `client_secret`, among other things.
64/// let secret: yup_oauth2::ApplicationSecret = Default::default();
65/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
66/// // unless you replace  `None` with the desired Flow.
67/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
68/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
69/// // retrieve them from storage.
70/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
71///     secret,
72///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
73/// ).build().await.unwrap();
74///
75/// let client = hyper_util::client::legacy::Client::builder(
76///     hyper_util::rt::TokioExecutor::new()
77/// )
78/// .build(
79///     hyper_rustls::HttpsConnectorBuilder::new()
80///         .with_native_roots()
81///         .unwrap()
82///         .https_or_http()
83///         .enable_http1()
84///         .build()
85/// );
86/// let mut hub = CloudProfiler::new(client, auth);
87/// // As the method needs a request, you would usually fill it with the desired information
88/// // into the respective structure. Some of the parts shown here might not be applicable !
89/// // Values shown here are possibly random and not representative !
90/// let mut req = Profile::default();
91///
92/// // You can configure optional parameters by calling the respective setters at will, and
93/// // execute the final call using `doit()`.
94/// // Values shown here are possibly random and not representative !
95/// let result = hub.projects().profiles_patch(req, "name")
96///              .update_mask(FieldMask::new::<&str>(&[]))
97///              .doit().await;
98///
99/// match result {
100///     Err(e) => match e {
101///         // The Error enum provides details about what exactly happened.
102///         // You can also just use its `Debug`, `Display` or `Error` traits
103///          Error::HttpError(_)
104///         |Error::Io(_)
105///         |Error::MissingAPIKey
106///         |Error::MissingToken(_)
107///         |Error::Cancelled
108///         |Error::UploadSizeLimitExceeded(_, _)
109///         |Error::Failure(_)
110///         |Error::BadRequest(_)
111///         |Error::FieldClash(_)
112///         |Error::JsonDecodeError(_, _) => println!("{}", e),
113///     },
114///     Ok(res) => println!("Success: {:?}", res),
115/// }
116/// # }
117/// ```
118#[derive(Clone)]
119pub struct CloudProfiler<C> {
120    pub client: common::Client<C>,
121    pub auth: Box<dyn common::GetToken>,
122    _user_agent: String,
123    _base_url: String,
124    _root_url: String,
125}
126
127impl<C> common::Hub for CloudProfiler<C> {}
128
129impl<'a, C> CloudProfiler<C> {
130    pub fn new<A: 'static + common::GetToken>(
131        client: common::Client<C>,
132        auth: A,
133    ) -> CloudProfiler<C> {
134        CloudProfiler {
135            client,
136            auth: Box::new(auth),
137            _user_agent: "google-api-rust-client/6.0.0".to_string(),
138            _base_url: "https://cloudprofiler.googleapis.com/".to_string(),
139            _root_url: "https://cloudprofiler.googleapis.com/".to_string(),
140        }
141    }
142
143    pub fn projects(&'a self) -> ProjectMethods<'a, C> {
144        ProjectMethods { hub: self }
145    }
146
147    /// Set the user-agent header field to use in all requests to the server.
148    /// It defaults to `google-api-rust-client/6.0.0`.
149    ///
150    /// Returns the previously set user-agent.
151    pub fn user_agent(&mut self, agent_name: String) -> String {
152        std::mem::replace(&mut self._user_agent, agent_name)
153    }
154
155    /// Set the base url to use in all requests to the server.
156    /// It defaults to `https://cloudprofiler.googleapis.com/`.
157    ///
158    /// Returns the previously set base url.
159    pub fn base_url(&mut self, new_base_url: String) -> String {
160        std::mem::replace(&mut self._base_url, new_base_url)
161    }
162
163    /// Set the root url to use in all requests to the server.
164    /// It defaults to `https://cloudprofiler.googleapis.com/`.
165    ///
166    /// Returns the previously set root url.
167    pub fn root_url(&mut self, new_root_url: String) -> String {
168        std::mem::replace(&mut self._root_url, new_root_url)
169    }
170}
171
172// ############
173// SCHEMAS ###
174// ##########
175/// CreateProfileRequest describes a profile resource online creation request. The deployment field must be populated. The profile_type specifies the list of profile types supported by the agent. The creation call will hang until a profile of one of these types needs to be collected.
176///
177/// # Activities
178///
179/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
180/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
181///
182/// * [profiles create projects](ProjectProfileCreateCall) (request)
183#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
184#[serde_with::serde_as]
185#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
186pub struct CreateProfileRequest {
187    /// Deployment details.
188    pub deployment: Option<Deployment>,
189    /// One or more profile types that the agent is capable of providing.
190    #[serde(rename = "profileType")]
191    pub profile_type: Option<Vec<String>>,
192}
193
194impl common::RequestValue for CreateProfileRequest {}
195
196/// Deployment contains the deployment identification information.
197///
198/// This type is not used in any activity, and only used as *part* of another schema.
199///
200#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
201#[serde_with::serde_as]
202#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
203pub struct Deployment {
204    /// Labels identify the deployment within the user universe and same target. Validation regex for label names: `^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`. Value for an individual label must be \<= 512 bytes, the total size of all label names and values must be \<= 1024 bytes. Label named “language” can be used to record the programming language of the profiled deployment. The standard choices for the value include “java”, “go”, “python”, “ruby”, “nodejs”, “php”, “dotnet”. For deployments running on Google Cloud Platform, “zone” or “region” label should be present describing the deployment location. An example of a zone is “us-central1-a”, an example of a region is “us-central1” or “us-central”.
205    pub labels: Option<HashMap<String, String>>,
206    /// Project ID is the ID of a cloud project. Validation regex: `^a-z{4,61}[a-z0-9]$`.
207    #[serde(rename = "projectId")]
208    pub project_id: Option<String>,
209    /// Target is the service name used to group related deployments: * Service name for App Engine Flex / Standard. * Cluster and container name for GKE. * User-specified string for direct Compute Engine profiling (e.g. Java). * Job name for Dataflow. Validation regex: `^[a-z0-9]([-a-z0-9_.]{0,253}[a-z0-9])?$`.
210    pub target: Option<String>,
211}
212
213impl common::Part for Deployment {}
214
215/// ListProfileResponse contains the list of collected profiles for deployments in projects which the user has permissions to view.
216///
217/// # Activities
218///
219/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
220/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
221///
222/// * [profiles list projects](ProjectProfileListCall) (response)
223#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
224#[serde_with::serde_as]
225#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
226pub struct ListProfilesResponse {
227    /// Token to receive the next page of results. This field maybe empty if there are no more profiles to fetch.
228    #[serde(rename = "nextPageToken")]
229    pub next_page_token: Option<String>,
230    /// List of profiles fetched.
231    pub profiles: Option<Vec<Profile>>,
232    /// Number of profiles that were skipped in the current page since they were not able to be fetched successfully. This should typically be zero. A non-zero value may indicate a transient failure, in which case if the number is too high for your use case, the call may be retried.
233    #[serde(rename = "skippedProfiles")]
234    pub skipped_profiles: Option<i32>,
235}
236
237impl common::ResponseResult for ListProfilesResponse {}
238
239/// Profile resource.
240///
241/// # Activities
242///
243/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
244/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
245///
246/// * [profiles create projects](ProjectProfileCreateCall) (response)
247/// * [profiles create offline projects](ProjectProfileCreateOfflineCall) (request|response)
248/// * [profiles patch projects](ProjectProfilePatchCall) (request|response)
249#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
250#[serde_with::serde_as]
251#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
252pub struct Profile {
253    /// Deployment this profile corresponds to.
254    pub deployment: Option<Deployment>,
255    /// Duration of the profiling session. Input (for the offline mode) or output (for the online mode). The field represents requested profiling duration. It may slightly differ from the effective profiling duration, which is recorded in the profile data, in case the profiling can't be stopped immediately (e.g. in case stopping the profiling is handled asynchronously).
256    #[serde_as(as = "Option<common::serde::duration::Wrapper>")]
257    pub duration: Option<chrono::Duration>,
258    /// Input only. Labels associated to this specific profile. These labels will get merged with the deployment labels for the final data set. See documentation on deployment labels for validation rules and limits.
259    pub labels: Option<HashMap<String, String>>,
260    /// Output only. Opaque, server-assigned, unique ID for this profile.
261    pub name: Option<String>,
262    /// Input only. Profile bytes, as a gzip compressed serialized proto, the format is https://github.com/google/pprof/blob/master/proto/profile.proto.
263    #[serde(rename = "profileBytes")]
264    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
265    pub profile_bytes: Option<Vec<u8>>,
266    /// Type of profile. For offline mode, this must be specified when creating the profile. For online mode it is assigned and returned by the server.
267    #[serde(rename = "profileType")]
268    pub profile_type: Option<String>,
269    /// Output only. Start time for the profile. This output is only present in response from the ListProfiles method.
270    #[serde(rename = "startTime")]
271    pub start_time: Option<chrono::DateTime<chrono::offset::Utc>>,
272}
273
274impl common::RequestValue for Profile {}
275impl common::ResponseResult for Profile {}
276
277// ###################
278// MethodBuilders ###
279// #################
280
281/// A builder providing access to all methods supported on *project* resources.
282/// It is not used directly, but through the [`CloudProfiler`] hub.
283///
284/// # Example
285///
286/// Instantiate a resource builder
287///
288/// ```test_harness,no_run
289/// extern crate hyper;
290/// extern crate hyper_rustls;
291/// extern crate google_cloudprofiler2 as cloudprofiler2;
292///
293/// # async fn dox() {
294/// use cloudprofiler2::{CloudProfiler, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
295///
296/// let secret: yup_oauth2::ApplicationSecret = Default::default();
297/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
298///     secret,
299///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
300/// ).build().await.unwrap();
301///
302/// let client = hyper_util::client::legacy::Client::builder(
303///     hyper_util::rt::TokioExecutor::new()
304/// )
305/// .build(
306///     hyper_rustls::HttpsConnectorBuilder::new()
307///         .with_native_roots()
308///         .unwrap()
309///         .https_or_http()
310///         .enable_http1()
311///         .build()
312/// );
313/// let mut hub = CloudProfiler::new(client, auth);
314/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
315/// // like `profiles_create(...)`, `profiles_create_offline(...)`, `profiles_list(...)` and `profiles_patch(...)`
316/// // to build up your call.
317/// let rb = hub.projects();
318/// # }
319/// ```
320pub struct ProjectMethods<'a, C>
321where
322    C: 'a,
323{
324    hub: &'a CloudProfiler<C>,
325}
326
327impl<'a, C> common::MethodsBuilder for ProjectMethods<'a, C> {}
328
329impl<'a, C> ProjectMethods<'a, C> {
330    /// Create a builder to help you perform the following task:
331    ///
332    /// CreateProfile creates a new profile resource in the online mode. _Direct use of this API is discouraged, please use a [supported profiler agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) instead for profile collection._ The server ensures that the new profiles are created at a constant rate per deployment, so the creation request may hang for some time until the next profile session is available. The request may fail with ABORTED error if the creation is not available within ~1m, the response will indicate the duration of the backoff the client should take before attempting creating a profile again. The backoff duration is returned in google.rpc.RetryInfo extension on the response status. To a gRPC client, the extension will be return as a binary-serialized proto in the trailing metadata item named "google.rpc.retryinfo-bin".
333    ///
334    /// # Arguments
335    ///
336    /// * `request` - No description provided.
337    /// * `parent` - Parent project to create the profile in.
338    pub fn profiles_create(
339        &self,
340        request: CreateProfileRequest,
341        parent: &str,
342    ) -> ProjectProfileCreateCall<'a, C> {
343        ProjectProfileCreateCall {
344            hub: self.hub,
345            _request: request,
346            _parent: parent.to_string(),
347            _delegate: Default::default(),
348            _additional_params: Default::default(),
349            _scopes: Default::default(),
350        }
351    }
352
353    /// Create a builder to help you perform the following task:
354    ///
355    /// CreateOfflineProfile creates a new profile resource in the offline mode. The client provides the profile to create along with the profile bytes, the server records it. _Direct use of this API is discouraged, please use a [supported profiler agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) instead for profile collection._
356    ///
357    /// # Arguments
358    ///
359    /// * `request` - No description provided.
360    /// * `parent` - Parent project to create the profile in.
361    pub fn profiles_create_offline(
362        &self,
363        request: Profile,
364        parent: &str,
365    ) -> ProjectProfileCreateOfflineCall<'a, C> {
366        ProjectProfileCreateOfflineCall {
367            hub: self.hub,
368            _request: request,
369            _parent: parent.to_string(),
370            _delegate: Default::default(),
371            _additional_params: Default::default(),
372            _scopes: Default::default(),
373        }
374    }
375
376    /// Create a builder to help you perform the following task:
377    ///
378    /// Lists profiles which have been collected so far and for which the caller has permission to view.
379    ///
380    /// # Arguments
381    ///
382    /// * `parent` - Required. The parent, which owns this collection of profiles. Format: projects/{user_project_id}
383    pub fn profiles_list(&self, parent: &str) -> ProjectProfileListCall<'a, C> {
384        ProjectProfileListCall {
385            hub: self.hub,
386            _parent: parent.to_string(),
387            _page_token: Default::default(),
388            _page_size: Default::default(),
389            _delegate: Default::default(),
390            _additional_params: Default::default(),
391            _scopes: Default::default(),
392        }
393    }
394
395    /// Create a builder to help you perform the following task:
396    ///
397    /// UpdateProfile updates the profile bytes and labels on the profile resource created in the online mode. Updating the bytes for profiles created in the offline mode is currently not supported: the profile content must be provided at the time of the profile creation. _Direct use of this API is discouraged, please use a [supported profiler agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) instead for profile collection._
398    ///
399    /// # Arguments
400    ///
401    /// * `request` - No description provided.
402    /// * `name` - Output only. Opaque, server-assigned, unique ID for this profile.
403    pub fn profiles_patch(&self, request: Profile, name: &str) -> ProjectProfilePatchCall<'a, C> {
404        ProjectProfilePatchCall {
405            hub: self.hub,
406            _request: request,
407            _name: name.to_string(),
408            _update_mask: Default::default(),
409            _delegate: Default::default(),
410            _additional_params: Default::default(),
411            _scopes: Default::default(),
412        }
413    }
414}
415
416// ###################
417// CallBuilders   ###
418// #################
419
420/// CreateProfile creates a new profile resource in the online mode. _Direct use of this API is discouraged, please use a [supported profiler agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) instead for profile collection._ The server ensures that the new profiles are created at a constant rate per deployment, so the creation request may hang for some time until the next profile session is available. The request may fail with ABORTED error if the creation is not available within ~1m, the response will indicate the duration of the backoff the client should take before attempting creating a profile again. The backoff duration is returned in google.rpc.RetryInfo extension on the response status. To a gRPC client, the extension will be return as a binary-serialized proto in the trailing metadata item named "google.rpc.retryinfo-bin".
421///
422/// A builder for the *profiles.create* method supported by a *project* resource.
423/// It is not used directly, but through a [`ProjectMethods`] instance.
424///
425/// # Example
426///
427/// Instantiate a resource method builder
428///
429/// ```test_harness,no_run
430/// # extern crate hyper;
431/// # extern crate hyper_rustls;
432/// # extern crate google_cloudprofiler2 as cloudprofiler2;
433/// use cloudprofiler2::api::CreateProfileRequest;
434/// # async fn dox() {
435/// # use cloudprofiler2::{CloudProfiler, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
436///
437/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
438/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
439/// #     secret,
440/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
441/// # ).build().await.unwrap();
442///
443/// # let client = hyper_util::client::legacy::Client::builder(
444/// #     hyper_util::rt::TokioExecutor::new()
445/// # )
446/// # .build(
447/// #     hyper_rustls::HttpsConnectorBuilder::new()
448/// #         .with_native_roots()
449/// #         .unwrap()
450/// #         .https_or_http()
451/// #         .enable_http1()
452/// #         .build()
453/// # );
454/// # let mut hub = CloudProfiler::new(client, auth);
455/// // As the method needs a request, you would usually fill it with the desired information
456/// // into the respective structure. Some of the parts shown here might not be applicable !
457/// // Values shown here are possibly random and not representative !
458/// let mut req = CreateProfileRequest::default();
459///
460/// // You can configure optional parameters by calling the respective setters at will, and
461/// // execute the final call using `doit()`.
462/// // Values shown here are possibly random and not representative !
463/// let result = hub.projects().profiles_create(req, "parent")
464///              .doit().await;
465/// # }
466/// ```
467pub struct ProjectProfileCreateCall<'a, C>
468where
469    C: 'a,
470{
471    hub: &'a CloudProfiler<C>,
472    _request: CreateProfileRequest,
473    _parent: String,
474    _delegate: Option<&'a mut dyn common::Delegate>,
475    _additional_params: HashMap<String, String>,
476    _scopes: BTreeSet<String>,
477}
478
479impl<'a, C> common::CallBuilder for ProjectProfileCreateCall<'a, C> {}
480
481impl<'a, C> ProjectProfileCreateCall<'a, C>
482where
483    C: common::Connector,
484{
485    /// Perform the operation you have build so far.
486    pub async fn doit(mut self) -> common::Result<(common::Response, Profile)> {
487        use std::borrow::Cow;
488        use std::io::{Read, Seek};
489
490        use common::{url::Params, ToParts};
491        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
492
493        let mut dd = common::DefaultDelegate;
494        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
495        dlg.begin(common::MethodInfo {
496            id: "cloudprofiler.projects.profiles.create",
497            http_method: hyper::Method::POST,
498        });
499
500        for &field in ["alt", "parent"].iter() {
501            if self._additional_params.contains_key(field) {
502                dlg.finished(false);
503                return Err(common::Error::FieldClash(field));
504            }
505        }
506
507        let mut params = Params::with_capacity(4 + self._additional_params.len());
508        params.push("parent", self._parent);
509
510        params.extend(self._additional_params.iter());
511
512        params.push("alt", "json");
513        let mut url = self.hub._base_url.clone() + "v2/{+parent}/profiles";
514        if self._scopes.is_empty() {
515            self._scopes
516                .insert(Scope::CloudPlatform.as_ref().to_string());
517        }
518
519        #[allow(clippy::single_element_loop)]
520        for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
521            url = params.uri_replacement(url, param_name, find_this, true);
522        }
523        {
524            let to_remove = ["parent"];
525            params.remove_params(&to_remove);
526        }
527
528        let url = params.parse_with_url(&url);
529
530        let mut json_mime_type = mime::APPLICATION_JSON;
531        let mut request_value_reader = {
532            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
533            common::remove_json_null_values(&mut value);
534            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
535            serde_json::to_writer(&mut dst, &value).unwrap();
536            dst
537        };
538        let request_size = request_value_reader
539            .seek(std::io::SeekFrom::End(0))
540            .unwrap();
541        request_value_reader
542            .seek(std::io::SeekFrom::Start(0))
543            .unwrap();
544
545        loop {
546            let token = match self
547                .hub
548                .auth
549                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
550                .await
551            {
552                Ok(token) => token,
553                Err(e) => match dlg.token(e) {
554                    Ok(token) => token,
555                    Err(e) => {
556                        dlg.finished(false);
557                        return Err(common::Error::MissingToken(e));
558                    }
559                },
560            };
561            request_value_reader
562                .seek(std::io::SeekFrom::Start(0))
563                .unwrap();
564            let mut req_result = {
565                let client = &self.hub.client;
566                dlg.pre_request();
567                let mut req_builder = hyper::Request::builder()
568                    .method(hyper::Method::POST)
569                    .uri(url.as_str())
570                    .header(USER_AGENT, self.hub._user_agent.clone());
571
572                if let Some(token) = token.as_ref() {
573                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
574                }
575
576                let request = req_builder
577                    .header(CONTENT_TYPE, json_mime_type.to_string())
578                    .header(CONTENT_LENGTH, request_size as u64)
579                    .body(common::to_body(
580                        request_value_reader.get_ref().clone().into(),
581                    ));
582
583                client.request(request.unwrap()).await
584            };
585
586            match req_result {
587                Err(err) => {
588                    if let common::Retry::After(d) = dlg.http_error(&err) {
589                        sleep(d).await;
590                        continue;
591                    }
592                    dlg.finished(false);
593                    return Err(common::Error::HttpError(err));
594                }
595                Ok(res) => {
596                    let (mut parts, body) = res.into_parts();
597                    let mut body = common::Body::new(body);
598                    if !parts.status.is_success() {
599                        let bytes = common::to_bytes(body).await.unwrap_or_default();
600                        let error = serde_json::from_str(&common::to_string(&bytes));
601                        let response = common::to_response(parts, bytes.into());
602
603                        if let common::Retry::After(d) =
604                            dlg.http_failure(&response, error.as_ref().ok())
605                        {
606                            sleep(d).await;
607                            continue;
608                        }
609
610                        dlg.finished(false);
611
612                        return Err(match error {
613                            Ok(value) => common::Error::BadRequest(value),
614                            _ => common::Error::Failure(response),
615                        });
616                    }
617                    let response = {
618                        let bytes = common::to_bytes(body).await.unwrap_or_default();
619                        let encoded = common::to_string(&bytes);
620                        match serde_json::from_str(&encoded) {
621                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
622                            Err(error) => {
623                                dlg.response_json_decode_error(&encoded, &error);
624                                return Err(common::Error::JsonDecodeError(
625                                    encoded.to_string(),
626                                    error,
627                                ));
628                            }
629                        }
630                    };
631
632                    dlg.finished(true);
633                    return Ok(response);
634                }
635            }
636        }
637    }
638
639    ///
640    /// Sets the *request* property to the given value.
641    ///
642    /// Even though the property as already been set when instantiating this call,
643    /// we provide this method for API completeness.
644    pub fn request(mut self, new_value: CreateProfileRequest) -> ProjectProfileCreateCall<'a, C> {
645        self._request = new_value;
646        self
647    }
648    /// Parent project to create the profile in.
649    ///
650    /// Sets the *parent* path property to the given value.
651    ///
652    /// Even though the property as already been set when instantiating this call,
653    /// we provide this method for API completeness.
654    pub fn parent(mut self, new_value: &str) -> ProjectProfileCreateCall<'a, C> {
655        self._parent = new_value.to_string();
656        self
657    }
658    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
659    /// while executing the actual API request.
660    ///
661    /// ````text
662    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
663    /// ````
664    ///
665    /// Sets the *delegate* property to the given value.
666    pub fn delegate(
667        mut self,
668        new_value: &'a mut dyn common::Delegate,
669    ) -> ProjectProfileCreateCall<'a, C> {
670        self._delegate = Some(new_value);
671        self
672    }
673
674    /// Set any additional parameter of the query string used in the request.
675    /// It should be used to set parameters which are not yet available through their own
676    /// setters.
677    ///
678    /// Please note that this method must not be used to set any of the known parameters
679    /// which have their own setter method. If done anyway, the request will fail.
680    ///
681    /// # Additional Parameters
682    ///
683    /// * *$.xgafv* (query-string) - V1 error format.
684    /// * *access_token* (query-string) - OAuth access token.
685    /// * *alt* (query-string) - Data format for response.
686    /// * *callback* (query-string) - JSONP
687    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
688    /// * *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.
689    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
690    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
691    /// * *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.
692    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
693    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
694    pub fn param<T>(mut self, name: T, value: T) -> ProjectProfileCreateCall<'a, C>
695    where
696        T: AsRef<str>,
697    {
698        self._additional_params
699            .insert(name.as_ref().to_string(), value.as_ref().to_string());
700        self
701    }
702
703    /// Identifies the authorization scope for the method you are building.
704    ///
705    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
706    /// [`Scope::CloudPlatform`].
707    ///
708    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
709    /// tokens for more than one scope.
710    ///
711    /// Usually there is more than one suitable scope to authorize an operation, some of which may
712    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
713    /// sufficient, a read-write scope will do as well.
714    pub fn add_scope<St>(mut self, scope: St) -> ProjectProfileCreateCall<'a, C>
715    where
716        St: AsRef<str>,
717    {
718        self._scopes.insert(String::from(scope.as_ref()));
719        self
720    }
721    /// Identifies the authorization scope(s) for the method you are building.
722    ///
723    /// See [`Self::add_scope()`] for details.
724    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectProfileCreateCall<'a, C>
725    where
726        I: IntoIterator<Item = St>,
727        St: AsRef<str>,
728    {
729        self._scopes
730            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
731        self
732    }
733
734    /// Removes all scopes, and no default scope will be used either.
735    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
736    /// for details).
737    pub fn clear_scopes(mut self) -> ProjectProfileCreateCall<'a, C> {
738        self._scopes.clear();
739        self
740    }
741}
742
743/// CreateOfflineProfile creates a new profile resource in the offline mode. The client provides the profile to create along with the profile bytes, the server records it. _Direct use of this API is discouraged, please use a [supported profiler agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) instead for profile collection._
744///
745/// A builder for the *profiles.createOffline* method supported by a *project* resource.
746/// It is not used directly, but through a [`ProjectMethods`] instance.
747///
748/// # Example
749///
750/// Instantiate a resource method builder
751///
752/// ```test_harness,no_run
753/// # extern crate hyper;
754/// # extern crate hyper_rustls;
755/// # extern crate google_cloudprofiler2 as cloudprofiler2;
756/// use cloudprofiler2::api::Profile;
757/// # async fn dox() {
758/// # use cloudprofiler2::{CloudProfiler, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
759///
760/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
761/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
762/// #     secret,
763/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
764/// # ).build().await.unwrap();
765///
766/// # let client = hyper_util::client::legacy::Client::builder(
767/// #     hyper_util::rt::TokioExecutor::new()
768/// # )
769/// # .build(
770/// #     hyper_rustls::HttpsConnectorBuilder::new()
771/// #         .with_native_roots()
772/// #         .unwrap()
773/// #         .https_or_http()
774/// #         .enable_http1()
775/// #         .build()
776/// # );
777/// # let mut hub = CloudProfiler::new(client, auth);
778/// // As the method needs a request, you would usually fill it with the desired information
779/// // into the respective structure. Some of the parts shown here might not be applicable !
780/// // Values shown here are possibly random and not representative !
781/// let mut req = Profile::default();
782///
783/// // You can configure optional parameters by calling the respective setters at will, and
784/// // execute the final call using `doit()`.
785/// // Values shown here are possibly random and not representative !
786/// let result = hub.projects().profiles_create_offline(req, "parent")
787///              .doit().await;
788/// # }
789/// ```
790pub struct ProjectProfileCreateOfflineCall<'a, C>
791where
792    C: 'a,
793{
794    hub: &'a CloudProfiler<C>,
795    _request: Profile,
796    _parent: String,
797    _delegate: Option<&'a mut dyn common::Delegate>,
798    _additional_params: HashMap<String, String>,
799    _scopes: BTreeSet<String>,
800}
801
802impl<'a, C> common::CallBuilder for ProjectProfileCreateOfflineCall<'a, C> {}
803
804impl<'a, C> ProjectProfileCreateOfflineCall<'a, C>
805where
806    C: common::Connector,
807{
808    /// Perform the operation you have build so far.
809    pub async fn doit(mut self) -> common::Result<(common::Response, Profile)> {
810        use std::borrow::Cow;
811        use std::io::{Read, Seek};
812
813        use common::{url::Params, ToParts};
814        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
815
816        let mut dd = common::DefaultDelegate;
817        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
818        dlg.begin(common::MethodInfo {
819            id: "cloudprofiler.projects.profiles.createOffline",
820            http_method: hyper::Method::POST,
821        });
822
823        for &field in ["alt", "parent"].iter() {
824            if self._additional_params.contains_key(field) {
825                dlg.finished(false);
826                return Err(common::Error::FieldClash(field));
827            }
828        }
829
830        let mut params = Params::with_capacity(4 + self._additional_params.len());
831        params.push("parent", self._parent);
832
833        params.extend(self._additional_params.iter());
834
835        params.push("alt", "json");
836        let mut url = self.hub._base_url.clone() + "v2/{+parent}/profiles:createOffline";
837        if self._scopes.is_empty() {
838            self._scopes
839                .insert(Scope::CloudPlatform.as_ref().to_string());
840        }
841
842        #[allow(clippy::single_element_loop)]
843        for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
844            url = params.uri_replacement(url, param_name, find_this, true);
845        }
846        {
847            let to_remove = ["parent"];
848            params.remove_params(&to_remove);
849        }
850
851        let url = params.parse_with_url(&url);
852
853        let mut json_mime_type = mime::APPLICATION_JSON;
854        let mut request_value_reader = {
855            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
856            common::remove_json_null_values(&mut value);
857            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
858            serde_json::to_writer(&mut dst, &value).unwrap();
859            dst
860        };
861        let request_size = request_value_reader
862            .seek(std::io::SeekFrom::End(0))
863            .unwrap();
864        request_value_reader
865            .seek(std::io::SeekFrom::Start(0))
866            .unwrap();
867
868        loop {
869            let token = match self
870                .hub
871                .auth
872                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
873                .await
874            {
875                Ok(token) => token,
876                Err(e) => match dlg.token(e) {
877                    Ok(token) => token,
878                    Err(e) => {
879                        dlg.finished(false);
880                        return Err(common::Error::MissingToken(e));
881                    }
882                },
883            };
884            request_value_reader
885                .seek(std::io::SeekFrom::Start(0))
886                .unwrap();
887            let mut req_result = {
888                let client = &self.hub.client;
889                dlg.pre_request();
890                let mut req_builder = hyper::Request::builder()
891                    .method(hyper::Method::POST)
892                    .uri(url.as_str())
893                    .header(USER_AGENT, self.hub._user_agent.clone());
894
895                if let Some(token) = token.as_ref() {
896                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
897                }
898
899                let request = req_builder
900                    .header(CONTENT_TYPE, json_mime_type.to_string())
901                    .header(CONTENT_LENGTH, request_size as u64)
902                    .body(common::to_body(
903                        request_value_reader.get_ref().clone().into(),
904                    ));
905
906                client.request(request.unwrap()).await
907            };
908
909            match req_result {
910                Err(err) => {
911                    if let common::Retry::After(d) = dlg.http_error(&err) {
912                        sleep(d).await;
913                        continue;
914                    }
915                    dlg.finished(false);
916                    return Err(common::Error::HttpError(err));
917                }
918                Ok(res) => {
919                    let (mut parts, body) = res.into_parts();
920                    let mut body = common::Body::new(body);
921                    if !parts.status.is_success() {
922                        let bytes = common::to_bytes(body).await.unwrap_or_default();
923                        let error = serde_json::from_str(&common::to_string(&bytes));
924                        let response = common::to_response(parts, bytes.into());
925
926                        if let common::Retry::After(d) =
927                            dlg.http_failure(&response, error.as_ref().ok())
928                        {
929                            sleep(d).await;
930                            continue;
931                        }
932
933                        dlg.finished(false);
934
935                        return Err(match error {
936                            Ok(value) => common::Error::BadRequest(value),
937                            _ => common::Error::Failure(response),
938                        });
939                    }
940                    let response = {
941                        let bytes = common::to_bytes(body).await.unwrap_or_default();
942                        let encoded = common::to_string(&bytes);
943                        match serde_json::from_str(&encoded) {
944                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
945                            Err(error) => {
946                                dlg.response_json_decode_error(&encoded, &error);
947                                return Err(common::Error::JsonDecodeError(
948                                    encoded.to_string(),
949                                    error,
950                                ));
951                            }
952                        }
953                    };
954
955                    dlg.finished(true);
956                    return Ok(response);
957                }
958            }
959        }
960    }
961
962    ///
963    /// Sets the *request* property to the given value.
964    ///
965    /// Even though the property as already been set when instantiating this call,
966    /// we provide this method for API completeness.
967    pub fn request(mut self, new_value: Profile) -> ProjectProfileCreateOfflineCall<'a, C> {
968        self._request = new_value;
969        self
970    }
971    /// Parent project to create the profile in.
972    ///
973    /// Sets the *parent* path property to the given value.
974    ///
975    /// Even though the property as already been set when instantiating this call,
976    /// we provide this method for API completeness.
977    pub fn parent(mut self, new_value: &str) -> ProjectProfileCreateOfflineCall<'a, C> {
978        self._parent = new_value.to_string();
979        self
980    }
981    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
982    /// while executing the actual API request.
983    ///
984    /// ````text
985    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
986    /// ````
987    ///
988    /// Sets the *delegate* property to the given value.
989    pub fn delegate(
990        mut self,
991        new_value: &'a mut dyn common::Delegate,
992    ) -> ProjectProfileCreateOfflineCall<'a, C> {
993        self._delegate = Some(new_value);
994        self
995    }
996
997    /// Set any additional parameter of the query string used in the request.
998    /// It should be used to set parameters which are not yet available through their own
999    /// setters.
1000    ///
1001    /// Please note that this method must not be used to set any of the known parameters
1002    /// which have their own setter method. If done anyway, the request will fail.
1003    ///
1004    /// # Additional Parameters
1005    ///
1006    /// * *$.xgafv* (query-string) - V1 error format.
1007    /// * *access_token* (query-string) - OAuth access token.
1008    /// * *alt* (query-string) - Data format for response.
1009    /// * *callback* (query-string) - JSONP
1010    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1011    /// * *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.
1012    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1013    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1014    /// * *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.
1015    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1016    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1017    pub fn param<T>(mut self, name: T, value: T) -> ProjectProfileCreateOfflineCall<'a, C>
1018    where
1019        T: AsRef<str>,
1020    {
1021        self._additional_params
1022            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1023        self
1024    }
1025
1026    /// Identifies the authorization scope for the method you are building.
1027    ///
1028    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1029    /// [`Scope::CloudPlatform`].
1030    ///
1031    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1032    /// tokens for more than one scope.
1033    ///
1034    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1035    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1036    /// sufficient, a read-write scope will do as well.
1037    pub fn add_scope<St>(mut self, scope: St) -> ProjectProfileCreateOfflineCall<'a, C>
1038    where
1039        St: AsRef<str>,
1040    {
1041        self._scopes.insert(String::from(scope.as_ref()));
1042        self
1043    }
1044    /// Identifies the authorization scope(s) for the method you are building.
1045    ///
1046    /// See [`Self::add_scope()`] for details.
1047    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectProfileCreateOfflineCall<'a, C>
1048    where
1049        I: IntoIterator<Item = St>,
1050        St: AsRef<str>,
1051    {
1052        self._scopes
1053            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1054        self
1055    }
1056
1057    /// Removes all scopes, and no default scope will be used either.
1058    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1059    /// for details).
1060    pub fn clear_scopes(mut self) -> ProjectProfileCreateOfflineCall<'a, C> {
1061        self._scopes.clear();
1062        self
1063    }
1064}
1065
1066/// Lists profiles which have been collected so far and for which the caller has permission to view.
1067///
1068/// A builder for the *profiles.list* method supported by a *project* resource.
1069/// It is not used directly, but through a [`ProjectMethods`] instance.
1070///
1071/// # Example
1072///
1073/// Instantiate a resource method builder
1074///
1075/// ```test_harness,no_run
1076/// # extern crate hyper;
1077/// # extern crate hyper_rustls;
1078/// # extern crate google_cloudprofiler2 as cloudprofiler2;
1079/// # async fn dox() {
1080/// # use cloudprofiler2::{CloudProfiler, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1081///
1082/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1083/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1084/// #     secret,
1085/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1086/// # ).build().await.unwrap();
1087///
1088/// # let client = hyper_util::client::legacy::Client::builder(
1089/// #     hyper_util::rt::TokioExecutor::new()
1090/// # )
1091/// # .build(
1092/// #     hyper_rustls::HttpsConnectorBuilder::new()
1093/// #         .with_native_roots()
1094/// #         .unwrap()
1095/// #         .https_or_http()
1096/// #         .enable_http1()
1097/// #         .build()
1098/// # );
1099/// # let mut hub = CloudProfiler::new(client, auth);
1100/// // You can configure optional parameters by calling the respective setters at will, and
1101/// // execute the final call using `doit()`.
1102/// // Values shown here are possibly random and not representative !
1103/// let result = hub.projects().profiles_list("parent")
1104///              .page_token("sanctus")
1105///              .page_size(-80)
1106///              .doit().await;
1107/// # }
1108/// ```
1109pub struct ProjectProfileListCall<'a, C>
1110where
1111    C: 'a,
1112{
1113    hub: &'a CloudProfiler<C>,
1114    _parent: String,
1115    _page_token: Option<String>,
1116    _page_size: Option<i32>,
1117    _delegate: Option<&'a mut dyn common::Delegate>,
1118    _additional_params: HashMap<String, String>,
1119    _scopes: BTreeSet<String>,
1120}
1121
1122impl<'a, C> common::CallBuilder for ProjectProfileListCall<'a, C> {}
1123
1124impl<'a, C> ProjectProfileListCall<'a, C>
1125where
1126    C: common::Connector,
1127{
1128    /// Perform the operation you have build so far.
1129    pub async fn doit(mut self) -> common::Result<(common::Response, ListProfilesResponse)> {
1130        use std::borrow::Cow;
1131        use std::io::{Read, Seek};
1132
1133        use common::{url::Params, ToParts};
1134        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1135
1136        let mut dd = common::DefaultDelegate;
1137        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1138        dlg.begin(common::MethodInfo {
1139            id: "cloudprofiler.projects.profiles.list",
1140            http_method: hyper::Method::GET,
1141        });
1142
1143        for &field in ["alt", "parent", "pageToken", "pageSize"].iter() {
1144            if self._additional_params.contains_key(field) {
1145                dlg.finished(false);
1146                return Err(common::Error::FieldClash(field));
1147            }
1148        }
1149
1150        let mut params = Params::with_capacity(5 + self._additional_params.len());
1151        params.push("parent", self._parent);
1152        if let Some(value) = self._page_token.as_ref() {
1153            params.push("pageToken", value);
1154        }
1155        if let Some(value) = self._page_size.as_ref() {
1156            params.push("pageSize", value.to_string());
1157        }
1158
1159        params.extend(self._additional_params.iter());
1160
1161        params.push("alt", "json");
1162        let mut url = self.hub._base_url.clone() + "v2/{+parent}/profiles";
1163        if self._scopes.is_empty() {
1164            self._scopes
1165                .insert(Scope::CloudPlatform.as_ref().to_string());
1166        }
1167
1168        #[allow(clippy::single_element_loop)]
1169        for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
1170            url = params.uri_replacement(url, param_name, find_this, true);
1171        }
1172        {
1173            let to_remove = ["parent"];
1174            params.remove_params(&to_remove);
1175        }
1176
1177        let url = params.parse_with_url(&url);
1178
1179        loop {
1180            let token = match self
1181                .hub
1182                .auth
1183                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1184                .await
1185            {
1186                Ok(token) => token,
1187                Err(e) => match dlg.token(e) {
1188                    Ok(token) => token,
1189                    Err(e) => {
1190                        dlg.finished(false);
1191                        return Err(common::Error::MissingToken(e));
1192                    }
1193                },
1194            };
1195            let mut req_result = {
1196                let client = &self.hub.client;
1197                dlg.pre_request();
1198                let mut req_builder = hyper::Request::builder()
1199                    .method(hyper::Method::GET)
1200                    .uri(url.as_str())
1201                    .header(USER_AGENT, self.hub._user_agent.clone());
1202
1203                if let Some(token) = token.as_ref() {
1204                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1205                }
1206
1207                let request = req_builder
1208                    .header(CONTENT_LENGTH, 0_u64)
1209                    .body(common::to_body::<String>(None));
1210
1211                client.request(request.unwrap()).await
1212            };
1213
1214            match req_result {
1215                Err(err) => {
1216                    if let common::Retry::After(d) = dlg.http_error(&err) {
1217                        sleep(d).await;
1218                        continue;
1219                    }
1220                    dlg.finished(false);
1221                    return Err(common::Error::HttpError(err));
1222                }
1223                Ok(res) => {
1224                    let (mut parts, body) = res.into_parts();
1225                    let mut body = common::Body::new(body);
1226                    if !parts.status.is_success() {
1227                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1228                        let error = serde_json::from_str(&common::to_string(&bytes));
1229                        let response = common::to_response(parts, bytes.into());
1230
1231                        if let common::Retry::After(d) =
1232                            dlg.http_failure(&response, error.as_ref().ok())
1233                        {
1234                            sleep(d).await;
1235                            continue;
1236                        }
1237
1238                        dlg.finished(false);
1239
1240                        return Err(match error {
1241                            Ok(value) => common::Error::BadRequest(value),
1242                            _ => common::Error::Failure(response),
1243                        });
1244                    }
1245                    let response = {
1246                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1247                        let encoded = common::to_string(&bytes);
1248                        match serde_json::from_str(&encoded) {
1249                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1250                            Err(error) => {
1251                                dlg.response_json_decode_error(&encoded, &error);
1252                                return Err(common::Error::JsonDecodeError(
1253                                    encoded.to_string(),
1254                                    error,
1255                                ));
1256                            }
1257                        }
1258                    };
1259
1260                    dlg.finished(true);
1261                    return Ok(response);
1262                }
1263            }
1264        }
1265    }
1266
1267    /// Required. The parent, which owns this collection of profiles. Format: projects/{user_project_id}
1268    ///
1269    /// Sets the *parent* path property to the given value.
1270    ///
1271    /// Even though the property as already been set when instantiating this call,
1272    /// we provide this method for API completeness.
1273    pub fn parent(mut self, new_value: &str) -> ProjectProfileListCall<'a, C> {
1274        self._parent = new_value.to_string();
1275        self
1276    }
1277    /// Optional. The token to continue pagination and get profiles from a particular page. When paginating, all other parameters provided to `ListProfiles` must match the call that provided the page token.
1278    ///
1279    /// Sets the *page token* query property to the given value.
1280    pub fn page_token(mut self, new_value: &str) -> ProjectProfileListCall<'a, C> {
1281        self._page_token = Some(new_value.to_string());
1282        self
1283    }
1284    /// Optional. The maximum number of items to return. Default page_size is 1000. Max limit is 1000.
1285    ///
1286    /// Sets the *page size* query property to the given value.
1287    pub fn page_size(mut self, new_value: i32) -> ProjectProfileListCall<'a, C> {
1288        self._page_size = Some(new_value);
1289        self
1290    }
1291    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1292    /// while executing the actual API request.
1293    ///
1294    /// ````text
1295    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1296    /// ````
1297    ///
1298    /// Sets the *delegate* property to the given value.
1299    pub fn delegate(
1300        mut self,
1301        new_value: &'a mut dyn common::Delegate,
1302    ) -> ProjectProfileListCall<'a, C> {
1303        self._delegate = Some(new_value);
1304        self
1305    }
1306
1307    /// Set any additional parameter of the query string used in the request.
1308    /// It should be used to set parameters which are not yet available through their own
1309    /// setters.
1310    ///
1311    /// Please note that this method must not be used to set any of the known parameters
1312    /// which have their own setter method. If done anyway, the request will fail.
1313    ///
1314    /// # Additional Parameters
1315    ///
1316    /// * *$.xgafv* (query-string) - V1 error format.
1317    /// * *access_token* (query-string) - OAuth access token.
1318    /// * *alt* (query-string) - Data format for response.
1319    /// * *callback* (query-string) - JSONP
1320    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1321    /// * *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.
1322    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1323    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1324    /// * *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.
1325    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1326    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1327    pub fn param<T>(mut self, name: T, value: T) -> ProjectProfileListCall<'a, C>
1328    where
1329        T: AsRef<str>,
1330    {
1331        self._additional_params
1332            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1333        self
1334    }
1335
1336    /// Identifies the authorization scope for the method you are building.
1337    ///
1338    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1339    /// [`Scope::CloudPlatform`].
1340    ///
1341    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1342    /// tokens for more than one scope.
1343    ///
1344    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1345    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1346    /// sufficient, a read-write scope will do as well.
1347    pub fn add_scope<St>(mut self, scope: St) -> ProjectProfileListCall<'a, C>
1348    where
1349        St: AsRef<str>,
1350    {
1351        self._scopes.insert(String::from(scope.as_ref()));
1352        self
1353    }
1354    /// Identifies the authorization scope(s) for the method you are building.
1355    ///
1356    /// See [`Self::add_scope()`] for details.
1357    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectProfileListCall<'a, C>
1358    where
1359        I: IntoIterator<Item = St>,
1360        St: AsRef<str>,
1361    {
1362        self._scopes
1363            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1364        self
1365    }
1366
1367    /// Removes all scopes, and no default scope will be used either.
1368    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1369    /// for details).
1370    pub fn clear_scopes(mut self) -> ProjectProfileListCall<'a, C> {
1371        self._scopes.clear();
1372        self
1373    }
1374}
1375
1376/// UpdateProfile updates the profile bytes and labels on the profile resource created in the online mode. Updating the bytes for profiles created in the offline mode is currently not supported: the profile content must be provided at the time of the profile creation. _Direct use of this API is discouraged, please use a [supported profiler agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) instead for profile collection._
1377///
1378/// A builder for the *profiles.patch* method supported by a *project* resource.
1379/// It is not used directly, but through a [`ProjectMethods`] instance.
1380///
1381/// # Example
1382///
1383/// Instantiate a resource method builder
1384///
1385/// ```test_harness,no_run
1386/// # extern crate hyper;
1387/// # extern crate hyper_rustls;
1388/// # extern crate google_cloudprofiler2 as cloudprofiler2;
1389/// use cloudprofiler2::api::Profile;
1390/// # async fn dox() {
1391/// # use cloudprofiler2::{CloudProfiler, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1392///
1393/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1394/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1395/// #     secret,
1396/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1397/// # ).build().await.unwrap();
1398///
1399/// # let client = hyper_util::client::legacy::Client::builder(
1400/// #     hyper_util::rt::TokioExecutor::new()
1401/// # )
1402/// # .build(
1403/// #     hyper_rustls::HttpsConnectorBuilder::new()
1404/// #         .with_native_roots()
1405/// #         .unwrap()
1406/// #         .https_or_http()
1407/// #         .enable_http1()
1408/// #         .build()
1409/// # );
1410/// # let mut hub = CloudProfiler::new(client, auth);
1411/// // As the method needs a request, you would usually fill it with the desired information
1412/// // into the respective structure. Some of the parts shown here might not be applicable !
1413/// // Values shown here are possibly random and not representative !
1414/// let mut req = Profile::default();
1415///
1416/// // You can configure optional parameters by calling the respective setters at will, and
1417/// // execute the final call using `doit()`.
1418/// // Values shown here are possibly random and not representative !
1419/// let result = hub.projects().profiles_patch(req, "name")
1420///              .update_mask(FieldMask::new::<&str>(&[]))
1421///              .doit().await;
1422/// # }
1423/// ```
1424pub struct ProjectProfilePatchCall<'a, C>
1425where
1426    C: 'a,
1427{
1428    hub: &'a CloudProfiler<C>,
1429    _request: Profile,
1430    _name: String,
1431    _update_mask: Option<common::FieldMask>,
1432    _delegate: Option<&'a mut dyn common::Delegate>,
1433    _additional_params: HashMap<String, String>,
1434    _scopes: BTreeSet<String>,
1435}
1436
1437impl<'a, C> common::CallBuilder for ProjectProfilePatchCall<'a, C> {}
1438
1439impl<'a, C> ProjectProfilePatchCall<'a, C>
1440where
1441    C: common::Connector,
1442{
1443    /// Perform the operation you have build so far.
1444    pub async fn doit(mut self) -> common::Result<(common::Response, Profile)> {
1445        use std::borrow::Cow;
1446        use std::io::{Read, Seek};
1447
1448        use common::{url::Params, ToParts};
1449        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1450
1451        let mut dd = common::DefaultDelegate;
1452        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1453        dlg.begin(common::MethodInfo {
1454            id: "cloudprofiler.projects.profiles.patch",
1455            http_method: hyper::Method::PATCH,
1456        });
1457
1458        for &field in ["alt", "name", "updateMask"].iter() {
1459            if self._additional_params.contains_key(field) {
1460                dlg.finished(false);
1461                return Err(common::Error::FieldClash(field));
1462            }
1463        }
1464
1465        let mut params = Params::with_capacity(5 + self._additional_params.len());
1466        params.push("name", self._name);
1467        if let Some(value) = self._update_mask.as_ref() {
1468            params.push("updateMask", value.to_string());
1469        }
1470
1471        params.extend(self._additional_params.iter());
1472
1473        params.push("alt", "json");
1474        let mut url = self.hub._base_url.clone() + "v2/{+name}";
1475        if self._scopes.is_empty() {
1476            self._scopes
1477                .insert(Scope::CloudPlatform.as_ref().to_string());
1478        }
1479
1480        #[allow(clippy::single_element_loop)]
1481        for &(find_this, param_name) in [("{+name}", "name")].iter() {
1482            url = params.uri_replacement(url, param_name, find_this, true);
1483        }
1484        {
1485            let to_remove = ["name"];
1486            params.remove_params(&to_remove);
1487        }
1488
1489        let url = params.parse_with_url(&url);
1490
1491        let mut json_mime_type = mime::APPLICATION_JSON;
1492        let mut request_value_reader = {
1493            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1494            common::remove_json_null_values(&mut value);
1495            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1496            serde_json::to_writer(&mut dst, &value).unwrap();
1497            dst
1498        };
1499        let request_size = request_value_reader
1500            .seek(std::io::SeekFrom::End(0))
1501            .unwrap();
1502        request_value_reader
1503            .seek(std::io::SeekFrom::Start(0))
1504            .unwrap();
1505
1506        loop {
1507            let token = match self
1508                .hub
1509                .auth
1510                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1511                .await
1512            {
1513                Ok(token) => token,
1514                Err(e) => match dlg.token(e) {
1515                    Ok(token) => token,
1516                    Err(e) => {
1517                        dlg.finished(false);
1518                        return Err(common::Error::MissingToken(e));
1519                    }
1520                },
1521            };
1522            request_value_reader
1523                .seek(std::io::SeekFrom::Start(0))
1524                .unwrap();
1525            let mut req_result = {
1526                let client = &self.hub.client;
1527                dlg.pre_request();
1528                let mut req_builder = hyper::Request::builder()
1529                    .method(hyper::Method::PATCH)
1530                    .uri(url.as_str())
1531                    .header(USER_AGENT, self.hub._user_agent.clone());
1532
1533                if let Some(token) = token.as_ref() {
1534                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1535                }
1536
1537                let request = req_builder
1538                    .header(CONTENT_TYPE, json_mime_type.to_string())
1539                    .header(CONTENT_LENGTH, request_size as u64)
1540                    .body(common::to_body(
1541                        request_value_reader.get_ref().clone().into(),
1542                    ));
1543
1544                client.request(request.unwrap()).await
1545            };
1546
1547            match req_result {
1548                Err(err) => {
1549                    if let common::Retry::After(d) = dlg.http_error(&err) {
1550                        sleep(d).await;
1551                        continue;
1552                    }
1553                    dlg.finished(false);
1554                    return Err(common::Error::HttpError(err));
1555                }
1556                Ok(res) => {
1557                    let (mut parts, body) = res.into_parts();
1558                    let mut body = common::Body::new(body);
1559                    if !parts.status.is_success() {
1560                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1561                        let error = serde_json::from_str(&common::to_string(&bytes));
1562                        let response = common::to_response(parts, bytes.into());
1563
1564                        if let common::Retry::After(d) =
1565                            dlg.http_failure(&response, error.as_ref().ok())
1566                        {
1567                            sleep(d).await;
1568                            continue;
1569                        }
1570
1571                        dlg.finished(false);
1572
1573                        return Err(match error {
1574                            Ok(value) => common::Error::BadRequest(value),
1575                            _ => common::Error::Failure(response),
1576                        });
1577                    }
1578                    let response = {
1579                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1580                        let encoded = common::to_string(&bytes);
1581                        match serde_json::from_str(&encoded) {
1582                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1583                            Err(error) => {
1584                                dlg.response_json_decode_error(&encoded, &error);
1585                                return Err(common::Error::JsonDecodeError(
1586                                    encoded.to_string(),
1587                                    error,
1588                                ));
1589                            }
1590                        }
1591                    };
1592
1593                    dlg.finished(true);
1594                    return Ok(response);
1595                }
1596            }
1597        }
1598    }
1599
1600    ///
1601    /// Sets the *request* property to the given value.
1602    ///
1603    /// Even though the property as already been set when instantiating this call,
1604    /// we provide this method for API completeness.
1605    pub fn request(mut self, new_value: Profile) -> ProjectProfilePatchCall<'a, C> {
1606        self._request = new_value;
1607        self
1608    }
1609    /// Output only. Opaque, server-assigned, unique ID for this profile.
1610    ///
1611    /// Sets the *name* path property to the given value.
1612    ///
1613    /// Even though the property as already been set when instantiating this call,
1614    /// we provide this method for API completeness.
1615    pub fn name(mut self, new_value: &str) -> ProjectProfilePatchCall<'a, C> {
1616        self._name = new_value.to_string();
1617        self
1618    }
1619    /// Field mask used to specify the fields to be overwritten. Currently only profile_bytes and labels fields are supported by UpdateProfile, so only those fields can be specified in the mask. When no mask is provided, all fields are overwritten.
1620    ///
1621    /// Sets the *update mask* query property to the given value.
1622    pub fn update_mask(mut self, new_value: common::FieldMask) -> ProjectProfilePatchCall<'a, C> {
1623        self._update_mask = Some(new_value);
1624        self
1625    }
1626    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1627    /// while executing the actual API request.
1628    ///
1629    /// ````text
1630    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1631    /// ````
1632    ///
1633    /// Sets the *delegate* property to the given value.
1634    pub fn delegate(
1635        mut self,
1636        new_value: &'a mut dyn common::Delegate,
1637    ) -> ProjectProfilePatchCall<'a, C> {
1638        self._delegate = Some(new_value);
1639        self
1640    }
1641
1642    /// Set any additional parameter of the query string used in the request.
1643    /// It should be used to set parameters which are not yet available through their own
1644    /// setters.
1645    ///
1646    /// Please note that this method must not be used to set any of the known parameters
1647    /// which have their own setter method. If done anyway, the request will fail.
1648    ///
1649    /// # Additional Parameters
1650    ///
1651    /// * *$.xgafv* (query-string) - V1 error format.
1652    /// * *access_token* (query-string) - OAuth access token.
1653    /// * *alt* (query-string) - Data format for response.
1654    /// * *callback* (query-string) - JSONP
1655    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1656    /// * *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.
1657    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1658    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1659    /// * *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.
1660    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1661    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1662    pub fn param<T>(mut self, name: T, value: T) -> ProjectProfilePatchCall<'a, C>
1663    where
1664        T: AsRef<str>,
1665    {
1666        self._additional_params
1667            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1668        self
1669    }
1670
1671    /// Identifies the authorization scope for the method you are building.
1672    ///
1673    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1674    /// [`Scope::CloudPlatform`].
1675    ///
1676    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1677    /// tokens for more than one scope.
1678    ///
1679    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1680    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1681    /// sufficient, a read-write scope will do as well.
1682    pub fn add_scope<St>(mut self, scope: St) -> ProjectProfilePatchCall<'a, C>
1683    where
1684        St: AsRef<str>,
1685    {
1686        self._scopes.insert(String::from(scope.as_ref()));
1687        self
1688    }
1689    /// Identifies the authorization scope(s) for the method you are building.
1690    ///
1691    /// See [`Self::add_scope()`] for details.
1692    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectProfilePatchCall<'a, C>
1693    where
1694        I: IntoIterator<Item = St>,
1695        St: AsRef<str>,
1696    {
1697        self._scopes
1698            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1699        self
1700    }
1701
1702    /// Removes all scopes, and no default scope will be used either.
1703    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1704    /// for details).
1705    pub fn clear_scopes(mut self) -> ProjectProfilePatchCall<'a, C> {
1706        self._scopes.clear();
1707        self
1708    }
1709}