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