google_cloudtrace1/
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    /// Write Trace data for a project or application
20    TraceAppend,
21
22    /// Read Trace data for a project or application
23    TraceReadonly,
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::TraceAppend => "https://www.googleapis.com/auth/trace.append",
31            Scope::TraceReadonly => "https://www.googleapis.com/auth/trace.readonly",
32        }
33    }
34}
35
36#[allow(clippy::derivable_impls)]
37impl Default for Scope {
38    fn default() -> Scope {
39        Scope::TraceReadonly
40    }
41}
42
43// ########
44// HUB ###
45// ######
46
47/// Central instance to access all CloudTrace 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_cloudtrace1 as cloudtrace1;
57/// use cloudtrace1::{Result, Error};
58/// # async fn dox() {
59/// use cloudtrace1::{CloudTrace, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
60///
61/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
62/// // `client_secret`, among other things.
63/// let secret: yup_oauth2::ApplicationSecret = Default::default();
64/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
65/// // unless you replace  `None` with the desired Flow.
66/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
67/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
68/// // retrieve them from storage.
69/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
70///     .with_native_roots()
71///     .unwrap()
72///     .https_only()
73///     .enable_http2()
74///     .build();
75///
76/// let executor = hyper_util::rt::TokioExecutor::new();
77/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
78///     secret,
79///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
80///     yup_oauth2::client::CustomHyperClientBuilder::from(
81///         hyper_util::client::legacy::Client::builder(executor).build(connector),
82///     ),
83/// ).build().await.unwrap();
84///
85/// let client = hyper_util::client::legacy::Client::builder(
86///     hyper_util::rt::TokioExecutor::new()
87/// )
88/// .build(
89///     hyper_rustls::HttpsConnectorBuilder::new()
90///         .with_native_roots()
91///         .unwrap()
92///         .https_or_http()
93///         .enable_http2()
94///         .build()
95/// );
96/// let mut hub = CloudTrace::new(client, auth);
97/// // You can configure optional parameters by calling the respective setters at will, and
98/// // execute the final call using `doit()`.
99/// // Values shown here are possibly random and not representative !
100/// let result = hub.projects().traces_get("projectId", "traceId")
101///              .doit().await;
102///
103/// match result {
104///     Err(e) => match e {
105///         // The Error enum provides details about what exactly happened.
106///         // You can also just use its `Debug`, `Display` or `Error` traits
107///          Error::HttpError(_)
108///         |Error::Io(_)
109///         |Error::MissingAPIKey
110///         |Error::MissingToken(_)
111///         |Error::Cancelled
112///         |Error::UploadSizeLimitExceeded(_, _)
113///         |Error::Failure(_)
114///         |Error::BadRequest(_)
115///         |Error::FieldClash(_)
116///         |Error::JsonDecodeError(_, _) => println!("{}", e),
117///     },
118///     Ok(res) => println!("Success: {:?}", res),
119/// }
120/// # }
121/// ```
122#[derive(Clone)]
123pub struct CloudTrace<C> {
124    pub client: common::Client<C>,
125    pub auth: Box<dyn common::GetToken>,
126    _user_agent: String,
127    _base_url: String,
128    _root_url: String,
129}
130
131impl<C> common::Hub for CloudTrace<C> {}
132
133impl<'a, C> CloudTrace<C> {
134    pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> CloudTrace<C> {
135        CloudTrace {
136            client,
137            auth: Box::new(auth),
138            _user_agent: "google-api-rust-client/7.0.0".to_string(),
139            _base_url: "https://cloudtrace.googleapis.com/".to_string(),
140            _root_url: "https://cloudtrace.googleapis.com/".to_string(),
141        }
142    }
143
144    pub fn projects(&'a self) -> ProjectMethods<'a, C> {
145        ProjectMethods { hub: self }
146    }
147
148    /// Set the user-agent header field to use in all requests to the server.
149    /// It defaults to `google-api-rust-client/7.0.0`.
150    ///
151    /// Returns the previously set user-agent.
152    pub fn user_agent(&mut self, agent_name: String) -> String {
153        std::mem::replace(&mut self._user_agent, agent_name)
154    }
155
156    /// Set the base url to use in all requests to the server.
157    /// It defaults to `https://cloudtrace.googleapis.com/`.
158    ///
159    /// Returns the previously set base url.
160    pub fn base_url(&mut self, new_base_url: String) -> String {
161        std::mem::replace(&mut self._base_url, new_base_url)
162    }
163
164    /// Set the root url to use in all requests to the server.
165    /// It defaults to `https://cloudtrace.googleapis.com/`.
166    ///
167    /// Returns the previously set root url.
168    pub fn root_url(&mut self, new_root_url: String) -> String {
169        std::mem::replace(&mut self._root_url, new_root_url)
170    }
171}
172
173// ############
174// SCHEMAS ###
175// ##########
176/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
177///
178/// # Activities
179///
180/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
181/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
182///
183/// * [patch traces projects](ProjectPatchTraceCall) (response)
184#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
185#[serde_with::serde_as]
186#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
187pub struct Empty {
188    _never_set: Option<bool>,
189}
190
191impl common::ResponseResult for Empty {}
192
193/// The response message for the `ListTraces` method.
194///
195/// # Activities
196///
197/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
198/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
199///
200/// * [traces list projects](ProjectTraceListCall) (response)
201#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
202#[serde_with::serde_as]
203#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
204pub struct ListTracesResponse {
205    /// If defined, indicates that there are more traces that match the request and that this value should be passed to the next request to continue retrieving additional traces.
206    #[serde(rename = "nextPageToken")]
207    pub next_page_token: Option<String>,
208    /// List of trace records as specified by the view parameter.
209    pub traces: Option<Vec<Trace>>,
210}
211
212impl common::ResponseResult for ListTracesResponse {}
213
214/// A trace describes how long it takes for an application to perform an operation. It consists of a set of spans, each of which represent a single timed event within the operation.
215///
216/// # Activities
217///
218/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
219/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
220///
221/// * [traces get projects](ProjectTraceGetCall) (response)
222#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
223#[serde_with::serde_as]
224#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
225pub struct Trace {
226    /// Project ID of the Cloud project where the trace data is stored.
227    #[serde(rename = "projectId")]
228    pub project_id: Option<String>,
229    /// Collection of spans in the trace.
230    pub spans: Option<Vec<TraceSpan>>,
231    /// Globally unique identifier for the trace. This identifier is a 128-bit numeric value formatted as a 32-byte hex string. For example, `382d4f4c6b7bb2f4a972559d9085001d`. The numeric value should not be zero.
232    #[serde(rename = "traceId")]
233    pub trace_id: Option<String>,
234}
235
236impl common::ResponseResult for Trace {}
237
238/// A span represents a single timed event within a trace. Spans can be nested and form a trace tree. Often, a trace contains a root span that describes the end-to-end latency of an operation and, optionally, one or more subspans for its suboperations. Spans do not need to be contiguous. There may be gaps between spans in a trace.
239///
240/// This type is not used in any activity, and only used as *part* of another schema.
241///
242#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
243#[serde_with::serde_as]
244#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
245pub struct TraceSpan {
246    /// End time of the span in seconds and nanoseconds from the UNIX epoch.
247    #[serde(rename = "endTime")]
248    pub end_time: Option<chrono::DateTime<chrono::offset::Utc>>,
249    /// Distinguishes between spans generated in a particular context. For example, two spans with the same name may be distinguished using `RPC_CLIENT` and `RPC_SERVER` to identify queueing latency associated with the span.
250    pub kind: Option<String>,
251    /// Collection of labels associated with the span. Label keys must be less than 128 bytes. Label values must be less than 16 KiB. Some keys might have predefined meaning, and you can also create your own. For more information, see [Cloud Trace labels](https://cloud.google.com/trace/docs/trace-labels).
252    pub labels: Option<HashMap<String, String>>,
253    /// Name of the span. Must be less than 128 bytes. The span name is sanitized and displayed in the Trace tool in the Google Cloud Platform Console. The name may be a method name or some other per-call site name. For the same executable and the same call point, a best practice is to use a consistent name, which makes it easier to correlate cross-trace spans.
254    pub name: Option<String>,
255    /// Optional. ID of the parent span, if any.
256    #[serde(rename = "parentSpanId")]
257    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
258    pub parent_span_id: Option<u64>,
259    /// Identifier for the span. Must be a 64-bit integer other than 0 and unique within a trace. For example, `2205310701640571284`.
260    #[serde(rename = "spanId")]
261    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
262    pub span_id: Option<u64>,
263    /// Start time of the span in seconds and nanoseconds from the UNIX epoch.
264    #[serde(rename = "startTime")]
265    pub start_time: Option<chrono::DateTime<chrono::offset::Utc>>,
266}
267
268impl common::Part for TraceSpan {}
269
270/// List of new or updated traces.
271///
272/// # Activities
273///
274/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
275/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
276///
277/// * [patch traces projects](ProjectPatchTraceCall) (request)
278#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
279#[serde_with::serde_as]
280#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
281pub struct Traces {
282    /// List of traces.
283    pub traces: Option<Vec<Trace>>,
284}
285
286impl common::RequestValue for Traces {}
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 [`CloudTrace`] 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_cloudtrace1 as cloudtrace1;
303///
304/// # async fn dox() {
305/// use cloudtrace1::{CloudTrace, 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 = CloudTrace::new(client, auth);
336/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
337/// // like `patch_traces(...)`, `traces_get(...)` and `traces_list(...)`
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 CloudTrace<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    /// Gets a single trace by its ID.
355    ///
356    /// # Arguments
357    ///
358    /// * `projectId` - Required. ID of the Cloud project where the trace data is stored.
359    /// * `traceId` - Required. ID of the trace to return.
360    pub fn traces_get(&self, project_id: &str, trace_id: &str) -> ProjectTraceGetCall<'a, C> {
361        ProjectTraceGetCall {
362            hub: self.hub,
363            _project_id: project_id.to_string(),
364            _trace_id: trace_id.to_string(),
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    /// Returns a list of traces that match the specified filter conditions.
374    ///
375    /// # Arguments
376    ///
377    /// * `projectId` - Required. ID of the Cloud project where the trace data is stored.
378    pub fn traces_list(&self, project_id: &str) -> ProjectTraceListCall<'a, C> {
379        ProjectTraceListCall {
380            hub: self.hub,
381            _project_id: project_id.to_string(),
382            _view: Default::default(),
383            _start_time: Default::default(),
384            _page_token: Default::default(),
385            _page_size: Default::default(),
386            _order_by: Default::default(),
387            _filter: Default::default(),
388            _end_time: Default::default(),
389            _delegate: Default::default(),
390            _additional_params: Default::default(),
391            _scopes: Default::default(),
392        }
393    }
394
395    /// Create a builder to help you perform the following task:
396    ///
397    /// Sends trace spans to Cloud Trace. Spans cannot be updated. If the trace ID and span ID already exist, an additional copy of the span will be stored.
398    ///
399    /// # Arguments
400    ///
401    /// * `request` - No description provided.
402    /// * `projectId` - Required. ID of the Cloud project where the trace data is stored.
403    pub fn patch_traces(&self, request: Traces, project_id: &str) -> ProjectPatchTraceCall<'a, C> {
404        ProjectPatchTraceCall {
405            hub: self.hub,
406            _request: request,
407            _project_id: project_id.to_string(),
408            _delegate: Default::default(),
409            _additional_params: Default::default(),
410            _scopes: Default::default(),
411        }
412    }
413}
414
415// ###################
416// CallBuilders   ###
417// #################
418
419/// Gets a single trace by its ID.
420///
421/// A builder for the *traces.get* method supported by a *project* resource.
422/// It is not used directly, but through a [`ProjectMethods`] instance.
423///
424/// # Example
425///
426/// Instantiate a resource method builder
427///
428/// ```test_harness,no_run
429/// # extern crate hyper;
430/// # extern crate hyper_rustls;
431/// # extern crate google_cloudtrace1 as cloudtrace1;
432/// # async fn dox() {
433/// # use cloudtrace1::{CloudTrace, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
434///
435/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
436/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
437/// #     .with_native_roots()
438/// #     .unwrap()
439/// #     .https_only()
440/// #     .enable_http2()
441/// #     .build();
442///
443/// # let executor = hyper_util::rt::TokioExecutor::new();
444/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
445/// #     secret,
446/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
447/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
448/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
449/// #     ),
450/// # ).build().await.unwrap();
451///
452/// # let client = hyper_util::client::legacy::Client::builder(
453/// #     hyper_util::rt::TokioExecutor::new()
454/// # )
455/// # .build(
456/// #     hyper_rustls::HttpsConnectorBuilder::new()
457/// #         .with_native_roots()
458/// #         .unwrap()
459/// #         .https_or_http()
460/// #         .enable_http2()
461/// #         .build()
462/// # );
463/// # let mut hub = CloudTrace::new(client, auth);
464/// // You can configure optional parameters by calling the respective setters at will, and
465/// // execute the final call using `doit()`.
466/// // Values shown here are possibly random and not representative !
467/// let result = hub.projects().traces_get("projectId", "traceId")
468///              .doit().await;
469/// # }
470/// ```
471pub struct ProjectTraceGetCall<'a, C>
472where
473    C: 'a,
474{
475    hub: &'a CloudTrace<C>,
476    _project_id: String,
477    _trace_id: String,
478    _delegate: Option<&'a mut dyn common::Delegate>,
479    _additional_params: HashMap<String, String>,
480    _scopes: BTreeSet<String>,
481}
482
483impl<'a, C> common::CallBuilder for ProjectTraceGetCall<'a, C> {}
484
485impl<'a, C> ProjectTraceGetCall<'a, C>
486where
487    C: common::Connector,
488{
489    /// Perform the operation you have build so far.
490    pub async fn doit(mut self) -> common::Result<(common::Response, Trace)> {
491        use std::borrow::Cow;
492        use std::io::{Read, Seek};
493
494        use common::{url::Params, ToParts};
495        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
496
497        let mut dd = common::DefaultDelegate;
498        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
499        dlg.begin(common::MethodInfo {
500            id: "cloudtrace.projects.traces.get",
501            http_method: hyper::Method::GET,
502        });
503
504        for &field in ["alt", "projectId", "traceId"].iter() {
505            if self._additional_params.contains_key(field) {
506                dlg.finished(false);
507                return Err(common::Error::FieldClash(field));
508            }
509        }
510
511        let mut params = Params::with_capacity(4 + self._additional_params.len());
512        params.push("projectId", self._project_id);
513        params.push("traceId", self._trace_id);
514
515        params.extend(self._additional_params.iter());
516
517        params.push("alt", "json");
518        let mut url = self.hub._base_url.clone() + "v1/projects/{projectId}/traces/{traceId}";
519        if self._scopes.is_empty() {
520            self._scopes
521                .insert(Scope::TraceReadonly.as_ref().to_string());
522        }
523
524        #[allow(clippy::single_element_loop)]
525        for &(find_this, param_name) in
526            [("{projectId}", "projectId"), ("{traceId}", "traceId")].iter()
527        {
528            url = params.uri_replacement(url, param_name, find_this, false);
529        }
530        {
531            let to_remove = ["traceId", "projectId"];
532            params.remove_params(&to_remove);
533        }
534
535        let url = params.parse_with_url(&url);
536
537        loop {
538            let token = match self
539                .hub
540                .auth
541                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
542                .await
543            {
544                Ok(token) => token,
545                Err(e) => match dlg.token(e) {
546                    Ok(token) => token,
547                    Err(e) => {
548                        dlg.finished(false);
549                        return Err(common::Error::MissingToken(e));
550                    }
551                },
552            };
553            let mut req_result = {
554                let client = &self.hub.client;
555                dlg.pre_request();
556                let mut req_builder = hyper::Request::builder()
557                    .method(hyper::Method::GET)
558                    .uri(url.as_str())
559                    .header(USER_AGENT, self.hub._user_agent.clone());
560
561                if let Some(token) = token.as_ref() {
562                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
563                }
564
565                let request = req_builder
566                    .header(CONTENT_LENGTH, 0_u64)
567                    .body(common::to_body::<String>(None));
568
569                client.request(request.unwrap()).await
570            };
571
572            match req_result {
573                Err(err) => {
574                    if let common::Retry::After(d) = dlg.http_error(&err) {
575                        sleep(d).await;
576                        continue;
577                    }
578                    dlg.finished(false);
579                    return Err(common::Error::HttpError(err));
580                }
581                Ok(res) => {
582                    let (mut parts, body) = res.into_parts();
583                    let mut body = common::Body::new(body);
584                    if !parts.status.is_success() {
585                        let bytes = common::to_bytes(body).await.unwrap_or_default();
586                        let error = serde_json::from_str(&common::to_string(&bytes));
587                        let response = common::to_response(parts, bytes.into());
588
589                        if let common::Retry::After(d) =
590                            dlg.http_failure(&response, error.as_ref().ok())
591                        {
592                            sleep(d).await;
593                            continue;
594                        }
595
596                        dlg.finished(false);
597
598                        return Err(match error {
599                            Ok(value) => common::Error::BadRequest(value),
600                            _ => common::Error::Failure(response),
601                        });
602                    }
603                    let response = {
604                        let bytes = common::to_bytes(body).await.unwrap_or_default();
605                        let encoded = common::to_string(&bytes);
606                        match serde_json::from_str(&encoded) {
607                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
608                            Err(error) => {
609                                dlg.response_json_decode_error(&encoded, &error);
610                                return Err(common::Error::JsonDecodeError(
611                                    encoded.to_string(),
612                                    error,
613                                ));
614                            }
615                        }
616                    };
617
618                    dlg.finished(true);
619                    return Ok(response);
620                }
621            }
622        }
623    }
624
625    /// Required. ID of the Cloud project where the trace data is stored.
626    ///
627    /// Sets the *project id* path property to the given value.
628    ///
629    /// Even though the property as already been set when instantiating this call,
630    /// we provide this method for API completeness.
631    pub fn project_id(mut self, new_value: &str) -> ProjectTraceGetCall<'a, C> {
632        self._project_id = new_value.to_string();
633        self
634    }
635    /// Required. ID of the trace to return.
636    ///
637    /// Sets the *trace id* path property to the given value.
638    ///
639    /// Even though the property as already been set when instantiating this call,
640    /// we provide this method for API completeness.
641    pub fn trace_id(mut self, new_value: &str) -> ProjectTraceGetCall<'a, C> {
642        self._trace_id = new_value.to_string();
643        self
644    }
645    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
646    /// while executing the actual API request.
647    ///
648    /// ````text
649    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
650    /// ````
651    ///
652    /// Sets the *delegate* property to the given value.
653    pub fn delegate(
654        mut self,
655        new_value: &'a mut dyn common::Delegate,
656    ) -> ProjectTraceGetCall<'a, C> {
657        self._delegate = Some(new_value);
658        self
659    }
660
661    /// Set any additional parameter of the query string used in the request.
662    /// It should be used to set parameters which are not yet available through their own
663    /// setters.
664    ///
665    /// Please note that this method must not be used to set any of the known parameters
666    /// which have their own setter method. If done anyway, the request will fail.
667    ///
668    /// # Additional Parameters
669    ///
670    /// * *$.xgafv* (query-string) - V1 error format.
671    /// * *access_token* (query-string) - OAuth access token.
672    /// * *alt* (query-string) - Data format for response.
673    /// * *callback* (query-string) - JSONP
674    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
675    /// * *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.
676    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
677    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
678    /// * *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.
679    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
680    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
681    pub fn param<T>(mut self, name: T, value: T) -> ProjectTraceGetCall<'a, C>
682    where
683        T: AsRef<str>,
684    {
685        self._additional_params
686            .insert(name.as_ref().to_string(), value.as_ref().to_string());
687        self
688    }
689
690    /// Identifies the authorization scope for the method you are building.
691    ///
692    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
693    /// [`Scope::TraceReadonly`].
694    ///
695    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
696    /// tokens for more than one scope.
697    ///
698    /// Usually there is more than one suitable scope to authorize an operation, some of which may
699    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
700    /// sufficient, a read-write scope will do as well.
701    pub fn add_scope<St>(mut self, scope: St) -> ProjectTraceGetCall<'a, C>
702    where
703        St: AsRef<str>,
704    {
705        self._scopes.insert(String::from(scope.as_ref()));
706        self
707    }
708    /// Identifies the authorization scope(s) for the method you are building.
709    ///
710    /// See [`Self::add_scope()`] for details.
711    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectTraceGetCall<'a, C>
712    where
713        I: IntoIterator<Item = St>,
714        St: AsRef<str>,
715    {
716        self._scopes
717            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
718        self
719    }
720
721    /// Removes all scopes, and no default scope will be used either.
722    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
723    /// for details).
724    pub fn clear_scopes(mut self) -> ProjectTraceGetCall<'a, C> {
725        self._scopes.clear();
726        self
727    }
728}
729
730/// Returns a list of traces that match the specified filter conditions.
731///
732/// A builder for the *traces.list* method supported by a *project* resource.
733/// It is not used directly, but through a [`ProjectMethods`] instance.
734///
735/// # Example
736///
737/// Instantiate a resource method builder
738///
739/// ```test_harness,no_run
740/// # extern crate hyper;
741/// # extern crate hyper_rustls;
742/// # extern crate google_cloudtrace1 as cloudtrace1;
743/// # async fn dox() {
744/// # use cloudtrace1::{CloudTrace, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
745///
746/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
747/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
748/// #     .with_native_roots()
749/// #     .unwrap()
750/// #     .https_only()
751/// #     .enable_http2()
752/// #     .build();
753///
754/// # let executor = hyper_util::rt::TokioExecutor::new();
755/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
756/// #     secret,
757/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
758/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
759/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
760/// #     ),
761/// # ).build().await.unwrap();
762///
763/// # let client = hyper_util::client::legacy::Client::builder(
764/// #     hyper_util::rt::TokioExecutor::new()
765/// # )
766/// # .build(
767/// #     hyper_rustls::HttpsConnectorBuilder::new()
768/// #         .with_native_roots()
769/// #         .unwrap()
770/// #         .https_or_http()
771/// #         .enable_http2()
772/// #         .build()
773/// # );
774/// # let mut hub = CloudTrace::new(client, auth);
775/// // You can configure optional parameters by calling the respective setters at will, and
776/// // execute the final call using `doit()`.
777/// // Values shown here are possibly random and not representative !
778/// let result = hub.projects().traces_list("projectId")
779///              .view("takimata")
780///              .start_time(chrono::Utc::now())
781///              .page_token("amet.")
782///              .page_size(-20)
783///              .order_by("ipsum")
784///              .filter("gubergren")
785///              .end_time(chrono::Utc::now())
786///              .doit().await;
787/// # }
788/// ```
789pub struct ProjectTraceListCall<'a, C>
790where
791    C: 'a,
792{
793    hub: &'a CloudTrace<C>,
794    _project_id: String,
795    _view: Option<String>,
796    _start_time: Option<chrono::DateTime<chrono::offset::Utc>>,
797    _page_token: Option<String>,
798    _page_size: Option<i32>,
799    _order_by: Option<String>,
800    _filter: Option<String>,
801    _end_time: Option<chrono::DateTime<chrono::offset::Utc>>,
802    _delegate: Option<&'a mut dyn common::Delegate>,
803    _additional_params: HashMap<String, String>,
804    _scopes: BTreeSet<String>,
805}
806
807impl<'a, C> common::CallBuilder for ProjectTraceListCall<'a, C> {}
808
809impl<'a, C> ProjectTraceListCall<'a, C>
810where
811    C: common::Connector,
812{
813    /// Perform the operation you have build so far.
814    pub async fn doit(mut self) -> common::Result<(common::Response, ListTracesResponse)> {
815        use std::borrow::Cow;
816        use std::io::{Read, Seek};
817
818        use common::{url::Params, ToParts};
819        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
820
821        let mut dd = common::DefaultDelegate;
822        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
823        dlg.begin(common::MethodInfo {
824            id: "cloudtrace.projects.traces.list",
825            http_method: hyper::Method::GET,
826        });
827
828        for &field in [
829            "alt",
830            "projectId",
831            "view",
832            "startTime",
833            "pageToken",
834            "pageSize",
835            "orderBy",
836            "filter",
837            "endTime",
838        ]
839        .iter()
840        {
841            if self._additional_params.contains_key(field) {
842                dlg.finished(false);
843                return Err(common::Error::FieldClash(field));
844            }
845        }
846
847        let mut params = Params::with_capacity(10 + self._additional_params.len());
848        params.push("projectId", self._project_id);
849        if let Some(value) = self._view.as_ref() {
850            params.push("view", value);
851        }
852        if let Some(value) = self._start_time.as_ref() {
853            params.push("startTime", common::serde::datetime_to_string(&value));
854        }
855        if let Some(value) = self._page_token.as_ref() {
856            params.push("pageToken", value);
857        }
858        if let Some(value) = self._page_size.as_ref() {
859            params.push("pageSize", value.to_string());
860        }
861        if let Some(value) = self._order_by.as_ref() {
862            params.push("orderBy", value);
863        }
864        if let Some(value) = self._filter.as_ref() {
865            params.push("filter", value);
866        }
867        if let Some(value) = self._end_time.as_ref() {
868            params.push("endTime", common::serde::datetime_to_string(&value));
869        }
870
871        params.extend(self._additional_params.iter());
872
873        params.push("alt", "json");
874        let mut url = self.hub._base_url.clone() + "v1/projects/{projectId}/traces";
875        if self._scopes.is_empty() {
876            self._scopes
877                .insert(Scope::TraceReadonly.as_ref().to_string());
878        }
879
880        #[allow(clippy::single_element_loop)]
881        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
882            url = params.uri_replacement(url, param_name, find_this, false);
883        }
884        {
885            let to_remove = ["projectId"];
886            params.remove_params(&to_remove);
887        }
888
889        let url = params.parse_with_url(&url);
890
891        loop {
892            let token = match self
893                .hub
894                .auth
895                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
896                .await
897            {
898                Ok(token) => token,
899                Err(e) => match dlg.token(e) {
900                    Ok(token) => token,
901                    Err(e) => {
902                        dlg.finished(false);
903                        return Err(common::Error::MissingToken(e));
904                    }
905                },
906            };
907            let mut req_result = {
908                let client = &self.hub.client;
909                dlg.pre_request();
910                let mut req_builder = hyper::Request::builder()
911                    .method(hyper::Method::GET)
912                    .uri(url.as_str())
913                    .header(USER_AGENT, self.hub._user_agent.clone());
914
915                if let Some(token) = token.as_ref() {
916                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
917                }
918
919                let request = req_builder
920                    .header(CONTENT_LENGTH, 0_u64)
921                    .body(common::to_body::<String>(None));
922
923                client.request(request.unwrap()).await
924            };
925
926            match req_result {
927                Err(err) => {
928                    if let common::Retry::After(d) = dlg.http_error(&err) {
929                        sleep(d).await;
930                        continue;
931                    }
932                    dlg.finished(false);
933                    return Err(common::Error::HttpError(err));
934                }
935                Ok(res) => {
936                    let (mut parts, body) = res.into_parts();
937                    let mut body = common::Body::new(body);
938                    if !parts.status.is_success() {
939                        let bytes = common::to_bytes(body).await.unwrap_or_default();
940                        let error = serde_json::from_str(&common::to_string(&bytes));
941                        let response = common::to_response(parts, bytes.into());
942
943                        if let common::Retry::After(d) =
944                            dlg.http_failure(&response, error.as_ref().ok())
945                        {
946                            sleep(d).await;
947                            continue;
948                        }
949
950                        dlg.finished(false);
951
952                        return Err(match error {
953                            Ok(value) => common::Error::BadRequest(value),
954                            _ => common::Error::Failure(response),
955                        });
956                    }
957                    let response = {
958                        let bytes = common::to_bytes(body).await.unwrap_or_default();
959                        let encoded = common::to_string(&bytes);
960                        match serde_json::from_str(&encoded) {
961                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
962                            Err(error) => {
963                                dlg.response_json_decode_error(&encoded, &error);
964                                return Err(common::Error::JsonDecodeError(
965                                    encoded.to_string(),
966                                    error,
967                                ));
968                            }
969                        }
970                    };
971
972                    dlg.finished(true);
973                    return Ok(response);
974                }
975            }
976        }
977    }
978
979    /// Required. ID of the Cloud project where the trace data is stored.
980    ///
981    /// Sets the *project id* path property to the given value.
982    ///
983    /// Even though the property as already been set when instantiating this call,
984    /// we provide this method for API completeness.
985    pub fn project_id(mut self, new_value: &str) -> ProjectTraceListCall<'a, C> {
986        self._project_id = new_value.to_string();
987        self
988    }
989    /// Optional. Type of data returned for traces in the list. Default is `MINIMAL`.
990    ///
991    /// Sets the *view* query property to the given value.
992    pub fn view(mut self, new_value: &str) -> ProjectTraceListCall<'a, C> {
993        self._view = Some(new_value.to_string());
994        self
995    }
996    /// Start of the time interval (inclusive) during which the trace data was collected from the application.
997    ///
998    /// Sets the *start time* query property to the given value.
999    pub fn start_time(
1000        mut self,
1001        new_value: chrono::DateTime<chrono::offset::Utc>,
1002    ) -> ProjectTraceListCall<'a, C> {
1003        self._start_time = Some(new_value);
1004        self
1005    }
1006    /// Token identifying the page of results to return. If provided, use the value of the `next_page_token` field from a previous request.
1007    ///
1008    /// Sets the *page token* query property to the given value.
1009    pub fn page_token(mut self, new_value: &str) -> ProjectTraceListCall<'a, C> {
1010        self._page_token = Some(new_value.to_string());
1011        self
1012    }
1013    /// Optional. Maximum number of traces to return. If not specified or <= 0, the implementation selects a reasonable value. The implementation may return fewer traces than the requested page size.
1014    ///
1015    /// Sets the *page size* query property to the given value.
1016    pub fn page_size(mut self, new_value: i32) -> ProjectTraceListCall<'a, C> {
1017        self._page_size = Some(new_value);
1018        self
1019    }
1020    /// Optional. Field used to sort the returned traces. Can be one of the following: * `trace_id` * `name` (`name` field of root span in the trace) * `duration` (difference between `end_time` and `start_time` fields of the root span) * `start` (`start_time` field of the root span) Descending order can be specified by appending `desc` to the sort field (for example, `name desc`). Only one sort field is permitted.
1021    ///
1022    /// Sets the *order by* query property to the given value.
1023    pub fn order_by(mut self, new_value: &str) -> ProjectTraceListCall<'a, C> {
1024        self._order_by = Some(new_value.to_string());
1025        self
1026    }
1027    /// Optional. A filter against properties of the trace. See [filter syntax documentation](https://cloud.google.com/trace/docs/trace-filters) for details.
1028    ///
1029    /// Sets the *filter* query property to the given value.
1030    pub fn filter(mut self, new_value: &str) -> ProjectTraceListCall<'a, C> {
1031        self._filter = Some(new_value.to_string());
1032        self
1033    }
1034    /// End of the time interval (inclusive) during which the trace data was collected from the application.
1035    ///
1036    /// Sets the *end time* query property to the given value.
1037    pub fn end_time(
1038        mut self,
1039        new_value: chrono::DateTime<chrono::offset::Utc>,
1040    ) -> ProjectTraceListCall<'a, C> {
1041        self._end_time = Some(new_value);
1042        self
1043    }
1044    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1045    /// while executing the actual API request.
1046    ///
1047    /// ````text
1048    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1049    /// ````
1050    ///
1051    /// Sets the *delegate* property to the given value.
1052    pub fn delegate(
1053        mut self,
1054        new_value: &'a mut dyn common::Delegate,
1055    ) -> ProjectTraceListCall<'a, C> {
1056        self._delegate = Some(new_value);
1057        self
1058    }
1059
1060    /// Set any additional parameter of the query string used in the request.
1061    /// It should be used to set parameters which are not yet available through their own
1062    /// setters.
1063    ///
1064    /// Please note that this method must not be used to set any of the known parameters
1065    /// which have their own setter method. If done anyway, the request will fail.
1066    ///
1067    /// # Additional Parameters
1068    ///
1069    /// * *$.xgafv* (query-string) - V1 error format.
1070    /// * *access_token* (query-string) - OAuth access token.
1071    /// * *alt* (query-string) - Data format for response.
1072    /// * *callback* (query-string) - JSONP
1073    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1074    /// * *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.
1075    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1076    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1077    /// * *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.
1078    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1079    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1080    pub fn param<T>(mut self, name: T, value: T) -> ProjectTraceListCall<'a, C>
1081    where
1082        T: AsRef<str>,
1083    {
1084        self._additional_params
1085            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1086        self
1087    }
1088
1089    /// Identifies the authorization scope for the method you are building.
1090    ///
1091    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1092    /// [`Scope::TraceReadonly`].
1093    ///
1094    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1095    /// tokens for more than one scope.
1096    ///
1097    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1098    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1099    /// sufficient, a read-write scope will do as well.
1100    pub fn add_scope<St>(mut self, scope: St) -> ProjectTraceListCall<'a, C>
1101    where
1102        St: AsRef<str>,
1103    {
1104        self._scopes.insert(String::from(scope.as_ref()));
1105        self
1106    }
1107    /// Identifies the authorization scope(s) for the method you are building.
1108    ///
1109    /// See [`Self::add_scope()`] for details.
1110    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectTraceListCall<'a, C>
1111    where
1112        I: IntoIterator<Item = St>,
1113        St: AsRef<str>,
1114    {
1115        self._scopes
1116            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1117        self
1118    }
1119
1120    /// Removes all scopes, and no default scope will be used either.
1121    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1122    /// for details).
1123    pub fn clear_scopes(mut self) -> ProjectTraceListCall<'a, C> {
1124        self._scopes.clear();
1125        self
1126    }
1127}
1128
1129/// Sends trace spans to Cloud Trace. Spans cannot be updated. If the trace ID and span ID already exist, an additional copy of the span will be stored.
1130///
1131/// A builder for the *patchTraces* method supported by a *project* resource.
1132/// It is not used directly, but through a [`ProjectMethods`] instance.
1133///
1134/// # Example
1135///
1136/// Instantiate a resource method builder
1137///
1138/// ```test_harness,no_run
1139/// # extern crate hyper;
1140/// # extern crate hyper_rustls;
1141/// # extern crate google_cloudtrace1 as cloudtrace1;
1142/// use cloudtrace1::api::Traces;
1143/// # async fn dox() {
1144/// # use cloudtrace1::{CloudTrace, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1145///
1146/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1147/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1148/// #     .with_native_roots()
1149/// #     .unwrap()
1150/// #     .https_only()
1151/// #     .enable_http2()
1152/// #     .build();
1153///
1154/// # let executor = hyper_util::rt::TokioExecutor::new();
1155/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1156/// #     secret,
1157/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1158/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1159/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1160/// #     ),
1161/// # ).build().await.unwrap();
1162///
1163/// # let client = hyper_util::client::legacy::Client::builder(
1164/// #     hyper_util::rt::TokioExecutor::new()
1165/// # )
1166/// # .build(
1167/// #     hyper_rustls::HttpsConnectorBuilder::new()
1168/// #         .with_native_roots()
1169/// #         .unwrap()
1170/// #         .https_or_http()
1171/// #         .enable_http2()
1172/// #         .build()
1173/// # );
1174/// # let mut hub = CloudTrace::new(client, auth);
1175/// // As the method needs a request, you would usually fill it with the desired information
1176/// // into the respective structure. Some of the parts shown here might not be applicable !
1177/// // Values shown here are possibly random and not representative !
1178/// let mut req = Traces::default();
1179///
1180/// // You can configure optional parameters by calling the respective setters at will, and
1181/// // execute the final call using `doit()`.
1182/// // Values shown here are possibly random and not representative !
1183/// let result = hub.projects().patch_traces(req, "projectId")
1184///              .doit().await;
1185/// # }
1186/// ```
1187pub struct ProjectPatchTraceCall<'a, C>
1188where
1189    C: 'a,
1190{
1191    hub: &'a CloudTrace<C>,
1192    _request: Traces,
1193    _project_id: String,
1194    _delegate: Option<&'a mut dyn common::Delegate>,
1195    _additional_params: HashMap<String, String>,
1196    _scopes: BTreeSet<String>,
1197}
1198
1199impl<'a, C> common::CallBuilder for ProjectPatchTraceCall<'a, C> {}
1200
1201impl<'a, C> ProjectPatchTraceCall<'a, C>
1202where
1203    C: common::Connector,
1204{
1205    /// Perform the operation you have build so far.
1206    pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
1207        use std::borrow::Cow;
1208        use std::io::{Read, Seek};
1209
1210        use common::{url::Params, ToParts};
1211        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1212
1213        let mut dd = common::DefaultDelegate;
1214        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1215        dlg.begin(common::MethodInfo {
1216            id: "cloudtrace.projects.patchTraces",
1217            http_method: hyper::Method::PATCH,
1218        });
1219
1220        for &field in ["alt", "projectId"].iter() {
1221            if self._additional_params.contains_key(field) {
1222                dlg.finished(false);
1223                return Err(common::Error::FieldClash(field));
1224            }
1225        }
1226
1227        let mut params = Params::with_capacity(4 + self._additional_params.len());
1228        params.push("projectId", self._project_id);
1229
1230        params.extend(self._additional_params.iter());
1231
1232        params.push("alt", "json");
1233        let mut url = self.hub._base_url.clone() + "v1/projects/{projectId}/traces";
1234        if self._scopes.is_empty() {
1235            self._scopes
1236                .insert(Scope::CloudPlatform.as_ref().to_string());
1237        }
1238
1239        #[allow(clippy::single_element_loop)]
1240        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
1241            url = params.uri_replacement(url, param_name, find_this, false);
1242        }
1243        {
1244            let to_remove = ["projectId"];
1245            params.remove_params(&to_remove);
1246        }
1247
1248        let url = params.parse_with_url(&url);
1249
1250        let mut json_mime_type = mime::APPLICATION_JSON;
1251        let mut request_value_reader = {
1252            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1253            common::remove_json_null_values(&mut value);
1254            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1255            serde_json::to_writer(&mut dst, &value).unwrap();
1256            dst
1257        };
1258        let request_size = request_value_reader
1259            .seek(std::io::SeekFrom::End(0))
1260            .unwrap();
1261        request_value_reader
1262            .seek(std::io::SeekFrom::Start(0))
1263            .unwrap();
1264
1265        loop {
1266            let token = match self
1267                .hub
1268                .auth
1269                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1270                .await
1271            {
1272                Ok(token) => token,
1273                Err(e) => match dlg.token(e) {
1274                    Ok(token) => token,
1275                    Err(e) => {
1276                        dlg.finished(false);
1277                        return Err(common::Error::MissingToken(e));
1278                    }
1279                },
1280            };
1281            request_value_reader
1282                .seek(std::io::SeekFrom::Start(0))
1283                .unwrap();
1284            let mut req_result = {
1285                let client = &self.hub.client;
1286                dlg.pre_request();
1287                let mut req_builder = hyper::Request::builder()
1288                    .method(hyper::Method::PATCH)
1289                    .uri(url.as_str())
1290                    .header(USER_AGENT, self.hub._user_agent.clone());
1291
1292                if let Some(token) = token.as_ref() {
1293                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1294                }
1295
1296                let request = req_builder
1297                    .header(CONTENT_TYPE, json_mime_type.to_string())
1298                    .header(CONTENT_LENGTH, request_size as u64)
1299                    .body(common::to_body(
1300                        request_value_reader.get_ref().clone().into(),
1301                    ));
1302
1303                client.request(request.unwrap()).await
1304            };
1305
1306            match req_result {
1307                Err(err) => {
1308                    if let common::Retry::After(d) = dlg.http_error(&err) {
1309                        sleep(d).await;
1310                        continue;
1311                    }
1312                    dlg.finished(false);
1313                    return Err(common::Error::HttpError(err));
1314                }
1315                Ok(res) => {
1316                    let (mut parts, body) = res.into_parts();
1317                    let mut body = common::Body::new(body);
1318                    if !parts.status.is_success() {
1319                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1320                        let error = serde_json::from_str(&common::to_string(&bytes));
1321                        let response = common::to_response(parts, bytes.into());
1322
1323                        if let common::Retry::After(d) =
1324                            dlg.http_failure(&response, error.as_ref().ok())
1325                        {
1326                            sleep(d).await;
1327                            continue;
1328                        }
1329
1330                        dlg.finished(false);
1331
1332                        return Err(match error {
1333                            Ok(value) => common::Error::BadRequest(value),
1334                            _ => common::Error::Failure(response),
1335                        });
1336                    }
1337                    let response = {
1338                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1339                        let encoded = common::to_string(&bytes);
1340                        match serde_json::from_str(&encoded) {
1341                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1342                            Err(error) => {
1343                                dlg.response_json_decode_error(&encoded, &error);
1344                                return Err(common::Error::JsonDecodeError(
1345                                    encoded.to_string(),
1346                                    error,
1347                                ));
1348                            }
1349                        }
1350                    };
1351
1352                    dlg.finished(true);
1353                    return Ok(response);
1354                }
1355            }
1356        }
1357    }
1358
1359    ///
1360    /// Sets the *request* property to the given value.
1361    ///
1362    /// Even though the property as already been set when instantiating this call,
1363    /// we provide this method for API completeness.
1364    pub fn request(mut self, new_value: Traces) -> ProjectPatchTraceCall<'a, C> {
1365        self._request = new_value;
1366        self
1367    }
1368    /// Required. ID of the Cloud project where the trace data is stored.
1369    ///
1370    /// Sets the *project id* path property to the given value.
1371    ///
1372    /// Even though the property as already been set when instantiating this call,
1373    /// we provide this method for API completeness.
1374    pub fn project_id(mut self, new_value: &str) -> ProjectPatchTraceCall<'a, C> {
1375        self._project_id = new_value.to_string();
1376        self
1377    }
1378    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1379    /// while executing the actual API request.
1380    ///
1381    /// ````text
1382    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1383    /// ````
1384    ///
1385    /// Sets the *delegate* property to the given value.
1386    pub fn delegate(
1387        mut self,
1388        new_value: &'a mut dyn common::Delegate,
1389    ) -> ProjectPatchTraceCall<'a, C> {
1390        self._delegate = Some(new_value);
1391        self
1392    }
1393
1394    /// Set any additional parameter of the query string used in the request.
1395    /// It should be used to set parameters which are not yet available through their own
1396    /// setters.
1397    ///
1398    /// Please note that this method must not be used to set any of the known parameters
1399    /// which have their own setter method. If done anyway, the request will fail.
1400    ///
1401    /// # Additional Parameters
1402    ///
1403    /// * *$.xgafv* (query-string) - V1 error format.
1404    /// * *access_token* (query-string) - OAuth access token.
1405    /// * *alt* (query-string) - Data format for response.
1406    /// * *callback* (query-string) - JSONP
1407    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1408    /// * *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.
1409    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1410    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1411    /// * *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.
1412    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1413    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1414    pub fn param<T>(mut self, name: T, value: T) -> ProjectPatchTraceCall<'a, C>
1415    where
1416        T: AsRef<str>,
1417    {
1418        self._additional_params
1419            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1420        self
1421    }
1422
1423    /// Identifies the authorization scope for the method you are building.
1424    ///
1425    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1426    /// [`Scope::CloudPlatform`].
1427    ///
1428    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1429    /// tokens for more than one scope.
1430    ///
1431    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1432    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1433    /// sufficient, a read-write scope will do as well.
1434    pub fn add_scope<St>(mut self, scope: St) -> ProjectPatchTraceCall<'a, C>
1435    where
1436        St: AsRef<str>,
1437    {
1438        self._scopes.insert(String::from(scope.as_ref()));
1439        self
1440    }
1441    /// Identifies the authorization scope(s) for the method you are building.
1442    ///
1443    /// See [`Self::add_scope()`] for details.
1444    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectPatchTraceCall<'a, C>
1445    where
1446        I: IntoIterator<Item = St>,
1447        St: AsRef<str>,
1448    {
1449        self._scopes
1450            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1451        self
1452    }
1453
1454    /// Removes all scopes, and no default scope will be used either.
1455    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1456    /// for details).
1457    pub fn clear_scopes(mut self) -> ProjectPatchTraceCall<'a, C> {
1458        self._scopes.clear();
1459        self
1460    }
1461}