use std::collections::HashMap;
use std::cell::RefCell;
use std::default::Default;
use std::collections::BTreeMap;
use serde_json as json;
use std::io;
use std::fs;
use std::mem;
use std::thread::sleep;
use crate::client;
#[derive(PartialEq, Eq, Hash)]
pub enum Scope {
CloudPlatform,
TraceAppend,
}
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
match *self {
Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
Scope::TraceAppend => "https://www.googleapis.com/auth/trace.append",
}
}
}
impl Default for Scope {
fn default() -> Scope {
Scope::TraceAppend
}
}
pub struct CloudTrace<> {
client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>,
auth: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<'a, > client::Hub for CloudTrace<> {}
impl<'a, > CloudTrace<> {
pub fn new(client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>, authenticator: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>) -> CloudTrace<> {
CloudTrace {
client,
auth: authenticator,
_user_agent: "google-api-rust-client/2.0.3".to_string(),
_base_url: "https://cloudtrace.googleapis.com/".to_string(),
_root_url: "https://cloudtrace.googleapis.com/".to_string(),
}
}
pub fn projects(&'a self) -> ProjectMethods<'a> {
ProjectMethods { hub: &self }
}
pub fn user_agent(&mut self, agent_name: String) -> String {
mem::replace(&mut self._user_agent, agent_name)
}
pub fn base_url(&mut self, new_base_url: String) -> String {
mem::replace(&mut self._base_url, new_base_url)
}
pub fn root_url(&mut self, new_root_url: String) -> String {
mem::replace(&mut self._root_url, new_root_url)
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Annotation {
pub attributes: Option<Attributes>,
pub description: Option<TruncatableString>,
}
impl client::Part for Annotation {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AttributeValue {
#[serde(rename="boolValue")]
pub bool_value: Option<bool>,
#[serde(rename="intValue")]
pub int_value: Option<String>,
#[serde(rename="stringValue")]
pub string_value: Option<TruncatableString>,
}
impl client::Part for AttributeValue {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Attributes {
#[serde(rename="attributeMap")]
pub attribute_map: Option<HashMap<String, AttributeValue>>,
#[serde(rename="droppedAttributesCount")]
pub dropped_attributes_count: Option<i32>,
}
impl client::Part for Attributes {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct BatchWriteSpansRequest {
pub spans: Option<Vec<Span>>,
}
impl client::RequestValue for BatchWriteSpansRequest {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Empty { _never_set: Option<bool> }
impl client::ResponseResult for Empty {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Link {
pub attributes: Option<Attributes>,
#[serde(rename="spanId")]
pub span_id: Option<String>,
#[serde(rename="traceId")]
pub trace_id: Option<String>,
#[serde(rename="type")]
pub type_: Option<String>,
}
impl client::Part for Link {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Links {
#[serde(rename="droppedLinksCount")]
pub dropped_links_count: Option<i32>,
pub link: Option<Vec<Link>>,
}
impl client::Part for Links {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct MessageEvent {
#[serde(rename="compressedSizeBytes")]
pub compressed_size_bytes: Option<String>,
pub id: Option<String>,
#[serde(rename="type")]
pub type_: Option<String>,
#[serde(rename="uncompressedSizeBytes")]
pub uncompressed_size_bytes: Option<String>,
}
impl client::Part for MessageEvent {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Module {
#[serde(rename="buildId")]
pub build_id: Option<TruncatableString>,
pub module: Option<TruncatableString>,
}
impl client::Part for Module {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Span {
pub attributes: Option<Attributes>,
#[serde(rename="childSpanCount")]
pub child_span_count: Option<i32>,
#[serde(rename="displayName")]
pub display_name: Option<TruncatableString>,
#[serde(rename="endTime")]
pub end_time: Option<String>,
pub links: Option<Links>,
pub name: Option<String>,
#[serde(rename="parentSpanId")]
pub parent_span_id: Option<String>,
#[serde(rename="sameProcessAsParentSpan")]
pub same_process_as_parent_span: Option<bool>,
#[serde(rename="spanId")]
pub span_id: Option<String>,
#[serde(rename="spanKind")]
pub span_kind: Option<String>,
#[serde(rename="stackTrace")]
pub stack_trace: Option<StackTrace>,
#[serde(rename="startTime")]
pub start_time: Option<String>,
pub status: Option<Status>,
#[serde(rename="timeEvents")]
pub time_events: Option<TimeEvents>,
}
impl client::RequestValue for Span {}
impl client::ResponseResult for Span {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct StackFrame {
#[serde(rename="columnNumber")]
pub column_number: Option<String>,
#[serde(rename="fileName")]
pub file_name: Option<TruncatableString>,
#[serde(rename="functionName")]
pub function_name: Option<TruncatableString>,
#[serde(rename="lineNumber")]
pub line_number: Option<String>,
#[serde(rename="loadModule")]
pub load_module: Option<Module>,
#[serde(rename="originalFunctionName")]
pub original_function_name: Option<TruncatableString>,
#[serde(rename="sourceVersion")]
pub source_version: Option<TruncatableString>,
}
impl client::Part for StackFrame {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct StackFrames {
#[serde(rename="droppedFramesCount")]
pub dropped_frames_count: Option<i32>,
pub frame: Option<Vec<StackFrame>>,
}
impl client::Part for StackFrames {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct StackTrace {
#[serde(rename="stackFrames")]
pub stack_frames: Option<StackFrames>,
#[serde(rename="stackTraceHashId")]
pub stack_trace_hash_id: Option<String>,
}
impl client::Part for StackTrace {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Status {
pub code: Option<i32>,
pub details: Option<Vec<HashMap<String, String>>>,
pub message: Option<String>,
}
impl client::Part for Status {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TimeEvent {
pub annotation: Option<Annotation>,
#[serde(rename="messageEvent")]
pub message_event: Option<MessageEvent>,
pub time: Option<String>,
}
impl client::Part for TimeEvent {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TimeEvents {
#[serde(rename="droppedAnnotationsCount")]
pub dropped_annotations_count: Option<i32>,
#[serde(rename="droppedMessageEventsCount")]
pub dropped_message_events_count: Option<i32>,
#[serde(rename="timeEvent")]
pub time_event: Option<Vec<TimeEvent>>,
}
impl client::Part for TimeEvents {}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TruncatableString {
#[serde(rename="truncatedByteCount")]
pub truncated_byte_count: Option<i32>,
pub value: Option<String>,
}
impl client::Part for TruncatableString {}
pub struct ProjectMethods<'a>
where {
hub: &'a CloudTrace<>,
}
impl<'a> client::MethodsBuilder for ProjectMethods<'a> {}
impl<'a> ProjectMethods<'a> {
pub fn traces_spans_create_span(&self, request: Span, name: &str) -> ProjectTraceSpanCreateSpanCall<'a> {
ProjectTraceSpanCreateSpanCall {
hub: self.hub,
_request: request,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
pub fn traces_batch_write(&self, request: BatchWriteSpansRequest, name: &str) -> ProjectTraceBatchWriteCall<'a> {
ProjectTraceBatchWriteCall {
hub: self.hub,
_request: request,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
pub struct ProjectTraceSpanCreateSpanCall<'a>
where {
hub: &'a CloudTrace<>,
_request: Span,
_name: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for ProjectTraceSpanCreateSpanCall<'a> {}
impl<'a> ProjectTraceSpanCreateSpanCall<'a> {
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Span)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "cloudtrace.projects.traces.spans.createSpan",
http_method: hyper::Method::POST });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("name", self._name.to_string()));
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v2/{+name}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{+name}", "name")].iter() {
let mut replace_with = String::new();
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = value.to_string();
break;
}
}
if find_this.as_bytes()[1] == '+' as u8 {
replace_with = percent_encode(replace_with.as_bytes(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["name"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
client::remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
.header(CONTENT_LENGTH, request_size as u64)
.body(hyper::body::Body::from(request_value_reader.get_ref().clone()));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
pub fn request(mut self, new_value: Span) -> ProjectTraceSpanCreateSpanCall<'a> {
self._request = new_value;
self
}
pub fn name(mut self, new_value: &str) -> ProjectTraceSpanCreateSpanCall<'a> {
self._name = new_value.to_string();
self
}
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> ProjectTraceSpanCreateSpanCall<'a> {
self._delegate = Some(new_value);
self
}
pub fn param<T>(mut self, name: T, value: T) -> ProjectTraceSpanCreateSpanCall<'a>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectTraceSpanCreateSpanCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
pub struct ProjectTraceBatchWriteCall<'a>
where {
hub: &'a CloudTrace<>,
_request: BatchWriteSpansRequest,
_name: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for ProjectTraceBatchWriteCall<'a> {}
impl<'a> ProjectTraceBatchWriteCall<'a> {
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Empty)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "cloudtrace.projects.traces.batchWrite",
http_method: hyper::Method::POST });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("name", self._name.to_string()));
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v2/{+name}/traces:batchWrite";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{+name}", "name")].iter() {
let mut replace_with = String::new();
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = value.to_string();
break;
}
}
if find_this.as_bytes()[1] == '+' as u8 {
replace_with = percent_encode(replace_with.as_bytes(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["name"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
client::remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
.header(CONTENT_LENGTH, request_size as u64)
.body(hyper::body::Body::from(request_value_reader.get_ref().clone()));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
pub fn request(mut self, new_value: BatchWriteSpansRequest) -> ProjectTraceBatchWriteCall<'a> {
self._request = new_value;
self
}
pub fn name(mut self, new_value: &str) -> ProjectTraceBatchWriteCall<'a> {
self._name = new_value.to_string();
self
}
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> ProjectTraceBatchWriteCall<'a> {
self._delegate = Some(new_value);
self
}
pub fn param<T>(mut self, name: T, value: T) -> ProjectTraceBatchWriteCall<'a>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectTraceBatchWriteCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}