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