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