google_cloudlatencytest2/
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    /// View monitoring data for all of your Google Cloud and API projects
17    MonitoringReadonly,
18}
19
20impl AsRef<str> for Scope {
21    fn as_ref(&self) -> &str {
22        match *self {
23            Scope::MonitoringReadonly => "https://www.googleapis.com/auth/monitoring.readonly",
24        }
25    }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30    fn default() -> Scope {
31        Scope::MonitoringReadonly
32    }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all Cloudlatencytest related resource activities
40///
41/// # Examples
42///
43/// Instantiate a new hub
44///
45/// ```test_harness,no_run
46/// extern crate hyper;
47/// extern crate hyper_rustls;
48/// extern crate google_cloudlatencytest2 as cloudlatencytest2;
49/// use cloudlatencytest2::api::Stats;
50/// use cloudlatencytest2::{Result, Error};
51/// # async fn dox() {
52/// use cloudlatencytest2::{Cloudlatencytest, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
53///
54/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
55/// // `client_secret`, among other things.
56/// let secret: yup_oauth2::ApplicationSecret = Default::default();
57/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
58/// // unless you replace  `None` with the desired Flow.
59/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
60/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
61/// // retrieve them from storage.
62/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
63///     .with_native_roots()
64///     .unwrap()
65///     .https_only()
66///     .enable_http2()
67///     .build();
68///
69/// let executor = hyper_util::rt::TokioExecutor::new();
70/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
71///     secret,
72///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
73///     yup_oauth2::client::CustomHyperClientBuilder::from(
74///         hyper_util::client::legacy::Client::builder(executor).build(connector),
75///     ),
76/// ).build().await.unwrap();
77///
78/// let client = hyper_util::client::legacy::Client::builder(
79///     hyper_util::rt::TokioExecutor::new()
80/// )
81/// .build(
82///     hyper_rustls::HttpsConnectorBuilder::new()
83///         .with_native_roots()
84///         .unwrap()
85///         .https_or_http()
86///         .enable_http2()
87///         .build()
88/// );
89/// let mut hub = Cloudlatencytest::new(client, auth);
90/// // As the method needs a request, you would usually fill it with the desired information
91/// // into the respective structure. Some of the parts shown here might not be applicable !
92/// // Values shown here are possibly random and not representative !
93/// let mut req = Stats::default();
94///
95/// // You can configure optional parameters by calling the respective setters at will, and
96/// // execute the final call using `doit()`.
97/// // Values shown here are possibly random and not representative !
98/// let result = hub.statscollection().updatestats(req)
99///              .doit().await;
100///
101/// match result {
102///     Err(e) => match e {
103///         // The Error enum provides details about what exactly happened.
104///         // You can also just use its `Debug`, `Display` or `Error` traits
105///          Error::HttpError(_)
106///         |Error::Io(_)
107///         |Error::MissingAPIKey
108///         |Error::MissingToken(_)
109///         |Error::Cancelled
110///         |Error::UploadSizeLimitExceeded(_, _)
111///         |Error::Failure(_)
112///         |Error::BadRequest(_)
113///         |Error::FieldClash(_)
114///         |Error::JsonDecodeError(_, _) => println!("{}", e),
115///     },
116///     Ok(res) => println!("Success: {:?}", res),
117/// }
118/// # }
119/// ```
120#[derive(Clone)]
121pub struct Cloudlatencytest<C> {
122    pub client: common::Client<C>,
123    pub auth: Box<dyn common::GetToken>,
124    _user_agent: String,
125    _base_url: String,
126    _root_url: String,
127}
128
129impl<C> common::Hub for Cloudlatencytest<C> {}
130
131impl<'a, C> Cloudlatencytest<C> {
132    pub fn new<A: 'static + common::GetToken>(
133        client: common::Client<C>,
134        auth: A,
135    ) -> Cloudlatencytest<C> {
136        Cloudlatencytest {
137            client,
138            auth: Box::new(auth),
139            _user_agent: "google-api-rust-client/7.0.0".to_string(),
140            _base_url: "https://cloudlatencytest-pa.googleapis.com/v2/statscollection/".to_string(),
141            _root_url: "https://cloudlatencytest-pa.googleapis.com/".to_string(),
142        }
143    }
144
145    pub fn statscollection(&'a self) -> StatscollectionMethods<'a, C> {
146        StatscollectionMethods { hub: self }
147    }
148
149    /// Set the user-agent header field to use in all requests to the server.
150    /// It defaults to `google-api-rust-client/7.0.0`.
151    ///
152    /// Returns the previously set user-agent.
153    pub fn user_agent(&mut self, agent_name: String) -> String {
154        std::mem::replace(&mut self._user_agent, agent_name)
155    }
156
157    /// Set the base url to use in all requests to the server.
158    /// It defaults to `https://cloudlatencytest-pa.googleapis.com/v2/statscollection/`.
159    ///
160    /// Returns the previously set base url.
161    pub fn base_url(&mut self, new_base_url: String) -> String {
162        std::mem::replace(&mut self._base_url, new_base_url)
163    }
164
165    /// Set the root url to use in all requests to the server.
166    /// It defaults to `https://cloudlatencytest-pa.googleapis.com/`.
167    ///
168    /// Returns the previously set root url.
169    pub fn root_url(&mut self, new_root_url: String) -> String {
170        std::mem::replace(&mut self._root_url, new_root_url)
171    }
172}
173
174// ############
175// SCHEMAS ###
176// ##########
177/// There is no detailed description.
178///
179/// # Activities
180///
181/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
182/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
183///
184/// * [updateaggregatedstats statscollection](StatscollectionUpdateaggregatedstatCall) (request)
185#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
186#[serde_with::serde_as]
187#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
188pub struct AggregatedStats {
189    /// no description provided
190    pub stats: Option<Vec<Stats>>,
191}
192
193impl common::RequestValue for AggregatedStats {}
194
195/// There is no detailed description.
196///
197/// # Activities
198///
199/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
200/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
201///
202/// * [updateaggregatedstats statscollection](StatscollectionUpdateaggregatedstatCall) (response)
203#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
204#[serde_with::serde_as]
205#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
206pub struct AggregatedStatsReply {
207    /// no description provided
208    #[serde(rename = "testValue")]
209    pub test_value: Option<String>,
210}
211
212impl common::ResponseResult for AggregatedStatsReply {}
213
214/// There is no detailed description.
215///
216/// This type is not used in any activity, and only used as *part* of another schema.
217///
218#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
219#[serde_with::serde_as]
220#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
221pub struct DoubleValue {
222    /// no description provided
223    pub label: Option<String>,
224    /// no description provided
225    pub value: Option<f32>,
226}
227
228impl common::Part for DoubleValue {}
229
230/// There is no detailed description.
231///
232/// This type is not used in any activity, and only used as *part* of another schema.
233///
234#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
235#[serde_with::serde_as]
236#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
237pub struct IntValue {
238    /// no description provided
239    pub label: Option<String>,
240    /// no description provided
241    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
242    pub value: Option<i64>,
243}
244
245impl common::Part for IntValue {}
246
247/// There is no detailed description.
248///
249/// # Activities
250///
251/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
252/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
253///
254/// * [updatestats statscollection](StatscollectionUpdatestatCall) (request)
255#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
256#[serde_with::serde_as]
257#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
258pub struct Stats {
259    /// no description provided
260    #[serde(rename = "doubleValues")]
261    pub double_values: Option<Vec<DoubleValue>>,
262    /// no description provided
263    #[serde(rename = "intValues")]
264    pub int_values: Option<Vec<IntValue>>,
265    /// no description provided
266    #[serde(rename = "stringValues")]
267    pub string_values: Option<Vec<StringValue>>,
268    /// no description provided
269    pub time: Option<f64>,
270}
271
272impl common::RequestValue for Stats {}
273
274/// There is no detailed description.
275///
276/// # Activities
277///
278/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
279/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
280///
281/// * [updatestats statscollection](StatscollectionUpdatestatCall) (response)
282#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
283#[serde_with::serde_as]
284#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
285pub struct StatsReply {
286    /// no description provided
287    #[serde(rename = "testValue")]
288    pub test_value: Option<String>,
289}
290
291impl common::ResponseResult for StatsReply {}
292
293/// There is no detailed description.
294///
295/// This type is not used in any activity, and only used as *part* of another schema.
296///
297#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
298#[serde_with::serde_as]
299#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
300pub struct StringValue {
301    /// no description provided
302    pub label: Option<String>,
303    /// no description provided
304    pub value: Option<String>,
305}
306
307impl common::Part for StringValue {}
308
309// ###################
310// MethodBuilders ###
311// #################
312
313/// A builder providing access to all methods supported on *statscollection* resources.
314/// It is not used directly, but through the [`Cloudlatencytest`] hub.
315///
316/// # Example
317///
318/// Instantiate a resource builder
319///
320/// ```test_harness,no_run
321/// extern crate hyper;
322/// extern crate hyper_rustls;
323/// extern crate google_cloudlatencytest2 as cloudlatencytest2;
324///
325/// # async fn dox() {
326/// use cloudlatencytest2::{Cloudlatencytest, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
327///
328/// let secret: yup_oauth2::ApplicationSecret = Default::default();
329/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
330///     .with_native_roots()
331///     .unwrap()
332///     .https_only()
333///     .enable_http2()
334///     .build();
335///
336/// let executor = hyper_util::rt::TokioExecutor::new();
337/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
338///     secret,
339///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
340///     yup_oauth2::client::CustomHyperClientBuilder::from(
341///         hyper_util::client::legacy::Client::builder(executor).build(connector),
342///     ),
343/// ).build().await.unwrap();
344///
345/// let client = hyper_util::client::legacy::Client::builder(
346///     hyper_util::rt::TokioExecutor::new()
347/// )
348/// .build(
349///     hyper_rustls::HttpsConnectorBuilder::new()
350///         .with_native_roots()
351///         .unwrap()
352///         .https_or_http()
353///         .enable_http2()
354///         .build()
355/// );
356/// let mut hub = Cloudlatencytest::new(client, auth);
357/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
358/// // like `updateaggregatedstats(...)` and `updatestats(...)`
359/// // to build up your call.
360/// let rb = hub.statscollection();
361/// # }
362/// ```
363pub struct StatscollectionMethods<'a, C>
364where
365    C: 'a,
366{
367    hub: &'a Cloudlatencytest<C>,
368}
369
370impl<'a, C> common::MethodsBuilder for StatscollectionMethods<'a, C> {}
371
372impl<'a, C> StatscollectionMethods<'a, C> {
373    /// Create a builder to help you perform the following task:
374    ///
375    /// RPC to update the new TCP stats.
376    ///
377    /// # Arguments
378    ///
379    /// * `request` - No description provided.
380    pub fn updateaggregatedstats(
381        &self,
382        request: AggregatedStats,
383    ) -> StatscollectionUpdateaggregatedstatCall<'a, C> {
384        StatscollectionUpdateaggregatedstatCall {
385            hub: self.hub,
386            _request: request,
387            _delegate: Default::default(),
388            _additional_params: Default::default(),
389            _scopes: Default::default(),
390        }
391    }
392
393    /// Create a builder to help you perform the following task:
394    ///
395    /// RPC to update the new TCP stats.
396    ///
397    /// # Arguments
398    ///
399    /// * `request` - No description provided.
400    pub fn updatestats(&self, request: Stats) -> StatscollectionUpdatestatCall<'a, C> {
401        StatscollectionUpdatestatCall {
402            hub: self.hub,
403            _request: request,
404            _delegate: Default::default(),
405            _additional_params: Default::default(),
406            _scopes: Default::default(),
407        }
408    }
409}
410
411// ###################
412// CallBuilders   ###
413// #################
414
415/// RPC to update the new TCP stats.
416///
417/// A builder for the *updateaggregatedstats* method supported by a *statscollection* resource.
418/// It is not used directly, but through a [`StatscollectionMethods`] instance.
419///
420/// # Example
421///
422/// Instantiate a resource method builder
423///
424/// ```test_harness,no_run
425/// # extern crate hyper;
426/// # extern crate hyper_rustls;
427/// # extern crate google_cloudlatencytest2 as cloudlatencytest2;
428/// use cloudlatencytest2::api::AggregatedStats;
429/// # async fn dox() {
430/// # use cloudlatencytest2::{Cloudlatencytest, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
431///
432/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
433/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
434/// #     .with_native_roots()
435/// #     .unwrap()
436/// #     .https_only()
437/// #     .enable_http2()
438/// #     .build();
439///
440/// # let executor = hyper_util::rt::TokioExecutor::new();
441/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
442/// #     secret,
443/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
444/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
445/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
446/// #     ),
447/// # ).build().await.unwrap();
448///
449/// # let client = hyper_util::client::legacy::Client::builder(
450/// #     hyper_util::rt::TokioExecutor::new()
451/// # )
452/// # .build(
453/// #     hyper_rustls::HttpsConnectorBuilder::new()
454/// #         .with_native_roots()
455/// #         .unwrap()
456/// #         .https_or_http()
457/// #         .enable_http2()
458/// #         .build()
459/// # );
460/// # let mut hub = Cloudlatencytest::new(client, auth);
461/// // As the method needs a request, you would usually fill it with the desired information
462/// // into the respective structure. Some of the parts shown here might not be applicable !
463/// // Values shown here are possibly random and not representative !
464/// let mut req = AggregatedStats::default();
465///
466/// // You can configure optional parameters by calling the respective setters at will, and
467/// // execute the final call using `doit()`.
468/// // Values shown here are possibly random and not representative !
469/// let result = hub.statscollection().updateaggregatedstats(req)
470///              .doit().await;
471/// # }
472/// ```
473pub struct StatscollectionUpdateaggregatedstatCall<'a, C>
474where
475    C: 'a,
476{
477    hub: &'a Cloudlatencytest<C>,
478    _request: AggregatedStats,
479    _delegate: Option<&'a mut dyn common::Delegate>,
480    _additional_params: HashMap<String, String>,
481    _scopes: BTreeSet<String>,
482}
483
484impl<'a, C> common::CallBuilder for StatscollectionUpdateaggregatedstatCall<'a, C> {}
485
486impl<'a, C> StatscollectionUpdateaggregatedstatCall<'a, C>
487where
488    C: common::Connector,
489{
490    /// Perform the operation you have build so far.
491    pub async fn doit(mut self) -> common::Result<(common::Response, AggregatedStatsReply)> {
492        use std::borrow::Cow;
493        use std::io::{Read, Seek};
494
495        use common::{url::Params, ToParts};
496        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
497
498        let mut dd = common::DefaultDelegate;
499        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
500        dlg.begin(common::MethodInfo {
501            id: "cloudlatencytest.statscollection.updateaggregatedstats",
502            http_method: hyper::Method::POST,
503        });
504
505        for &field in ["alt"].iter() {
506            if self._additional_params.contains_key(field) {
507                dlg.finished(false);
508                return Err(common::Error::FieldClash(field));
509            }
510        }
511
512        let mut params = Params::with_capacity(3 + self._additional_params.len());
513
514        params.extend(self._additional_params.iter());
515
516        params.push("alt", "json");
517        let mut url = self.hub._base_url.clone() + "updateaggregatedstats";
518        if self._scopes.is_empty() {
519            self._scopes
520                .insert(Scope::MonitoringReadonly.as_ref().to_string());
521        }
522
523        let url = params.parse_with_url(&url);
524
525        let mut json_mime_type = mime::APPLICATION_JSON;
526        let mut request_value_reader = {
527            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
528            common::remove_json_null_values(&mut value);
529            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
530            serde_json::to_writer(&mut dst, &value).unwrap();
531            dst
532        };
533        let request_size = request_value_reader
534            .seek(std::io::SeekFrom::End(0))
535            .unwrap();
536        request_value_reader
537            .seek(std::io::SeekFrom::Start(0))
538            .unwrap();
539
540        loop {
541            let token = match self
542                .hub
543                .auth
544                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
545                .await
546            {
547                Ok(token) => token,
548                Err(e) => match dlg.token(e) {
549                    Ok(token) => token,
550                    Err(e) => {
551                        dlg.finished(false);
552                        return Err(common::Error::MissingToken(e));
553                    }
554                },
555            };
556            request_value_reader
557                .seek(std::io::SeekFrom::Start(0))
558                .unwrap();
559            let mut req_result = {
560                let client = &self.hub.client;
561                dlg.pre_request();
562                let mut req_builder = hyper::Request::builder()
563                    .method(hyper::Method::POST)
564                    .uri(url.as_str())
565                    .header(USER_AGENT, self.hub._user_agent.clone());
566
567                if let Some(token) = token.as_ref() {
568                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
569                }
570
571                let request = req_builder
572                    .header(CONTENT_TYPE, json_mime_type.to_string())
573                    .header(CONTENT_LENGTH, request_size as u64)
574                    .body(common::to_body(
575                        request_value_reader.get_ref().clone().into(),
576                    ));
577
578                client.request(request.unwrap()).await
579            };
580
581            match req_result {
582                Err(err) => {
583                    if let common::Retry::After(d) = dlg.http_error(&err) {
584                        sleep(d).await;
585                        continue;
586                    }
587                    dlg.finished(false);
588                    return Err(common::Error::HttpError(err));
589                }
590                Ok(res) => {
591                    let (mut parts, body) = res.into_parts();
592                    let mut body = common::Body::new(body);
593                    if !parts.status.is_success() {
594                        let bytes = common::to_bytes(body).await.unwrap_or_default();
595                        let error = serde_json::from_str(&common::to_string(&bytes));
596                        let response = common::to_response(parts, bytes.into());
597
598                        if let common::Retry::After(d) =
599                            dlg.http_failure(&response, error.as_ref().ok())
600                        {
601                            sleep(d).await;
602                            continue;
603                        }
604
605                        dlg.finished(false);
606
607                        return Err(match error {
608                            Ok(value) => common::Error::BadRequest(value),
609                            _ => common::Error::Failure(response),
610                        });
611                    }
612                    let response = {
613                        let bytes = common::to_bytes(body).await.unwrap_or_default();
614                        let encoded = common::to_string(&bytes);
615                        match serde_json::from_str(&encoded) {
616                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
617                            Err(error) => {
618                                dlg.response_json_decode_error(&encoded, &error);
619                                return Err(common::Error::JsonDecodeError(
620                                    encoded.to_string(),
621                                    error,
622                                ));
623                            }
624                        }
625                    };
626
627                    dlg.finished(true);
628                    return Ok(response);
629                }
630            }
631        }
632    }
633
634    ///
635    /// Sets the *request* property to the given value.
636    ///
637    /// Even though the property as already been set when instantiating this call,
638    /// we provide this method for API completeness.
639    pub fn request(
640        mut self,
641        new_value: AggregatedStats,
642    ) -> StatscollectionUpdateaggregatedstatCall<'a, C> {
643        self._request = new_value;
644        self
645    }
646    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
647    /// while executing the actual API request.
648    ///
649    /// ````text
650    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
651    /// ````
652    ///
653    /// Sets the *delegate* property to the given value.
654    pub fn delegate(
655        mut self,
656        new_value: &'a mut dyn common::Delegate,
657    ) -> StatscollectionUpdateaggregatedstatCall<'a, C> {
658        self._delegate = Some(new_value);
659        self
660    }
661
662    /// Set any additional parameter of the query string used in the request.
663    /// It should be used to set parameters which are not yet available through their own
664    /// setters.
665    ///
666    /// Please note that this method must not be used to set any of the known parameters
667    /// which have their own setter method. If done anyway, the request will fail.
668    ///
669    /// # Additional Parameters
670    ///
671    /// * *alt* (query-string) - Data format for the response.
672    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
673    /// * *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.
674    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
675    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
676    /// * *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. Overrides userIp if both are provided.
677    /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
678    pub fn param<T>(mut self, name: T, value: T) -> StatscollectionUpdateaggregatedstatCall<'a, C>
679    where
680        T: AsRef<str>,
681    {
682        self._additional_params
683            .insert(name.as_ref().to_string(), value.as_ref().to_string());
684        self
685    }
686
687    /// Identifies the authorization scope for the method you are building.
688    ///
689    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
690    /// [`Scope::MonitoringReadonly`].
691    ///
692    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
693    /// tokens for more than one scope.
694    ///
695    /// Usually there is more than one suitable scope to authorize an operation, some of which may
696    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
697    /// sufficient, a read-write scope will do as well.
698    pub fn add_scope<St>(mut self, scope: St) -> StatscollectionUpdateaggregatedstatCall<'a, C>
699    where
700        St: AsRef<str>,
701    {
702        self._scopes.insert(String::from(scope.as_ref()));
703        self
704    }
705    /// Identifies the authorization scope(s) for the method you are building.
706    ///
707    /// See [`Self::add_scope()`] for details.
708    pub fn add_scopes<I, St>(mut self, scopes: I) -> StatscollectionUpdateaggregatedstatCall<'a, C>
709    where
710        I: IntoIterator<Item = St>,
711        St: AsRef<str>,
712    {
713        self._scopes
714            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
715        self
716    }
717
718    /// Removes all scopes, and no default scope will be used either.
719    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
720    /// for details).
721    pub fn clear_scopes(mut self) -> StatscollectionUpdateaggregatedstatCall<'a, C> {
722        self._scopes.clear();
723        self
724    }
725}
726
727/// RPC to update the new TCP stats.
728///
729/// A builder for the *updatestats* method supported by a *statscollection* resource.
730/// It is not used directly, but through a [`StatscollectionMethods`] instance.
731///
732/// # Example
733///
734/// Instantiate a resource method builder
735///
736/// ```test_harness,no_run
737/// # extern crate hyper;
738/// # extern crate hyper_rustls;
739/// # extern crate google_cloudlatencytest2 as cloudlatencytest2;
740/// use cloudlatencytest2::api::Stats;
741/// # async fn dox() {
742/// # use cloudlatencytest2::{Cloudlatencytest, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
743///
744/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
745/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
746/// #     .with_native_roots()
747/// #     .unwrap()
748/// #     .https_only()
749/// #     .enable_http2()
750/// #     .build();
751///
752/// # let executor = hyper_util::rt::TokioExecutor::new();
753/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
754/// #     secret,
755/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
756/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
757/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
758/// #     ),
759/// # ).build().await.unwrap();
760///
761/// # let client = hyper_util::client::legacy::Client::builder(
762/// #     hyper_util::rt::TokioExecutor::new()
763/// # )
764/// # .build(
765/// #     hyper_rustls::HttpsConnectorBuilder::new()
766/// #         .with_native_roots()
767/// #         .unwrap()
768/// #         .https_or_http()
769/// #         .enable_http2()
770/// #         .build()
771/// # );
772/// # let mut hub = Cloudlatencytest::new(client, auth);
773/// // As the method needs a request, you would usually fill it with the desired information
774/// // into the respective structure. Some of the parts shown here might not be applicable !
775/// // Values shown here are possibly random and not representative !
776/// let mut req = Stats::default();
777///
778/// // You can configure optional parameters by calling the respective setters at will, and
779/// // execute the final call using `doit()`.
780/// // Values shown here are possibly random and not representative !
781/// let result = hub.statscollection().updatestats(req)
782///              .doit().await;
783/// # }
784/// ```
785pub struct StatscollectionUpdatestatCall<'a, C>
786where
787    C: 'a,
788{
789    hub: &'a Cloudlatencytest<C>,
790    _request: Stats,
791    _delegate: Option<&'a mut dyn common::Delegate>,
792    _additional_params: HashMap<String, String>,
793    _scopes: BTreeSet<String>,
794}
795
796impl<'a, C> common::CallBuilder for StatscollectionUpdatestatCall<'a, C> {}
797
798impl<'a, C> StatscollectionUpdatestatCall<'a, C>
799where
800    C: common::Connector,
801{
802    /// Perform the operation you have build so far.
803    pub async fn doit(mut self) -> common::Result<(common::Response, StatsReply)> {
804        use std::borrow::Cow;
805        use std::io::{Read, Seek};
806
807        use common::{url::Params, ToParts};
808        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
809
810        let mut dd = common::DefaultDelegate;
811        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
812        dlg.begin(common::MethodInfo {
813            id: "cloudlatencytest.statscollection.updatestats",
814            http_method: hyper::Method::POST,
815        });
816
817        for &field in ["alt"].iter() {
818            if self._additional_params.contains_key(field) {
819                dlg.finished(false);
820                return Err(common::Error::FieldClash(field));
821            }
822        }
823
824        let mut params = Params::with_capacity(3 + self._additional_params.len());
825
826        params.extend(self._additional_params.iter());
827
828        params.push("alt", "json");
829        let mut url = self.hub._base_url.clone() + "updatestats";
830        if self._scopes.is_empty() {
831            self._scopes
832                .insert(Scope::MonitoringReadonly.as_ref().to_string());
833        }
834
835        let url = params.parse_with_url(&url);
836
837        let mut json_mime_type = mime::APPLICATION_JSON;
838        let mut request_value_reader = {
839            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
840            common::remove_json_null_values(&mut value);
841            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
842            serde_json::to_writer(&mut dst, &value).unwrap();
843            dst
844        };
845        let request_size = request_value_reader
846            .seek(std::io::SeekFrom::End(0))
847            .unwrap();
848        request_value_reader
849            .seek(std::io::SeekFrom::Start(0))
850            .unwrap();
851
852        loop {
853            let token = match self
854                .hub
855                .auth
856                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
857                .await
858            {
859                Ok(token) => token,
860                Err(e) => match dlg.token(e) {
861                    Ok(token) => token,
862                    Err(e) => {
863                        dlg.finished(false);
864                        return Err(common::Error::MissingToken(e));
865                    }
866                },
867            };
868            request_value_reader
869                .seek(std::io::SeekFrom::Start(0))
870                .unwrap();
871            let mut req_result = {
872                let client = &self.hub.client;
873                dlg.pre_request();
874                let mut req_builder = hyper::Request::builder()
875                    .method(hyper::Method::POST)
876                    .uri(url.as_str())
877                    .header(USER_AGENT, self.hub._user_agent.clone());
878
879                if let Some(token) = token.as_ref() {
880                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
881                }
882
883                let request = req_builder
884                    .header(CONTENT_TYPE, json_mime_type.to_string())
885                    .header(CONTENT_LENGTH, request_size as u64)
886                    .body(common::to_body(
887                        request_value_reader.get_ref().clone().into(),
888                    ));
889
890                client.request(request.unwrap()).await
891            };
892
893            match req_result {
894                Err(err) => {
895                    if let common::Retry::After(d) = dlg.http_error(&err) {
896                        sleep(d).await;
897                        continue;
898                    }
899                    dlg.finished(false);
900                    return Err(common::Error::HttpError(err));
901                }
902                Ok(res) => {
903                    let (mut parts, body) = res.into_parts();
904                    let mut body = common::Body::new(body);
905                    if !parts.status.is_success() {
906                        let bytes = common::to_bytes(body).await.unwrap_or_default();
907                        let error = serde_json::from_str(&common::to_string(&bytes));
908                        let response = common::to_response(parts, bytes.into());
909
910                        if let common::Retry::After(d) =
911                            dlg.http_failure(&response, error.as_ref().ok())
912                        {
913                            sleep(d).await;
914                            continue;
915                        }
916
917                        dlg.finished(false);
918
919                        return Err(match error {
920                            Ok(value) => common::Error::BadRequest(value),
921                            _ => common::Error::Failure(response),
922                        });
923                    }
924                    let response = {
925                        let bytes = common::to_bytes(body).await.unwrap_or_default();
926                        let encoded = common::to_string(&bytes);
927                        match serde_json::from_str(&encoded) {
928                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
929                            Err(error) => {
930                                dlg.response_json_decode_error(&encoded, &error);
931                                return Err(common::Error::JsonDecodeError(
932                                    encoded.to_string(),
933                                    error,
934                                ));
935                            }
936                        }
937                    };
938
939                    dlg.finished(true);
940                    return Ok(response);
941                }
942            }
943        }
944    }
945
946    ///
947    /// Sets the *request* property to the given value.
948    ///
949    /// Even though the property as already been set when instantiating this call,
950    /// we provide this method for API completeness.
951    pub fn request(mut self, new_value: Stats) -> StatscollectionUpdatestatCall<'a, C> {
952        self._request = new_value;
953        self
954    }
955    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
956    /// while executing the actual API request.
957    ///
958    /// ````text
959    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
960    /// ````
961    ///
962    /// Sets the *delegate* property to the given value.
963    pub fn delegate(
964        mut self,
965        new_value: &'a mut dyn common::Delegate,
966    ) -> StatscollectionUpdatestatCall<'a, C> {
967        self._delegate = Some(new_value);
968        self
969    }
970
971    /// Set any additional parameter of the query string used in the request.
972    /// It should be used to set parameters which are not yet available through their own
973    /// setters.
974    ///
975    /// Please note that this method must not be used to set any of the known parameters
976    /// which have their own setter method. If done anyway, the request will fail.
977    ///
978    /// # Additional Parameters
979    ///
980    /// * *alt* (query-string) - Data format for the response.
981    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
982    /// * *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.
983    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
984    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
985    /// * *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. Overrides userIp if both are provided.
986    /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
987    pub fn param<T>(mut self, name: T, value: T) -> StatscollectionUpdatestatCall<'a, C>
988    where
989        T: AsRef<str>,
990    {
991        self._additional_params
992            .insert(name.as_ref().to_string(), value.as_ref().to_string());
993        self
994    }
995
996    /// Identifies the authorization scope for the method you are building.
997    ///
998    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
999    /// [`Scope::MonitoringReadonly`].
1000    ///
1001    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1002    /// tokens for more than one scope.
1003    ///
1004    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1005    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1006    /// sufficient, a read-write scope will do as well.
1007    pub fn add_scope<St>(mut self, scope: St) -> StatscollectionUpdatestatCall<'a, C>
1008    where
1009        St: AsRef<str>,
1010    {
1011        self._scopes.insert(String::from(scope.as_ref()));
1012        self
1013    }
1014    /// Identifies the authorization scope(s) for the method you are building.
1015    ///
1016    /// See [`Self::add_scope()`] for details.
1017    pub fn add_scopes<I, St>(mut self, scopes: I) -> StatscollectionUpdatestatCall<'a, C>
1018    where
1019        I: IntoIterator<Item = St>,
1020        St: AsRef<str>,
1021    {
1022        self._scopes
1023            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1024        self
1025    }
1026
1027    /// Removes all scopes, and no default scope will be used either.
1028    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1029    /// for details).
1030    pub fn clear_scopes(mut self) -> StatscollectionUpdatestatCall<'a, C> {
1031        self._scopes.clear();
1032        self
1033    }
1034}