google_cloudtrace2/
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
23impl AsRef<str> for Scope {
24    fn as_ref(&self) -> &str {
25        match *self {
26            Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
27            Scope::TraceAppend => "https://www.googleapis.com/auth/trace.append",
28        }
29    }
30}
31
32#[allow(clippy::derivable_impls)]
33impl Default for Scope {
34    fn default() -> Scope {
35        Scope::TraceAppend
36    }
37}
38
39// ########
40// HUB ###
41// ######
42
43/// Central instance to access all CloudTrace related resource activities
44///
45/// # Examples
46///
47/// Instantiate a new hub
48///
49/// ```test_harness,no_run
50/// extern crate hyper;
51/// extern crate hyper_rustls;
52/// extern crate google_cloudtrace2 as cloudtrace2;
53/// use cloudtrace2::api::Span;
54/// use cloudtrace2::{Result, Error};
55/// # async fn dox() {
56/// use cloudtrace2::{CloudTrace, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
57///
58/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
59/// // `client_secret`, among other things.
60/// let secret: yup_oauth2::ApplicationSecret = Default::default();
61/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
62/// // unless you replace  `None` with the desired Flow.
63/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
64/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
65/// // retrieve them from storage.
66/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
67///     .with_native_roots()
68///     .unwrap()
69///     .https_only()
70///     .enable_http2()
71///     .build();
72///
73/// let executor = hyper_util::rt::TokioExecutor::new();
74/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
75///     secret,
76///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
77///     yup_oauth2::client::CustomHyperClientBuilder::from(
78///         hyper_util::client::legacy::Client::builder(executor).build(connector),
79///     ),
80/// ).build().await.unwrap();
81///
82/// let client = hyper_util::client::legacy::Client::builder(
83///     hyper_util::rt::TokioExecutor::new()
84/// )
85/// .build(
86///     hyper_rustls::HttpsConnectorBuilder::new()
87///         .with_native_roots()
88///         .unwrap()
89///         .https_or_http()
90///         .enable_http2()
91///         .build()
92/// );
93/// let mut hub = CloudTrace::new(client, auth);
94/// // As the method needs a request, you would usually fill it with the desired information
95/// // into the respective structure. Some of the parts shown here might not be applicable !
96/// // Values shown here are possibly random and not representative !
97/// let mut req = Span::default();
98///
99/// // You can configure optional parameters by calling the respective setters at will, and
100/// // execute the final call using `doit()`.
101/// // Values shown here are possibly random and not representative !
102/// let result = hub.projects().traces_spans_create_span(req, "name")
103///              .doit().await;
104///
105/// match result {
106///     Err(e) => match e {
107///         // The Error enum provides details about what exactly happened.
108///         // You can also just use its `Debug`, `Display` or `Error` traits
109///          Error::HttpError(_)
110///         |Error::Io(_)
111///         |Error::MissingAPIKey
112///         |Error::MissingToken(_)
113///         |Error::Cancelled
114///         |Error::UploadSizeLimitExceeded(_, _)
115///         |Error::Failure(_)
116///         |Error::BadRequest(_)
117///         |Error::FieldClash(_)
118///         |Error::JsonDecodeError(_, _) => println!("{}", e),
119///     },
120///     Ok(res) => println!("Success: {:?}", res),
121/// }
122/// # }
123/// ```
124#[derive(Clone)]
125pub struct CloudTrace<C> {
126    pub client: common::Client<C>,
127    pub auth: Box<dyn common::GetToken>,
128    _user_agent: String,
129    _base_url: String,
130    _root_url: String,
131}
132
133impl<C> common::Hub for CloudTrace<C> {}
134
135impl<'a, C> CloudTrace<C> {
136    pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> CloudTrace<C> {
137        CloudTrace {
138            client,
139            auth: Box::new(auth),
140            _user_agent: "google-api-rust-client/7.0.0".to_string(),
141            _base_url: "https://cloudtrace.googleapis.com/".to_string(),
142            _root_url: "https://cloudtrace.googleapis.com/".to_string(),
143        }
144    }
145
146    pub fn projects(&'a self) -> ProjectMethods<'a, C> {
147        ProjectMethods { hub: self }
148    }
149
150    /// Set the user-agent header field to use in all requests to the server.
151    /// It defaults to `google-api-rust-client/7.0.0`.
152    ///
153    /// Returns the previously set user-agent.
154    pub fn user_agent(&mut self, agent_name: String) -> String {
155        std::mem::replace(&mut self._user_agent, agent_name)
156    }
157
158    /// Set the base url to use in all requests to the server.
159    /// It defaults to `https://cloudtrace.googleapis.com/`.
160    ///
161    /// Returns the previously set base url.
162    pub fn base_url(&mut self, new_base_url: String) -> String {
163        std::mem::replace(&mut self._base_url, new_base_url)
164    }
165
166    /// Set the root url to use in all requests to the server.
167    /// It defaults to `https://cloudtrace.googleapis.com/`.
168    ///
169    /// Returns the previously set root url.
170    pub fn root_url(&mut self, new_root_url: String) -> String {
171        std::mem::replace(&mut self._root_url, new_root_url)
172    }
173}
174
175// ############
176// SCHEMAS ###
177// ##########
178/// Text annotation with a set of attributes.
179///
180/// This type is not used in any activity, and only used as *part* of another schema.
181///
182#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
183#[serde_with::serde_as]
184#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
185pub struct Annotation {
186    /// A set of attributes on the annotation. You can have up to 4 attributes per Annotation.
187    pub attributes: Option<Attributes>,
188    /// A user-supplied message describing the event. The maximum length for the description is 256 bytes.
189    pub description: Option<TruncatableString>,
190}
191
192impl common::Part for Annotation {}
193
194/// The allowed types for `[VALUE]` in a `[KEY]:[VALUE]` attribute.
195///
196/// This type is not used in any activity, and only used as *part* of another schema.
197///
198#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
199#[serde_with::serde_as]
200#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
201pub struct AttributeValue {
202    /// A Boolean value represented by `true` or `false`.
203    #[serde(rename = "boolValue")]
204    pub bool_value: Option<bool>,
205    /// A 64-bit signed integer.
206    #[serde(rename = "intValue")]
207    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
208    pub int_value: Option<i64>,
209    /// A string up to 256 bytes long.
210    #[serde(rename = "stringValue")]
211    pub string_value: Option<TruncatableString>,
212}
213
214impl common::Part for AttributeValue {}
215
216/// A set of attributes as key-value pairs.
217///
218/// This type is not used in any activity, and only used as *part* of another schema.
219///
220#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
221#[serde_with::serde_as]
222#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
223pub struct Attributes {
224    /// A set of attributes. Each attribute's key can be up to 128 bytes long. The value can be a string up to 256 bytes, a signed 64-bit integer, or the boolean values `true` or `false`. For example: "/instance_id": { "string_value": { "value": "my-instance" } } "/http/request_bytes": { "int_value": 300 } "example.com/myattribute": { "bool_value": false }
225    #[serde(rename = "attributeMap")]
226    pub attribute_map: Option<HashMap<String, AttributeValue>>,
227    /// The number of attributes that were discarded. Attributes can be discarded because their keys are too long or because there are too many attributes. If this value is 0 then all attributes are valid.
228    #[serde(rename = "droppedAttributesCount")]
229    pub dropped_attributes_count: Option<i32>,
230}
231
232impl common::Part for Attributes {}
233
234/// The request message for the `BatchWriteSpans` method.
235///
236/// # Activities
237///
238/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
239/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
240///
241/// * [traces batch write projects](ProjectTraceBatchWriteCall) (request)
242#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
243#[serde_with::serde_as]
244#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
245pub struct BatchWriteSpansRequest {
246    /// Required. A list of new spans. The span names must not match existing spans, otherwise the results are undefined.
247    pub spans: Option<Vec<Span>>,
248}
249
250impl common::RequestValue for BatchWriteSpansRequest {}
251
252/// 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); }
253///
254/// # Activities
255///
256/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
257/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
258///
259/// * [traces batch write projects](ProjectTraceBatchWriteCall) (response)
260#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
261#[serde_with::serde_as]
262#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
263pub struct Empty {
264    _never_set: Option<bool>,
265}
266
267impl common::ResponseResult for Empty {}
268
269/// A pointer from the current span to another span in the same trace or in a different trace. For example, this can be used in batching operations, where a single batch handler processes multiple requests from different traces or when the handler receives a request from a different project.
270///
271/// This type is not used in any activity, and only used as *part* of another schema.
272///
273#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
274#[serde_with::serde_as]
275#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
276pub struct Link {
277    /// A set of attributes on the link. Up to 32 attributes can be specified per link.
278    pub attributes: Option<Attributes>,
279    /// The `[SPAN_ID]` for a span within a trace.
280    #[serde(rename = "spanId")]
281    pub span_id: Option<String>,
282    /// The `[TRACE_ID]` for a trace within a project.
283    #[serde(rename = "traceId")]
284    pub trace_id: Option<String>,
285    /// The relationship of the current span relative to the linked span.
286    #[serde(rename = "type")]
287    pub type_: Option<String>,
288}
289
290impl common::Part for Link {}
291
292/// A collection of links, which are references from this span to a span in the same or different trace.
293///
294/// This type is not used in any activity, and only used as *part* of another schema.
295///
296#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
297#[serde_with::serde_as]
298#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
299pub struct Links {
300    /// The number of dropped links after the maximum size was enforced. If this value is 0, then no links were dropped.
301    #[serde(rename = "droppedLinksCount")]
302    pub dropped_links_count: Option<i32>,
303    /// A collection of links.
304    pub link: Option<Vec<Link>>,
305}
306
307impl common::Part for Links {}
308
309/// An event describing a message sent/received between Spans.
310///
311/// This type is not used in any activity, and only used as *part* of another schema.
312///
313#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
314#[serde_with::serde_as]
315#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
316pub struct MessageEvent {
317    /// The number of compressed bytes sent or received. If missing, the compressed size is assumed to be the same size as the uncompressed size.
318    #[serde(rename = "compressedSizeBytes")]
319    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
320    pub compressed_size_bytes: Option<i64>,
321    /// An identifier for the MessageEvent's message that can be used to match `SENT` and `RECEIVED` MessageEvents.
322    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
323    pub id: Option<i64>,
324    /// Type of MessageEvent. Indicates whether the message was sent or received.
325    #[serde(rename = "type")]
326    pub type_: Option<String>,
327    /// The number of uncompressed bytes sent or received.
328    #[serde(rename = "uncompressedSizeBytes")]
329    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
330    pub uncompressed_size_bytes: Option<i64>,
331}
332
333impl common::Part for MessageEvent {}
334
335/// Binary module.
336///
337/// This type is not used in any activity, and only used as *part* of another schema.
338///
339#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
340#[serde_with::serde_as]
341#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
342pub struct Module {
343    /// A unique identifier for the module, usually a hash of its contents (up to 128 bytes).
344    #[serde(rename = "buildId")]
345    pub build_id: Option<TruncatableString>,
346    /// For example: main binary, kernel modules, and dynamic libraries such as libc.so, sharedlib.so (up to 256 bytes).
347    pub module: Option<TruncatableString>,
348}
349
350impl common::Part for Module {}
351
352/// A span represents a single operation within a trace. Spans can be nested to form a trace tree. Often, a trace contains a root span that describes the end-to-end latency, and one or more subspans for its sub-operations. A trace can also contain multiple root spans, or none at all. Spans do not need to be contiguous. There might be gaps or overlaps between spans in a trace.
353///
354/// # Activities
355///
356/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
357/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
358///
359/// * [traces spans create span projects](ProjectTraceSpanCreateSpanCall) (request|response)
360#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
361#[serde_with::serde_as]
362#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
363pub struct Span {
364    /// A set of attributes on the span. You can have up to 32 attributes per span.
365    pub attributes: Option<Attributes>,
366    /// Optional. The number of child spans that were generated while this span was active. If set, allows implementation to detect missing child spans.
367    #[serde(rename = "childSpanCount")]
368    pub child_span_count: Option<i32>,
369    /// Required. A description of the span's operation (up to 128 bytes). Cloud Trace displays the description in the Cloud console. For example, the display name can be a qualified method name or a file name and a line number where the operation is called. A best practice is to use the same display name within an application and at the same call point. This makes it easier to correlate spans in different traces.
370    #[serde(rename = "displayName")]
371    pub display_name: Option<TruncatableString>,
372    /// Required. The end time of the span. On the client side, this is the time kept by the local machine where the span execution ends. On the server side, this is the time when the server application handler stops running.
373    #[serde(rename = "endTime")]
374    pub end_time: Option<chrono::DateTime<chrono::offset::Utc>>,
375    /// Links associated with the span. You can have up to 128 links per Span.
376    pub links: Option<Links>,
377    /// Required. The resource name of the span in the following format: * `projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID]` `[TRACE_ID]` is a unique identifier for a trace within a project; it is a 32-character hexadecimal encoding of a 16-byte array. It should not be zero. `[SPAN_ID]` is a unique identifier for a span within a trace; it is a 16-character hexadecimal encoding of an 8-byte array. It should not be zero. .
378    pub name: Option<String>,
379    /// The `[SPAN_ID]` of this span's parent span. If this is a root span, then this field must be empty.
380    #[serde(rename = "parentSpanId")]
381    pub parent_span_id: Option<String>,
382    /// Optional. Set this parameter to indicate whether this span is in the same process as its parent. If you do not set this parameter, Trace is unable to take advantage of this helpful information.
383    #[serde(rename = "sameProcessAsParentSpan")]
384    pub same_process_as_parent_span: Option<bool>,
385    /// Required. The `[SPAN_ID]` portion of the span's resource name.
386    #[serde(rename = "spanId")]
387    pub span_id: Option<String>,
388    /// Optional. Distinguishes between spans generated in a particular context. For example, two spans with the same name may be distinguished using `CLIENT` (caller) and `SERVER` (callee) to identify an RPC call.
389    #[serde(rename = "spanKind")]
390    pub span_kind: Option<String>,
391    /// Stack trace captured at the start of the span.
392    #[serde(rename = "stackTrace")]
393    pub stack_trace: Option<StackTrace>,
394    /// Required. The start time of the span. On the client side, this is the time kept by the local machine where the span execution starts. On the server side, this is the time when the server's application handler starts running.
395    #[serde(rename = "startTime")]
396    pub start_time: Option<chrono::DateTime<chrono::offset::Utc>>,
397    /// Optional. The final status for this span.
398    pub status: Option<Status>,
399    /// A set of time events. You can have up to 32 annotations and 128 message events per span.
400    #[serde(rename = "timeEvents")]
401    pub time_events: Option<TimeEvents>,
402}
403
404impl common::RequestValue for Span {}
405impl common::ResponseResult for Span {}
406
407/// Represents a single stack frame in a stack trace.
408///
409/// This type is not used in any activity, and only used as *part* of another schema.
410///
411#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
412#[serde_with::serde_as]
413#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
414pub struct StackFrame {
415    /// The column number where the function call appears, if available. This is important in JavaScript because of its anonymous functions.
416    #[serde(rename = "columnNumber")]
417    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
418    pub column_number: Option<i64>,
419    /// The name of the source file where the function call appears (up to 256 bytes).
420    #[serde(rename = "fileName")]
421    pub file_name: Option<TruncatableString>,
422    /// The fully-qualified name that uniquely identifies the function or method that is active in this frame (up to 1024 bytes).
423    #[serde(rename = "functionName")]
424    pub function_name: Option<TruncatableString>,
425    /// The line number in `file_name` where the function call appears.
426    #[serde(rename = "lineNumber")]
427    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
428    pub line_number: Option<i64>,
429    /// The binary module from where the code was loaded.
430    #[serde(rename = "loadModule")]
431    pub load_module: Option<Module>,
432    /// An un-mangled function name, if `function_name` is mangled. To get information about name mangling, run [this search](https://www.google.com/search?q=cxx+name+mangling). The name can be fully-qualified (up to 1024 bytes).
433    #[serde(rename = "originalFunctionName")]
434    pub original_function_name: Option<TruncatableString>,
435    /// The version of the deployed source code (up to 128 bytes).
436    #[serde(rename = "sourceVersion")]
437    pub source_version: Option<TruncatableString>,
438}
439
440impl common::Part for StackFrame {}
441
442/// A collection of stack frames, which can be truncated.
443///
444/// This type is not used in any activity, and only used as *part* of another schema.
445///
446#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
447#[serde_with::serde_as]
448#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
449pub struct StackFrames {
450    /// The number of stack frames that were dropped because there were too many stack frames. If this value is 0, then no stack frames were dropped.
451    #[serde(rename = "droppedFramesCount")]
452    pub dropped_frames_count: Option<i32>,
453    /// Stack frames in this call stack.
454    pub frame: Option<Vec<StackFrame>>,
455}
456
457impl common::Part for StackFrames {}
458
459/// A call stack appearing in a trace.
460///
461/// This type is not used in any activity, and only used as *part* of another schema.
462///
463#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
464#[serde_with::serde_as]
465#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
466pub struct StackTrace {
467    /// Stack frames in this stack trace. A maximum of 128 frames are allowed.
468    #[serde(rename = "stackFrames")]
469    pub stack_frames: Option<StackFrames>,
470    /// The hash ID is used to conserve network bandwidth for duplicate stack traces within a single trace. Often multiple spans will have identical stack traces. The first occurrence of a stack trace should contain both the `stackFrame` content and a value in `stackTraceHashId`. Subsequent spans within the same request can refer to that stack trace by only setting `stackTraceHashId`.
471    #[serde(rename = "stackTraceHashId")]
472    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
473    pub stack_trace_hash_id: Option<i64>,
474}
475
476impl common::Part for StackTrace {}
477
478/// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
479///
480/// This type is not used in any activity, and only used as *part* of another schema.
481///
482#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
483#[serde_with::serde_as]
484#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
485pub struct Status {
486    /// The status code, which should be an enum value of google.rpc.Code.
487    pub code: Option<i32>,
488    /// A list of messages that carry the error details. There is a common set of message types for APIs to use.
489    pub details: Option<Vec<HashMap<String, serde_json::Value>>>,
490    /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
491    pub message: Option<String>,
492}
493
494impl common::Part for Status {}
495
496/// A time-stamped annotation or message event in the Span.
497///
498/// This type is not used in any activity, and only used as *part* of another schema.
499///
500#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
501#[serde_with::serde_as]
502#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
503pub struct TimeEvent {
504    /// Text annotation with a set of attributes.
505    pub annotation: Option<Annotation>,
506    /// An event describing a message sent/received between Spans.
507    #[serde(rename = "messageEvent")]
508    pub message_event: Option<MessageEvent>,
509    /// The timestamp indicating the time the event occurred.
510    pub time: Option<chrono::DateTime<chrono::offset::Utc>>,
511}
512
513impl common::Part for TimeEvent {}
514
515/// A collection of `TimeEvent`s. A `TimeEvent` is a time-stamped annotation on the span, consisting of either user-supplied key:value pairs, or details of a message sent/received between Spans.
516///
517/// This type is not used in any activity, and only used as *part* of another schema.
518///
519#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
520#[serde_with::serde_as]
521#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
522pub struct TimeEvents {
523    /// The number of dropped annotations in all the included time events. If the value is 0, then no annotations were dropped.
524    #[serde(rename = "droppedAnnotationsCount")]
525    pub dropped_annotations_count: Option<i32>,
526    /// The number of dropped message events in all the included time events. If the value is 0, then no message events were dropped.
527    #[serde(rename = "droppedMessageEventsCount")]
528    pub dropped_message_events_count: Option<i32>,
529    /// A collection of `TimeEvent`s.
530    #[serde(rename = "timeEvent")]
531    pub time_event: Option<Vec<TimeEvent>>,
532}
533
534impl common::Part for TimeEvents {}
535
536/// Represents a string that might be shortened to a specified length.
537///
538/// This type is not used in any activity, and only used as *part* of another schema.
539///
540#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
541#[serde_with::serde_as]
542#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
543pub struct TruncatableString {
544    /// The number of bytes removed from the original string. If this value is 0, then the string was not shortened.
545    #[serde(rename = "truncatedByteCount")]
546    pub truncated_byte_count: Option<i32>,
547    /// The shortened string. For example, if the original string is 500 bytes long and the limit of the string is 128 bytes, then `value` contains the first 128 bytes of the 500-byte string. Truncation always happens on a UTF8 character boundary. If there are multi-byte characters in the string, then the length of the shortened string might be less than the size limit.
548    pub value: Option<String>,
549}
550
551impl common::Part for TruncatableString {}
552
553// ###################
554// MethodBuilders ###
555// #################
556
557/// A builder providing access to all methods supported on *project* resources.
558/// It is not used directly, but through the [`CloudTrace`] hub.
559///
560/// # Example
561///
562/// Instantiate a resource builder
563///
564/// ```test_harness,no_run
565/// extern crate hyper;
566/// extern crate hyper_rustls;
567/// extern crate google_cloudtrace2 as cloudtrace2;
568///
569/// # async fn dox() {
570/// use cloudtrace2::{CloudTrace, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
571///
572/// let secret: yup_oauth2::ApplicationSecret = Default::default();
573/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
574///     .with_native_roots()
575///     .unwrap()
576///     .https_only()
577///     .enable_http2()
578///     .build();
579///
580/// let executor = hyper_util::rt::TokioExecutor::new();
581/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
582///     secret,
583///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
584///     yup_oauth2::client::CustomHyperClientBuilder::from(
585///         hyper_util::client::legacy::Client::builder(executor).build(connector),
586///     ),
587/// ).build().await.unwrap();
588///
589/// let client = hyper_util::client::legacy::Client::builder(
590///     hyper_util::rt::TokioExecutor::new()
591/// )
592/// .build(
593///     hyper_rustls::HttpsConnectorBuilder::new()
594///         .with_native_roots()
595///         .unwrap()
596///         .https_or_http()
597///         .enable_http2()
598///         .build()
599/// );
600/// let mut hub = CloudTrace::new(client, auth);
601/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
602/// // like `traces_batch_write(...)` and `traces_spans_create_span(...)`
603/// // to build up your call.
604/// let rb = hub.projects();
605/// # }
606/// ```
607pub struct ProjectMethods<'a, C>
608where
609    C: 'a,
610{
611    hub: &'a CloudTrace<C>,
612}
613
614impl<'a, C> common::MethodsBuilder for ProjectMethods<'a, C> {}
615
616impl<'a, C> ProjectMethods<'a, C> {
617    /// Create a builder to help you perform the following task:
618    ///
619    /// Creates a new span. If a span ID already exists, an additional copy of the span will be stored.
620    ///
621    /// # Arguments
622    ///
623    /// * `request` - No description provided.
624    /// * `name` - Required. The resource name of the span in the following format: * `projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID]` `[TRACE_ID]` is a unique identifier for a trace within a project; it is a 32-character hexadecimal encoding of a 16-byte array. It should not be zero. `[SPAN_ID]` is a unique identifier for a span within a trace; it is a 16-character hexadecimal encoding of an 8-byte array. It should not be zero. .
625    pub fn traces_spans_create_span(
626        &self,
627        request: Span,
628        name: &str,
629    ) -> ProjectTraceSpanCreateSpanCall<'a, C> {
630        ProjectTraceSpanCreateSpanCall {
631            hub: self.hub,
632            _request: request,
633            _name: name.to_string(),
634            _delegate: Default::default(),
635            _additional_params: Default::default(),
636            _scopes: Default::default(),
637        }
638    }
639
640    /// Create a builder to help you perform the following task:
641    ///
642    /// Batch writes new spans to new or existing traces. You cannot update existing spans. If a span ID already exists, an additional copy of the span will be stored.
643    ///
644    /// # Arguments
645    ///
646    /// * `request` - No description provided.
647    /// * `name` - Required. The name of the project where the spans belong. The format is `projects/[PROJECT_ID]`.
648    pub fn traces_batch_write(
649        &self,
650        request: BatchWriteSpansRequest,
651        name: &str,
652    ) -> ProjectTraceBatchWriteCall<'a, C> {
653        ProjectTraceBatchWriteCall {
654            hub: self.hub,
655            _request: request,
656            _name: name.to_string(),
657            _delegate: Default::default(),
658            _additional_params: Default::default(),
659            _scopes: Default::default(),
660        }
661    }
662}
663
664// ###################
665// CallBuilders   ###
666// #################
667
668/// Creates a new span. If a span ID already exists, an additional copy of the span will be stored.
669///
670/// A builder for the *traces.spans.createSpan* method supported by a *project* resource.
671/// It is not used directly, but through a [`ProjectMethods`] instance.
672///
673/// # Example
674///
675/// Instantiate a resource method builder
676///
677/// ```test_harness,no_run
678/// # extern crate hyper;
679/// # extern crate hyper_rustls;
680/// # extern crate google_cloudtrace2 as cloudtrace2;
681/// use cloudtrace2::api::Span;
682/// # async fn dox() {
683/// # use cloudtrace2::{CloudTrace, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
684///
685/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
686/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
687/// #     .with_native_roots()
688/// #     .unwrap()
689/// #     .https_only()
690/// #     .enable_http2()
691/// #     .build();
692///
693/// # let executor = hyper_util::rt::TokioExecutor::new();
694/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
695/// #     secret,
696/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
697/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
698/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
699/// #     ),
700/// # ).build().await.unwrap();
701///
702/// # let client = hyper_util::client::legacy::Client::builder(
703/// #     hyper_util::rt::TokioExecutor::new()
704/// # )
705/// # .build(
706/// #     hyper_rustls::HttpsConnectorBuilder::new()
707/// #         .with_native_roots()
708/// #         .unwrap()
709/// #         .https_or_http()
710/// #         .enable_http2()
711/// #         .build()
712/// # );
713/// # let mut hub = CloudTrace::new(client, auth);
714/// // As the method needs a request, you would usually fill it with the desired information
715/// // into the respective structure. Some of the parts shown here might not be applicable !
716/// // Values shown here are possibly random and not representative !
717/// let mut req = Span::default();
718///
719/// // You can configure optional parameters by calling the respective setters at will, and
720/// // execute the final call using `doit()`.
721/// // Values shown here are possibly random and not representative !
722/// let result = hub.projects().traces_spans_create_span(req, "name")
723///              .doit().await;
724/// # }
725/// ```
726pub struct ProjectTraceSpanCreateSpanCall<'a, C>
727where
728    C: 'a,
729{
730    hub: &'a CloudTrace<C>,
731    _request: Span,
732    _name: String,
733    _delegate: Option<&'a mut dyn common::Delegate>,
734    _additional_params: HashMap<String, String>,
735    _scopes: BTreeSet<String>,
736}
737
738impl<'a, C> common::CallBuilder for ProjectTraceSpanCreateSpanCall<'a, C> {}
739
740impl<'a, C> ProjectTraceSpanCreateSpanCall<'a, C>
741where
742    C: common::Connector,
743{
744    /// Perform the operation you have build so far.
745    pub async fn doit(mut self) -> common::Result<(common::Response, Span)> {
746        use std::borrow::Cow;
747        use std::io::{Read, Seek};
748
749        use common::{url::Params, ToParts};
750        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
751
752        let mut dd = common::DefaultDelegate;
753        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
754        dlg.begin(common::MethodInfo {
755            id: "cloudtrace.projects.traces.spans.createSpan",
756            http_method: hyper::Method::POST,
757        });
758
759        for &field in ["alt", "name"].iter() {
760            if self._additional_params.contains_key(field) {
761                dlg.finished(false);
762                return Err(common::Error::FieldClash(field));
763            }
764        }
765
766        let mut params = Params::with_capacity(4 + self._additional_params.len());
767        params.push("name", self._name);
768
769        params.extend(self._additional_params.iter());
770
771        params.push("alt", "json");
772        let mut url = self.hub._base_url.clone() + "v2/{+name}";
773        if self._scopes.is_empty() {
774            self._scopes
775                .insert(Scope::CloudPlatform.as_ref().to_string());
776        }
777
778        #[allow(clippy::single_element_loop)]
779        for &(find_this, param_name) in [("{+name}", "name")].iter() {
780            url = params.uri_replacement(url, param_name, find_this, true);
781        }
782        {
783            let to_remove = ["name"];
784            params.remove_params(&to_remove);
785        }
786
787        let url = params.parse_with_url(&url);
788
789        let mut json_mime_type = mime::APPLICATION_JSON;
790        let mut request_value_reader = {
791            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
792            common::remove_json_null_values(&mut value);
793            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
794            serde_json::to_writer(&mut dst, &value).unwrap();
795            dst
796        };
797        let request_size = request_value_reader
798            .seek(std::io::SeekFrom::End(0))
799            .unwrap();
800        request_value_reader
801            .seek(std::io::SeekFrom::Start(0))
802            .unwrap();
803
804        loop {
805            let token = match self
806                .hub
807                .auth
808                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
809                .await
810            {
811                Ok(token) => token,
812                Err(e) => match dlg.token(e) {
813                    Ok(token) => token,
814                    Err(e) => {
815                        dlg.finished(false);
816                        return Err(common::Error::MissingToken(e));
817                    }
818                },
819            };
820            request_value_reader
821                .seek(std::io::SeekFrom::Start(0))
822                .unwrap();
823            let mut req_result = {
824                let client = &self.hub.client;
825                dlg.pre_request();
826                let mut req_builder = hyper::Request::builder()
827                    .method(hyper::Method::POST)
828                    .uri(url.as_str())
829                    .header(USER_AGENT, self.hub._user_agent.clone());
830
831                if let Some(token) = token.as_ref() {
832                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
833                }
834
835                let request = req_builder
836                    .header(CONTENT_TYPE, json_mime_type.to_string())
837                    .header(CONTENT_LENGTH, request_size as u64)
838                    .body(common::to_body(
839                        request_value_reader.get_ref().clone().into(),
840                    ));
841
842                client.request(request.unwrap()).await
843            };
844
845            match req_result {
846                Err(err) => {
847                    if let common::Retry::After(d) = dlg.http_error(&err) {
848                        sleep(d).await;
849                        continue;
850                    }
851                    dlg.finished(false);
852                    return Err(common::Error::HttpError(err));
853                }
854                Ok(res) => {
855                    let (mut parts, body) = res.into_parts();
856                    let mut body = common::Body::new(body);
857                    if !parts.status.is_success() {
858                        let bytes = common::to_bytes(body).await.unwrap_or_default();
859                        let error = serde_json::from_str(&common::to_string(&bytes));
860                        let response = common::to_response(parts, bytes.into());
861
862                        if let common::Retry::After(d) =
863                            dlg.http_failure(&response, error.as_ref().ok())
864                        {
865                            sleep(d).await;
866                            continue;
867                        }
868
869                        dlg.finished(false);
870
871                        return Err(match error {
872                            Ok(value) => common::Error::BadRequest(value),
873                            _ => common::Error::Failure(response),
874                        });
875                    }
876                    let response = {
877                        let bytes = common::to_bytes(body).await.unwrap_or_default();
878                        let encoded = common::to_string(&bytes);
879                        match serde_json::from_str(&encoded) {
880                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
881                            Err(error) => {
882                                dlg.response_json_decode_error(&encoded, &error);
883                                return Err(common::Error::JsonDecodeError(
884                                    encoded.to_string(),
885                                    error,
886                                ));
887                            }
888                        }
889                    };
890
891                    dlg.finished(true);
892                    return Ok(response);
893                }
894            }
895        }
896    }
897
898    ///
899    /// Sets the *request* property to the given value.
900    ///
901    /// Even though the property as already been set when instantiating this call,
902    /// we provide this method for API completeness.
903    pub fn request(mut self, new_value: Span) -> ProjectTraceSpanCreateSpanCall<'a, C> {
904        self._request = new_value;
905        self
906    }
907    /// Required. The resource name of the span in the following format: * `projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID]` `[TRACE_ID]` is a unique identifier for a trace within a project; it is a 32-character hexadecimal encoding of a 16-byte array. It should not be zero. `[SPAN_ID]` is a unique identifier for a span within a trace; it is a 16-character hexadecimal encoding of an 8-byte array. It should not be zero. .
908    ///
909    /// Sets the *name* path property to the given value.
910    ///
911    /// Even though the property as already been set when instantiating this call,
912    /// we provide this method for API completeness.
913    pub fn name(mut self, new_value: &str) -> ProjectTraceSpanCreateSpanCall<'a, C> {
914        self._name = new_value.to_string();
915        self
916    }
917    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
918    /// while executing the actual API request.
919    ///
920    /// ````text
921    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
922    /// ````
923    ///
924    /// Sets the *delegate* property to the given value.
925    pub fn delegate(
926        mut self,
927        new_value: &'a mut dyn common::Delegate,
928    ) -> ProjectTraceSpanCreateSpanCall<'a, C> {
929        self._delegate = Some(new_value);
930        self
931    }
932
933    /// Set any additional parameter of the query string used in the request.
934    /// It should be used to set parameters which are not yet available through their own
935    /// setters.
936    ///
937    /// Please note that this method must not be used to set any of the known parameters
938    /// which have their own setter method. If done anyway, the request will fail.
939    ///
940    /// # Additional Parameters
941    ///
942    /// * *$.xgafv* (query-string) - V1 error format.
943    /// * *access_token* (query-string) - OAuth access token.
944    /// * *alt* (query-string) - Data format for response.
945    /// * *callback* (query-string) - JSONP
946    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
947    /// * *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.
948    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
949    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
950    /// * *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.
951    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
952    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
953    pub fn param<T>(mut self, name: T, value: T) -> ProjectTraceSpanCreateSpanCall<'a, C>
954    where
955        T: AsRef<str>,
956    {
957        self._additional_params
958            .insert(name.as_ref().to_string(), value.as_ref().to_string());
959        self
960    }
961
962    /// Identifies the authorization scope for the method you are building.
963    ///
964    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
965    /// [`Scope::CloudPlatform`].
966    ///
967    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
968    /// tokens for more than one scope.
969    ///
970    /// Usually there is more than one suitable scope to authorize an operation, some of which may
971    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
972    /// sufficient, a read-write scope will do as well.
973    pub fn add_scope<St>(mut self, scope: St) -> ProjectTraceSpanCreateSpanCall<'a, C>
974    where
975        St: AsRef<str>,
976    {
977        self._scopes.insert(String::from(scope.as_ref()));
978        self
979    }
980    /// Identifies the authorization scope(s) for the method you are building.
981    ///
982    /// See [`Self::add_scope()`] for details.
983    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectTraceSpanCreateSpanCall<'a, C>
984    where
985        I: IntoIterator<Item = St>,
986        St: AsRef<str>,
987    {
988        self._scopes
989            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
990        self
991    }
992
993    /// Removes all scopes, and no default scope will be used either.
994    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
995    /// for details).
996    pub fn clear_scopes(mut self) -> ProjectTraceSpanCreateSpanCall<'a, C> {
997        self._scopes.clear();
998        self
999    }
1000}
1001
1002/// Batch writes new spans to new or existing traces. You cannot update existing spans. If a span ID already exists, an additional copy of the span will be stored.
1003///
1004/// A builder for the *traces.batchWrite* method supported by a *project* resource.
1005/// It is not used directly, but through a [`ProjectMethods`] instance.
1006///
1007/// # Example
1008///
1009/// Instantiate a resource method builder
1010///
1011/// ```test_harness,no_run
1012/// # extern crate hyper;
1013/// # extern crate hyper_rustls;
1014/// # extern crate google_cloudtrace2 as cloudtrace2;
1015/// use cloudtrace2::api::BatchWriteSpansRequest;
1016/// # async fn dox() {
1017/// # use cloudtrace2::{CloudTrace, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1018///
1019/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1020/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1021/// #     .with_native_roots()
1022/// #     .unwrap()
1023/// #     .https_only()
1024/// #     .enable_http2()
1025/// #     .build();
1026///
1027/// # let executor = hyper_util::rt::TokioExecutor::new();
1028/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1029/// #     secret,
1030/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1031/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1032/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1033/// #     ),
1034/// # ).build().await.unwrap();
1035///
1036/// # let client = hyper_util::client::legacy::Client::builder(
1037/// #     hyper_util::rt::TokioExecutor::new()
1038/// # )
1039/// # .build(
1040/// #     hyper_rustls::HttpsConnectorBuilder::new()
1041/// #         .with_native_roots()
1042/// #         .unwrap()
1043/// #         .https_or_http()
1044/// #         .enable_http2()
1045/// #         .build()
1046/// # );
1047/// # let mut hub = CloudTrace::new(client, auth);
1048/// // As the method needs a request, you would usually fill it with the desired information
1049/// // into the respective structure. Some of the parts shown here might not be applicable !
1050/// // Values shown here are possibly random and not representative !
1051/// let mut req = BatchWriteSpansRequest::default();
1052///
1053/// // You can configure optional parameters by calling the respective setters at will, and
1054/// // execute the final call using `doit()`.
1055/// // Values shown here are possibly random and not representative !
1056/// let result = hub.projects().traces_batch_write(req, "name")
1057///              .doit().await;
1058/// # }
1059/// ```
1060pub struct ProjectTraceBatchWriteCall<'a, C>
1061where
1062    C: 'a,
1063{
1064    hub: &'a CloudTrace<C>,
1065    _request: BatchWriteSpansRequest,
1066    _name: String,
1067    _delegate: Option<&'a mut dyn common::Delegate>,
1068    _additional_params: HashMap<String, String>,
1069    _scopes: BTreeSet<String>,
1070}
1071
1072impl<'a, C> common::CallBuilder for ProjectTraceBatchWriteCall<'a, C> {}
1073
1074impl<'a, C> ProjectTraceBatchWriteCall<'a, C>
1075where
1076    C: common::Connector,
1077{
1078    /// Perform the operation you have build so far.
1079    pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
1080        use std::borrow::Cow;
1081        use std::io::{Read, Seek};
1082
1083        use common::{url::Params, ToParts};
1084        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1085
1086        let mut dd = common::DefaultDelegate;
1087        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1088        dlg.begin(common::MethodInfo {
1089            id: "cloudtrace.projects.traces.batchWrite",
1090            http_method: hyper::Method::POST,
1091        });
1092
1093        for &field in ["alt", "name"].iter() {
1094            if self._additional_params.contains_key(field) {
1095                dlg.finished(false);
1096                return Err(common::Error::FieldClash(field));
1097            }
1098        }
1099
1100        let mut params = Params::with_capacity(4 + self._additional_params.len());
1101        params.push("name", self._name);
1102
1103        params.extend(self._additional_params.iter());
1104
1105        params.push("alt", "json");
1106        let mut url = self.hub._base_url.clone() + "v2/{+name}/traces:batchWrite";
1107        if self._scopes.is_empty() {
1108            self._scopes
1109                .insert(Scope::CloudPlatform.as_ref().to_string());
1110        }
1111
1112        #[allow(clippy::single_element_loop)]
1113        for &(find_this, param_name) in [("{+name}", "name")].iter() {
1114            url = params.uri_replacement(url, param_name, find_this, true);
1115        }
1116        {
1117            let to_remove = ["name"];
1118            params.remove_params(&to_remove);
1119        }
1120
1121        let url = params.parse_with_url(&url);
1122
1123        let mut json_mime_type = mime::APPLICATION_JSON;
1124        let mut request_value_reader = {
1125            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1126            common::remove_json_null_values(&mut value);
1127            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1128            serde_json::to_writer(&mut dst, &value).unwrap();
1129            dst
1130        };
1131        let request_size = request_value_reader
1132            .seek(std::io::SeekFrom::End(0))
1133            .unwrap();
1134        request_value_reader
1135            .seek(std::io::SeekFrom::Start(0))
1136            .unwrap();
1137
1138        loop {
1139            let token = match self
1140                .hub
1141                .auth
1142                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1143                .await
1144            {
1145                Ok(token) => token,
1146                Err(e) => match dlg.token(e) {
1147                    Ok(token) => token,
1148                    Err(e) => {
1149                        dlg.finished(false);
1150                        return Err(common::Error::MissingToken(e));
1151                    }
1152                },
1153            };
1154            request_value_reader
1155                .seek(std::io::SeekFrom::Start(0))
1156                .unwrap();
1157            let mut req_result = {
1158                let client = &self.hub.client;
1159                dlg.pre_request();
1160                let mut req_builder = hyper::Request::builder()
1161                    .method(hyper::Method::POST)
1162                    .uri(url.as_str())
1163                    .header(USER_AGENT, self.hub._user_agent.clone());
1164
1165                if let Some(token) = token.as_ref() {
1166                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1167                }
1168
1169                let request = req_builder
1170                    .header(CONTENT_TYPE, json_mime_type.to_string())
1171                    .header(CONTENT_LENGTH, request_size as u64)
1172                    .body(common::to_body(
1173                        request_value_reader.get_ref().clone().into(),
1174                    ));
1175
1176                client.request(request.unwrap()).await
1177            };
1178
1179            match req_result {
1180                Err(err) => {
1181                    if let common::Retry::After(d) = dlg.http_error(&err) {
1182                        sleep(d).await;
1183                        continue;
1184                    }
1185                    dlg.finished(false);
1186                    return Err(common::Error::HttpError(err));
1187                }
1188                Ok(res) => {
1189                    let (mut parts, body) = res.into_parts();
1190                    let mut body = common::Body::new(body);
1191                    if !parts.status.is_success() {
1192                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1193                        let error = serde_json::from_str(&common::to_string(&bytes));
1194                        let response = common::to_response(parts, bytes.into());
1195
1196                        if let common::Retry::After(d) =
1197                            dlg.http_failure(&response, error.as_ref().ok())
1198                        {
1199                            sleep(d).await;
1200                            continue;
1201                        }
1202
1203                        dlg.finished(false);
1204
1205                        return Err(match error {
1206                            Ok(value) => common::Error::BadRequest(value),
1207                            _ => common::Error::Failure(response),
1208                        });
1209                    }
1210                    let response = {
1211                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1212                        let encoded = common::to_string(&bytes);
1213                        match serde_json::from_str(&encoded) {
1214                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1215                            Err(error) => {
1216                                dlg.response_json_decode_error(&encoded, &error);
1217                                return Err(common::Error::JsonDecodeError(
1218                                    encoded.to_string(),
1219                                    error,
1220                                ));
1221                            }
1222                        }
1223                    };
1224
1225                    dlg.finished(true);
1226                    return Ok(response);
1227                }
1228            }
1229        }
1230    }
1231
1232    ///
1233    /// Sets the *request* property to the given value.
1234    ///
1235    /// Even though the property as already been set when instantiating this call,
1236    /// we provide this method for API completeness.
1237    pub fn request(
1238        mut self,
1239        new_value: BatchWriteSpansRequest,
1240    ) -> ProjectTraceBatchWriteCall<'a, C> {
1241        self._request = new_value;
1242        self
1243    }
1244    /// Required. The name of the project where the spans belong. The format is `projects/[PROJECT_ID]`.
1245    ///
1246    /// Sets the *name* path property to the given value.
1247    ///
1248    /// Even though the property as already been set when instantiating this call,
1249    /// we provide this method for API completeness.
1250    pub fn name(mut self, new_value: &str) -> ProjectTraceBatchWriteCall<'a, C> {
1251        self._name = new_value.to_string();
1252        self
1253    }
1254    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1255    /// while executing the actual API request.
1256    ///
1257    /// ````text
1258    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1259    /// ````
1260    ///
1261    /// Sets the *delegate* property to the given value.
1262    pub fn delegate(
1263        mut self,
1264        new_value: &'a mut dyn common::Delegate,
1265    ) -> ProjectTraceBatchWriteCall<'a, C> {
1266        self._delegate = Some(new_value);
1267        self
1268    }
1269
1270    /// Set any additional parameter of the query string used in the request.
1271    /// It should be used to set parameters which are not yet available through their own
1272    /// setters.
1273    ///
1274    /// Please note that this method must not be used to set any of the known parameters
1275    /// which have their own setter method. If done anyway, the request will fail.
1276    ///
1277    /// # Additional Parameters
1278    ///
1279    /// * *$.xgafv* (query-string) - V1 error format.
1280    /// * *access_token* (query-string) - OAuth access token.
1281    /// * *alt* (query-string) - Data format for response.
1282    /// * *callback* (query-string) - JSONP
1283    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1284    /// * *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.
1285    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1286    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1287    /// * *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.
1288    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1289    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1290    pub fn param<T>(mut self, name: T, value: T) -> ProjectTraceBatchWriteCall<'a, C>
1291    where
1292        T: AsRef<str>,
1293    {
1294        self._additional_params
1295            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1296        self
1297    }
1298
1299    /// Identifies the authorization scope for the method you are building.
1300    ///
1301    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1302    /// [`Scope::CloudPlatform`].
1303    ///
1304    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1305    /// tokens for more than one scope.
1306    ///
1307    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1308    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1309    /// sufficient, a read-write scope will do as well.
1310    pub fn add_scope<St>(mut self, scope: St) -> ProjectTraceBatchWriteCall<'a, C>
1311    where
1312        St: AsRef<str>,
1313    {
1314        self._scopes.insert(String::from(scope.as_ref()));
1315        self
1316    }
1317    /// Identifies the authorization scope(s) for the method you are building.
1318    ///
1319    /// See [`Self::add_scope()`] for details.
1320    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectTraceBatchWriteCall<'a, C>
1321    where
1322        I: IntoIterator<Item = St>,
1323        St: AsRef<str>,
1324    {
1325        self._scopes
1326            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1327        self
1328    }
1329
1330    /// Removes all scopes, and no default scope will be used either.
1331    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1332    /// for details).
1333    pub fn clear_scopes(mut self) -> ProjectTraceBatchWriteCall<'a, C> {
1334        self._scopes.clear();
1335        self
1336    }
1337}