google_chromeuxreport1/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// ########
12// HUB ###
13// ######
14
15/// Central instance to access all ChromeUXReport related resource activities
16///
17/// # Examples
18///
19/// Instantiate a new hub
20///
21/// ```test_harness,no_run
22/// extern crate hyper;
23/// extern crate hyper_rustls;
24/// extern crate google_chromeuxreport1 as chromeuxreport1;
25/// use chromeuxreport1::api::QueryHistoryRequest;
26/// use chromeuxreport1::{Result, Error};
27/// # async fn dox() {
28/// use chromeuxreport1::{ChromeUXReport, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
29///
30/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
31/// // `client_secret`, among other things.
32/// let secret: yup_oauth2::ApplicationSecret = Default::default();
33/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
34/// // unless you replace `None` with the desired Flow.
35/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
36/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
37/// // retrieve them from storage.
38/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
39/// secret,
40/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
41/// ).build().await.unwrap();
42///
43/// let client = hyper_util::client::legacy::Client::builder(
44/// hyper_util::rt::TokioExecutor::new()
45/// )
46/// .build(
47/// hyper_rustls::HttpsConnectorBuilder::new()
48/// .with_native_roots()
49/// .unwrap()
50/// .https_or_http()
51/// .enable_http1()
52/// .build()
53/// );
54/// let mut hub = ChromeUXReport::new(client, auth);
55/// // As the method needs a request, you would usually fill it with the desired information
56/// // into the respective structure. Some of the parts shown here might not be applicable !
57/// // Values shown here are possibly random and not representative !
58/// let mut req = QueryHistoryRequest::default();
59///
60/// // You can configure optional parameters by calling the respective setters at will, and
61/// // execute the final call using `doit()`.
62/// // Values shown here are possibly random and not representative !
63/// let result = hub.records().query_history_record(req)
64/// .doit().await;
65///
66/// match result {
67/// Err(e) => match e {
68/// // The Error enum provides details about what exactly happened.
69/// // You can also just use its `Debug`, `Display` or `Error` traits
70/// Error::HttpError(_)
71/// |Error::Io(_)
72/// |Error::MissingAPIKey
73/// |Error::MissingToken(_)
74/// |Error::Cancelled
75/// |Error::UploadSizeLimitExceeded(_, _)
76/// |Error::Failure(_)
77/// |Error::BadRequest(_)
78/// |Error::FieldClash(_)
79/// |Error::JsonDecodeError(_, _) => println!("{}", e),
80/// },
81/// Ok(res) => println!("Success: {:?}", res),
82/// }
83/// # }
84/// ```
85#[derive(Clone)]
86pub struct ChromeUXReport<C> {
87 pub client: common::Client<C>,
88 pub auth: Box<dyn common::GetToken>,
89 _user_agent: String,
90 _base_url: String,
91 _root_url: String,
92}
93
94impl<C> common::Hub for ChromeUXReport<C> {}
95
96impl<'a, C> ChromeUXReport<C> {
97 pub fn new<A: 'static + common::GetToken>(
98 client: common::Client<C>,
99 auth: A,
100 ) -> ChromeUXReport<C> {
101 ChromeUXReport {
102 client,
103 auth: Box::new(auth),
104 _user_agent: "google-api-rust-client/6.0.0".to_string(),
105 _base_url: "https://chromeuxreport.googleapis.com/".to_string(),
106 _root_url: "https://chromeuxreport.googleapis.com/".to_string(),
107 }
108 }
109
110 pub fn records(&'a self) -> RecordMethods<'a, C> {
111 RecordMethods { hub: self }
112 }
113
114 /// Set the user-agent header field to use in all requests to the server.
115 /// It defaults to `google-api-rust-client/6.0.0`.
116 ///
117 /// Returns the previously set user-agent.
118 pub fn user_agent(&mut self, agent_name: String) -> String {
119 std::mem::replace(&mut self._user_agent, agent_name)
120 }
121
122 /// Set the base url to use in all requests to the server.
123 /// It defaults to `https://chromeuxreport.googleapis.com/`.
124 ///
125 /// Returns the previously set base url.
126 pub fn base_url(&mut self, new_base_url: String) -> String {
127 std::mem::replace(&mut self._base_url, new_base_url)
128 }
129
130 /// Set the root url to use in all requests to the server.
131 /// It defaults to `https://chromeuxreport.googleapis.com/`.
132 ///
133 /// Returns the previously set root url.
134 pub fn root_url(&mut self, new_root_url: String) -> String {
135 std::mem::replace(&mut self._root_url, new_root_url)
136 }
137}
138
139// ############
140// SCHEMAS ###
141// ##########
142/// A bin is a discrete portion of data spanning from start to end, or if no end is given, then from start to +inf. A bin's start and end values are given in the value type of the metric it represents. For example, "first contentful paint" is measured in milliseconds and exposed as ints, therefore its metric bins will use int32s for its start and end types. However, "cumulative layout shift" is measured in unitless decimals and is exposed as a decimal encoded as a string, therefore its metric bins will use strings for its value type.
143///
144/// This type is not used in any activity, and only used as *part* of another schema.
145///
146#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
147#[serde_with::serde_as]
148#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
149pub struct Bin {
150 /// The proportion of users that experienced this bin's value for the given metric.
151 pub density: Option<f64>,
152 /// End is the end of the data bin. If end is not populated, then the bin has no end and is valid from start to +inf.
153 pub end: Option<serde_json::Value>,
154 /// Start is the beginning of the data bin.
155 pub start: Option<serde_json::Value>,
156}
157
158impl common::Part for Bin {}
159
160/// The collection period is a date range which includes the `first` and `last` day.
161///
162/// This type is not used in any activity, and only used as *part* of another schema.
163///
164#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
165#[serde_with::serde_as]
166#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
167pub struct CollectionPeriod {
168 /// The first day in the collection period, inclusive.
169 #[serde(rename = "firstDate")]
170 pub first_date: Option<Date>,
171 /// The last day in the collection period, inclusive.
172 #[serde(rename = "lastDate")]
173 pub last_date: Option<Date>,
174}
175
176impl common::Part for CollectionPeriod {}
177
178/// Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp
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 Date {
186 /// Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.
187 pub day: Option<i32>,
188 /// Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.
189 pub month: Option<i32>,
190 /// Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.
191 pub year: Option<i32>,
192}
193
194impl common::Part for Date {}
195
196/// For enum metrics, provides fraction timeseries which add up to approximately 1.0 per entry (k-th element into the repeated fractions field for any k <= len) across fraction_timeseries.
197///
198/// This type is not used in any activity, and only used as *part* of another schema.
199///
200#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
201#[serde_with::serde_as]
202#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
203pub struct FractionTimeseries {
204 /// Values between 0.0 and 1.0 (inclusive) and NaN.
205 pub fractions: Option<Vec<f64>>,
206}
207
208impl common::Part for FractionTimeseries {}
209
210/// Key defines all the dimensions that identify this record as unique.
211///
212/// This type is not used in any activity, and only used as *part* of another schema.
213///
214#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
215#[serde_with::serde_as]
216#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
217pub struct HistoryKey {
218 /// The form factor is the device class that all users used to access the site for this record. If the form factor is unspecified, then aggregated data over all form factors will be returned.
219 #[serde(rename = "formFactor")]
220 pub form_factor: Option<String>,
221 /// Origin specifies the origin that this record is for. Note: When specifying an origin, data for loads under this origin over all pages are aggregated into origin level user experience data.
222 pub origin: Option<String>,
223 /// Url specifies a specific url that this record is for. This url should be normalized, following the normalization actions taken in the request to increase the chances of successful lookup. Note: When specifying a "url" only data for that specific url will be aggregated.
224 pub url: Option<String>,
225}
226
227impl common::Part for HistoryKey {}
228
229/// HistoryRecord is a timeseries of Chrome UX Report data. It contains user experience statistics for a single url pattern and a set of dimensions.
230///
231/// This type is not used in any activity, and only used as *part* of another schema.
232///
233#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
234#[serde_with::serde_as]
235#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
236pub struct HistoryRecord {
237 /// The collection periods indicate when each of the data points reflected in the time series data in metrics was collected. Note that all the time series share the same collection periods, and it is enforced in the CrUX pipeline that every time series has the same number of data points.
238 #[serde(rename = "collectionPeriods")]
239 pub collection_periods: Option<Vec<CollectionPeriod>>,
240 /// Key defines all of the unique querying parameters needed to look up a user experience history record.
241 pub key: Option<HistoryKey>,
242 /// Metrics is the map of user experience time series data available for the record defined in the key field. Metrics are keyed on the metric name. Allowed key values: ["first_contentful_paint", "first_input_delay", "largest_contentful_paint", "cumulative_layout_shift", "experimental_time_to_first_byte", "experimental_interaction_to_next_paint"]
243 pub metrics: Option<HashMap<String, MetricTimeseries>>,
244}
245
246impl common::Part for HistoryRecord {}
247
248/// Key defines all the dimensions that identify this record as unique.
249///
250/// This type is not used in any activity, and only used as *part* of another schema.
251///
252#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
253#[serde_with::serde_as]
254#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
255pub struct Key {
256 /// The effective connection type is the general connection class that all users experienced for this record. This field uses the values ["offline", "slow-2G", "2G", "3G", "4G"] as specified in: https://wicg.github.io/netinfo/#effective-connection-types If the effective connection type is unspecified, then aggregated data over all effective connection types will be returned.
257 #[serde(rename = "effectiveConnectionType")]
258 pub effective_connection_type: Option<String>,
259 /// The form factor is the device class that all users used to access the site for this record. If the form factor is unspecified, then aggregated data over all form factors will be returned.
260 #[serde(rename = "formFactor")]
261 pub form_factor: Option<String>,
262 /// Origin specifies the origin that this record is for. Note: When specifying an origin, data for loads under this origin over all pages are aggregated into origin level user experience data.
263 pub origin: Option<String>,
264 /// Url specifies a specific url that this record is for. Note: When specifying a "url" only data for that specific url will be aggregated.
265 pub url: Option<String>,
266}
267
268impl common::Part for Key {}
269
270/// A `metric` is a set of user experience data for a single web performance metric, like "first contentful paint". It contains a summary histogram of real world Chrome usage as a series of `bins`.
271///
272/// This type is not used in any activity, and only used as *part* of another schema.
273///
274#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
275#[serde_with::serde_as]
276#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
277pub struct Metric {
278 /// For enum metrics, provides fractions which add up to approximately 1.0.
279 pub fractions: Option<HashMap<String, f64>>,
280 /// The histogram of user experiences for a metric. The histogram will have at least one bin and the densities of all bins will add up to ~1.
281 pub histogram: Option<Vec<Bin>>,
282 /// Commonly useful percentiles of the Metric. The value type for the percentiles will be the same as the value types given for the Histogram bins.
283 pub percentiles: Option<Percentiles>,
284}
285
286impl common::Part for Metric {}
287
288/// A `metric timeseries` is a set of user experience data for a single web performance metric, like "first contentful paint". It contains a summary histogram of real world Chrome usage as a series of `bins`, where each bin has density values for a particular time period.
289///
290/// This type is not used in any activity, and only used as *part* of another schema.
291///
292#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
293#[serde_with::serde_as]
294#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
295pub struct MetricTimeseries {
296 /// Mapping from labels to timeseries of fractions attributed to this label.
297 #[serde(rename = "fractionTimeseries")]
298 pub fraction_timeseries: Option<HashMap<String, FractionTimeseries>>,
299 /// The histogram of user experiences for a metric. The histogram will have at least one bin and the densities of all bins will add up to ~1, for each timeseries entry.
300 #[serde(rename = "histogramTimeseries")]
301 pub histogram_timeseries: Option<Vec<TimeseriesBin>>,
302 /// Commonly useful percentiles of the Metric. The value type for the percentiles will be the same as the value types given for the Histogram bins.
303 #[serde(rename = "percentilesTimeseries")]
304 pub percentiles_timeseries: Option<TimeseriesPercentiles>,
305}
306
307impl common::Part for MetricTimeseries {}
308
309/// Percentiles contains synthetic values of a metric at a given statistical percentile. These are used for estimating a metric's value as experienced by a percentage of users out of the total number of users.
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 Percentiles {
317 /// 75% of users experienced the given metric at or below this value.
318 pub p75: Option<serde_json::Value>,
319}
320
321impl common::Part for Percentiles {}
322
323/// Request payload sent by a physical web client. This request includes all necessary context to load a particular user experience history record.
324///
325/// # Activities
326///
327/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
328/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
329///
330/// * [query history record records](RecordQueryHistoryRecordCall) (request)
331#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
332#[serde_with::serde_as]
333#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
334pub struct QueryHistoryRequest {
335 /// The form factor is a query dimension that specifies the device class that the record's data should belong to. Note: If no form factor is specified, then a special record with aggregated data over all form factors will be returned.
336 #[serde(rename = "formFactor")]
337 pub form_factor: Option<String>,
338 /// The metrics that should be included in the response. If none are specified then any metrics found will be returned. Allowed values: ["first_contentful_paint", "first_input_delay", "largest_contentful_paint", "cumulative_layout_shift", "experimental_time_to_first_byte", "experimental_interaction_to_next_paint"]
339 pub metrics: Option<Vec<String>>,
340 /// The url pattern "origin" refers to a url pattern that is the origin of a website. Examples: "https://example.com", "https://cloud.google.com"
341 pub origin: Option<String>,
342 /// The url pattern "url" refers to a url pattern that is any arbitrary url. Examples: "https://example.com/", "https://cloud.google.com/why-google-cloud/"
343 pub url: Option<String>,
344}
345
346impl common::RequestValue for QueryHistoryRequest {}
347
348/// Response payload sent back to a physical web client. This response contains the record found based on the identiers present in a `QueryHistoryRequest`. The returned response will have a history record, and sometimes details on normalization actions taken on the request that were necessary to make the request successful.
349///
350/// # Activities
351///
352/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
353/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
354///
355/// * [query history record records](RecordQueryHistoryRecordCall) (response)
356#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
357#[serde_with::serde_as]
358#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
359pub struct QueryHistoryResponse {
360 /// The record that was found.
361 pub record: Option<HistoryRecord>,
362 /// These are details about automated normalization actions that were taken in order to make the requested `url_pattern` valid.
363 #[serde(rename = "urlNormalizationDetails")]
364 pub url_normalization_details: Option<UrlNormalization>,
365}
366
367impl common::ResponseResult for QueryHistoryResponse {}
368
369/// Request payload sent by a physical web client. This request includes all necessary context to load a particular user experience record.
370///
371/// # Activities
372///
373/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
374/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
375///
376/// * [query record records](RecordQueryRecordCall) (request)
377#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
378#[serde_with::serde_as]
379#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
380pub struct QueryRequest {
381 /// The effective connection type is a query dimension that specifies the effective network class that the record's data should belong to. This field uses the values ["offline", "slow-2G", "2G", "3G", "4G"] as specified in: https://wicg.github.io/netinfo/#effective-connection-types Note: If no effective connection type is specified, then a special record with aggregated data over all effective connection types will be returned.
382 #[serde(rename = "effectiveConnectionType")]
383 pub effective_connection_type: Option<String>,
384 /// The form factor is a query dimension that specifies the device class that the record's data should belong to. Note: If no form factor is specified, then a special record with aggregated data over all form factors will be returned.
385 #[serde(rename = "formFactor")]
386 pub form_factor: Option<String>,
387 /// The metrics that should be included in the response. If none are specified then any metrics found will be returned. Allowed values: ["first_contentful_paint", "first_input_delay", "largest_contentful_paint", "cumulative_layout_shift", "experimental_time_to_first_byte", "experimental_interaction_to_next_paint"]
388 pub metrics: Option<Vec<String>>,
389 /// The url pattern "origin" refers to a url pattern that is the origin of a website. Examples: "https://example.com", "https://cloud.google.com"
390 pub origin: Option<String>,
391 /// The url pattern "url" refers to a url pattern that is any arbitrary url. Examples: "https://example.com/", "https://cloud.google.com/why-google-cloud/"
392 pub url: Option<String>,
393}
394
395impl common::RequestValue for QueryRequest {}
396
397/// Response payload sent back to a physical web client. This response contains the record found based on the identiers present in a `QueryRequest`. The returned response will have a record, and sometimes details on normalization actions taken on the request that were necessary to make the request successful.
398///
399/// # Activities
400///
401/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
402/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
403///
404/// * [query record records](RecordQueryRecordCall) (response)
405#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
406#[serde_with::serde_as]
407#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
408pub struct QueryResponse {
409 /// The record that was found.
410 pub record: Option<Record>,
411 /// These are details about automated normalization actions that were taken in order to make the requested `url_pattern` valid.
412 #[serde(rename = "urlNormalizationDetails")]
413 pub url_normalization_details: Option<UrlNormalization>,
414}
415
416impl common::ResponseResult for QueryResponse {}
417
418/// Record is a single Chrome UX report data record. It contains use experience statistics for a single url pattern and set of dimensions.
419///
420/// # Activities
421///
422/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
423/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
424///
425/// * [query history record records](RecordQueryHistoryRecordCall) (none)
426/// * [query record records](RecordQueryRecordCall) (none)
427#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
428#[serde_with::serde_as]
429#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
430pub struct Record {
431 /// The collection period indicates when the data reflected in this record was collected.
432 #[serde(rename = "collectionPeriod")]
433 pub collection_period: Option<CollectionPeriod>,
434 /// Key defines all of the unique querying parameters needed to look up a user experience record.
435 pub key: Option<Key>,
436 /// Metrics is the map of user experience data available for the record defined in the key field. Metrics are keyed on the metric name. Allowed key values: ["first_contentful_paint", "first_input_delay", "largest_contentful_paint", "cumulative_layout_shift", "experimental_time_to_first_byte", "experimental_interaction_to_next_paint"]
437 pub metrics: Option<HashMap<String, Metric>>,
438}
439
440impl common::Resource for Record {}
441
442/// A bin is a discrete portion of data spanning from start to end, or if no end is given, then from start to +inf. A bin's start and end values are given in the value type of the metric it represents. For example, "first contentful paint" is measured in milliseconds and exposed as ints, therefore its metric bins will use int32s for its start and end types. However, "cumulative layout shift" is measured in unitless decimals and is exposed as a decimal encoded as a string, therefore its metric bins will use strings for its value type.
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 TimeseriesBin {
450 /// The proportion of users that experienced this bin's value for the given metric in a given collection period; the index for each of these entries corresponds to an entry in the CollectionPeriods field in the HistoryRecord message, which describes when the density was observed in the field. Thus, the length of this list of densities is equal to the length of the CollectionPeriods field in the HistoryRecord message.
451 pub densities: Option<Vec<f64>>,
452 /// End is the end of the data bin. If end is not populated, then the bin has no end and is valid from start to +inf.
453 pub end: Option<serde_json::Value>,
454 /// Start is the beginning of the data bin.
455 pub start: Option<serde_json::Value>,
456}
457
458impl common::Part for TimeseriesBin {}
459
460/// Percentiles contains synthetic values of a metric at a given statistical percentile. These are used for estimating a metric's value as experienced by a percentage of users out of the total number of users.
461///
462/// This type is not used in any activity, and only used as *part* of another schema.
463///
464#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
465#[serde_with::serde_as]
466#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
467pub struct TimeseriesPercentiles {
468 /// 75% of users experienced the given metric at or below this value. The length of this list of densities is equal to the length of the CollectionPeriods field in the HistoryRecord message, which describes when the density was observed in the field.
469 pub p75s: Option<Vec<serde_json::Value>>,
470}
471
472impl common::Part for TimeseriesPercentiles {}
473
474/// Object representing the normalization actions taken to normalize a url to achieve a higher chance of successful lookup. These are simple automated changes that are taken when looking up the provided `url_patten` would be known to fail. Complex actions like following redirects are not handled.
475///
476/// This type is not used in any activity, and only used as *part* of another schema.
477///
478#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
479#[serde_with::serde_as]
480#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
481pub struct UrlNormalization {
482 /// The URL after any normalization actions. This is a valid user experience URL that could reasonably be looked up.
483 #[serde(rename = "normalizedUrl")]
484 pub normalized_url: Option<String>,
485 /// The original requested URL prior to any normalization actions.
486 #[serde(rename = "originalUrl")]
487 pub original_url: Option<String>,
488}
489
490impl common::Part for UrlNormalization {}
491
492// ###################
493// MethodBuilders ###
494// #################
495
496/// A builder providing access to all methods supported on *record* resources.
497/// It is not used directly, but through the [`ChromeUXReport`] hub.
498///
499/// # Example
500///
501/// Instantiate a resource builder
502///
503/// ```test_harness,no_run
504/// extern crate hyper;
505/// extern crate hyper_rustls;
506/// extern crate google_chromeuxreport1 as chromeuxreport1;
507///
508/// # async fn dox() {
509/// use chromeuxreport1::{ChromeUXReport, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
510///
511/// let secret: yup_oauth2::ApplicationSecret = Default::default();
512/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
513/// secret,
514/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
515/// ).build().await.unwrap();
516///
517/// let client = hyper_util::client::legacy::Client::builder(
518/// hyper_util::rt::TokioExecutor::new()
519/// )
520/// .build(
521/// hyper_rustls::HttpsConnectorBuilder::new()
522/// .with_native_roots()
523/// .unwrap()
524/// .https_or_http()
525/// .enable_http1()
526/// .build()
527/// );
528/// let mut hub = ChromeUXReport::new(client, auth);
529/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
530/// // like `query_history_record(...)` and `query_record(...)`
531/// // to build up your call.
532/// let rb = hub.records();
533/// # }
534/// ```
535pub struct RecordMethods<'a, C>
536where
537 C: 'a,
538{
539 hub: &'a ChromeUXReport<C>,
540}
541
542impl<'a, C> common::MethodsBuilder for RecordMethods<'a, C> {}
543
544impl<'a, C> RecordMethods<'a, C> {
545 /// Create a builder to help you perform the following task:
546 ///
547 /// Queries the Chrome User Experience Report for a timeseries `history record` for a given site. Returns a `history record` that contains one or more `metric timeseries` corresponding to performance data about the requested site.
548 ///
549 /// # Arguments
550 ///
551 /// * `request` - No description provided.
552 pub fn query_history_record(
553 &self,
554 request: QueryHistoryRequest,
555 ) -> RecordQueryHistoryRecordCall<'a, C> {
556 RecordQueryHistoryRecordCall {
557 hub: self.hub,
558 _request: request,
559 _delegate: Default::default(),
560 _additional_params: Default::default(),
561 }
562 }
563
564 /// Create a builder to help you perform the following task:
565 ///
566 /// Queries the Chrome User Experience for a single `record` for a given site. Returns a `record` that contains one or more `metrics` corresponding to performance data about the requested site.
567 ///
568 /// # Arguments
569 ///
570 /// * `request` - No description provided.
571 pub fn query_record(&self, request: QueryRequest) -> RecordQueryRecordCall<'a, C> {
572 RecordQueryRecordCall {
573 hub: self.hub,
574 _request: request,
575 _delegate: Default::default(),
576 _additional_params: Default::default(),
577 }
578 }
579}
580
581// ###################
582// CallBuilders ###
583// #################
584
585/// Queries the Chrome User Experience Report for a timeseries `history record` for a given site. Returns a `history record` that contains one or more `metric timeseries` corresponding to performance data about the requested site.
586///
587/// A builder for the *queryHistoryRecord* method supported by a *record* resource.
588/// It is not used directly, but through a [`RecordMethods`] instance.
589///
590/// # Example
591///
592/// Instantiate a resource method builder
593///
594/// ```test_harness,no_run
595/// # extern crate hyper;
596/// # extern crate hyper_rustls;
597/// # extern crate google_chromeuxreport1 as chromeuxreport1;
598/// use chromeuxreport1::api::QueryHistoryRequest;
599/// # async fn dox() {
600/// # use chromeuxreport1::{ChromeUXReport, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
601///
602/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
603/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
604/// # secret,
605/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
606/// # ).build().await.unwrap();
607///
608/// # let client = hyper_util::client::legacy::Client::builder(
609/// # hyper_util::rt::TokioExecutor::new()
610/// # )
611/// # .build(
612/// # hyper_rustls::HttpsConnectorBuilder::new()
613/// # .with_native_roots()
614/// # .unwrap()
615/// # .https_or_http()
616/// # .enable_http1()
617/// # .build()
618/// # );
619/// # let mut hub = ChromeUXReport::new(client, auth);
620/// // As the method needs a request, you would usually fill it with the desired information
621/// // into the respective structure. Some of the parts shown here might not be applicable !
622/// // Values shown here are possibly random and not representative !
623/// let mut req = QueryHistoryRequest::default();
624///
625/// // You can configure optional parameters by calling the respective setters at will, and
626/// // execute the final call using `doit()`.
627/// // Values shown here are possibly random and not representative !
628/// let result = hub.records().query_history_record(req)
629/// .doit().await;
630/// # }
631/// ```
632pub struct RecordQueryHistoryRecordCall<'a, C>
633where
634 C: 'a,
635{
636 hub: &'a ChromeUXReport<C>,
637 _request: QueryHistoryRequest,
638 _delegate: Option<&'a mut dyn common::Delegate>,
639 _additional_params: HashMap<String, String>,
640}
641
642impl<'a, C> common::CallBuilder for RecordQueryHistoryRecordCall<'a, C> {}
643
644impl<'a, C> RecordQueryHistoryRecordCall<'a, C>
645where
646 C: common::Connector,
647{
648 /// Perform the operation you have build so far.
649 pub async fn doit(mut self) -> common::Result<(common::Response, QueryHistoryResponse)> {
650 use std::borrow::Cow;
651 use std::io::{Read, Seek};
652
653 use common::{url::Params, ToParts};
654 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
655
656 let mut dd = common::DefaultDelegate;
657 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
658 dlg.begin(common::MethodInfo {
659 id: "chromeuxreport.records.queryHistoryRecord",
660 http_method: hyper::Method::POST,
661 });
662
663 for &field in ["alt"].iter() {
664 if self._additional_params.contains_key(field) {
665 dlg.finished(false);
666 return Err(common::Error::FieldClash(field));
667 }
668 }
669
670 let mut params = Params::with_capacity(3 + self._additional_params.len());
671
672 params.extend(self._additional_params.iter());
673
674 params.push("alt", "json");
675 let mut url = self.hub._base_url.clone() + "v1/records:queryHistoryRecord";
676
677 match dlg.api_key() {
678 Some(value) => params.push("key", value),
679 None => {
680 dlg.finished(false);
681 return Err(common::Error::MissingAPIKey);
682 }
683 }
684
685 let url = params.parse_with_url(&url);
686
687 let mut json_mime_type = mime::APPLICATION_JSON;
688 let mut request_value_reader = {
689 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
690 common::remove_json_null_values(&mut value);
691 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
692 serde_json::to_writer(&mut dst, &value).unwrap();
693 dst
694 };
695 let request_size = request_value_reader
696 .seek(std::io::SeekFrom::End(0))
697 .unwrap();
698 request_value_reader
699 .seek(std::io::SeekFrom::Start(0))
700 .unwrap();
701
702 loop {
703 request_value_reader
704 .seek(std::io::SeekFrom::Start(0))
705 .unwrap();
706 let mut req_result = {
707 let client = &self.hub.client;
708 dlg.pre_request();
709 let mut req_builder = hyper::Request::builder()
710 .method(hyper::Method::POST)
711 .uri(url.as_str())
712 .header(USER_AGENT, self.hub._user_agent.clone());
713
714 let request = req_builder
715 .header(CONTENT_TYPE, json_mime_type.to_string())
716 .header(CONTENT_LENGTH, request_size as u64)
717 .body(common::to_body(
718 request_value_reader.get_ref().clone().into(),
719 ));
720
721 client.request(request.unwrap()).await
722 };
723
724 match req_result {
725 Err(err) => {
726 if let common::Retry::After(d) = dlg.http_error(&err) {
727 sleep(d).await;
728 continue;
729 }
730 dlg.finished(false);
731 return Err(common::Error::HttpError(err));
732 }
733 Ok(res) => {
734 let (mut parts, body) = res.into_parts();
735 let mut body = common::Body::new(body);
736 if !parts.status.is_success() {
737 let bytes = common::to_bytes(body).await.unwrap_or_default();
738 let error = serde_json::from_str(&common::to_string(&bytes));
739 let response = common::to_response(parts, bytes.into());
740
741 if let common::Retry::After(d) =
742 dlg.http_failure(&response, error.as_ref().ok())
743 {
744 sleep(d).await;
745 continue;
746 }
747
748 dlg.finished(false);
749
750 return Err(match error {
751 Ok(value) => common::Error::BadRequest(value),
752 _ => common::Error::Failure(response),
753 });
754 }
755 let response = {
756 let bytes = common::to_bytes(body).await.unwrap_or_default();
757 let encoded = common::to_string(&bytes);
758 match serde_json::from_str(&encoded) {
759 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
760 Err(error) => {
761 dlg.response_json_decode_error(&encoded, &error);
762 return Err(common::Error::JsonDecodeError(
763 encoded.to_string(),
764 error,
765 ));
766 }
767 }
768 };
769
770 dlg.finished(true);
771 return Ok(response);
772 }
773 }
774 }
775 }
776
777 ///
778 /// Sets the *request* property to the given value.
779 ///
780 /// Even though the property as already been set when instantiating this call,
781 /// we provide this method for API completeness.
782 pub fn request(
783 mut self,
784 new_value: QueryHistoryRequest,
785 ) -> RecordQueryHistoryRecordCall<'a, C> {
786 self._request = new_value;
787 self
788 }
789 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
790 /// while executing the actual API request.
791 ///
792 /// ````text
793 /// It should be used to handle progress information, and to implement a certain level of resilience.
794 /// ````
795 ///
796 /// Sets the *delegate* property to the given value.
797 pub fn delegate(
798 mut self,
799 new_value: &'a mut dyn common::Delegate,
800 ) -> RecordQueryHistoryRecordCall<'a, C> {
801 self._delegate = Some(new_value);
802 self
803 }
804
805 /// Set any additional parameter of the query string used in the request.
806 /// It should be used to set parameters which are not yet available through their own
807 /// setters.
808 ///
809 /// Please note that this method must not be used to set any of the known parameters
810 /// which have their own setter method. If done anyway, the request will fail.
811 ///
812 /// # Additional Parameters
813 ///
814 /// * *$.xgafv* (query-string) - V1 error format.
815 /// * *access_token* (query-string) - OAuth access token.
816 /// * *alt* (query-string) - Data format for response.
817 /// * *callback* (query-string) - JSONP
818 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
819 /// * *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.
820 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
821 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
822 /// * *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.
823 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
824 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
825 pub fn param<T>(mut self, name: T, value: T) -> RecordQueryHistoryRecordCall<'a, C>
826 where
827 T: AsRef<str>,
828 {
829 self._additional_params
830 .insert(name.as_ref().to_string(), value.as_ref().to_string());
831 self
832 }
833}
834
835/// Queries the Chrome User Experience for a single `record` for a given site. Returns a `record` that contains one or more `metrics` corresponding to performance data about the requested site.
836///
837/// A builder for the *queryRecord* method supported by a *record* resource.
838/// It is not used directly, but through a [`RecordMethods`] instance.
839///
840/// # Example
841///
842/// Instantiate a resource method builder
843///
844/// ```test_harness,no_run
845/// # extern crate hyper;
846/// # extern crate hyper_rustls;
847/// # extern crate google_chromeuxreport1 as chromeuxreport1;
848/// use chromeuxreport1::api::QueryRequest;
849/// # async fn dox() {
850/// # use chromeuxreport1::{ChromeUXReport, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
851///
852/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
853/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
854/// # secret,
855/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
856/// # ).build().await.unwrap();
857///
858/// # let client = hyper_util::client::legacy::Client::builder(
859/// # hyper_util::rt::TokioExecutor::new()
860/// # )
861/// # .build(
862/// # hyper_rustls::HttpsConnectorBuilder::new()
863/// # .with_native_roots()
864/// # .unwrap()
865/// # .https_or_http()
866/// # .enable_http1()
867/// # .build()
868/// # );
869/// # let mut hub = ChromeUXReport::new(client, auth);
870/// // As the method needs a request, you would usually fill it with the desired information
871/// // into the respective structure. Some of the parts shown here might not be applicable !
872/// // Values shown here are possibly random and not representative !
873/// let mut req = QueryRequest::default();
874///
875/// // You can configure optional parameters by calling the respective setters at will, and
876/// // execute the final call using `doit()`.
877/// // Values shown here are possibly random and not representative !
878/// let result = hub.records().query_record(req)
879/// .doit().await;
880/// # }
881/// ```
882pub struct RecordQueryRecordCall<'a, C>
883where
884 C: 'a,
885{
886 hub: &'a ChromeUXReport<C>,
887 _request: QueryRequest,
888 _delegate: Option<&'a mut dyn common::Delegate>,
889 _additional_params: HashMap<String, String>,
890}
891
892impl<'a, C> common::CallBuilder for RecordQueryRecordCall<'a, C> {}
893
894impl<'a, C> RecordQueryRecordCall<'a, C>
895where
896 C: common::Connector,
897{
898 /// Perform the operation you have build so far.
899 pub async fn doit(mut self) -> common::Result<(common::Response, QueryResponse)> {
900 use std::borrow::Cow;
901 use std::io::{Read, Seek};
902
903 use common::{url::Params, ToParts};
904 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
905
906 let mut dd = common::DefaultDelegate;
907 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
908 dlg.begin(common::MethodInfo {
909 id: "chromeuxreport.records.queryRecord",
910 http_method: hyper::Method::POST,
911 });
912
913 for &field in ["alt"].iter() {
914 if self._additional_params.contains_key(field) {
915 dlg.finished(false);
916 return Err(common::Error::FieldClash(field));
917 }
918 }
919
920 let mut params = Params::with_capacity(3 + self._additional_params.len());
921
922 params.extend(self._additional_params.iter());
923
924 params.push("alt", "json");
925 let mut url = self.hub._base_url.clone() + "v1/records:queryRecord";
926
927 match dlg.api_key() {
928 Some(value) => params.push("key", value),
929 None => {
930 dlg.finished(false);
931 return Err(common::Error::MissingAPIKey);
932 }
933 }
934
935 let url = params.parse_with_url(&url);
936
937 let mut json_mime_type = mime::APPLICATION_JSON;
938 let mut request_value_reader = {
939 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
940 common::remove_json_null_values(&mut value);
941 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
942 serde_json::to_writer(&mut dst, &value).unwrap();
943 dst
944 };
945 let request_size = request_value_reader
946 .seek(std::io::SeekFrom::End(0))
947 .unwrap();
948 request_value_reader
949 .seek(std::io::SeekFrom::Start(0))
950 .unwrap();
951
952 loop {
953 request_value_reader
954 .seek(std::io::SeekFrom::Start(0))
955 .unwrap();
956 let mut req_result = {
957 let client = &self.hub.client;
958 dlg.pre_request();
959 let mut req_builder = hyper::Request::builder()
960 .method(hyper::Method::POST)
961 .uri(url.as_str())
962 .header(USER_AGENT, self.hub._user_agent.clone());
963
964 let request = req_builder
965 .header(CONTENT_TYPE, json_mime_type.to_string())
966 .header(CONTENT_LENGTH, request_size as u64)
967 .body(common::to_body(
968 request_value_reader.get_ref().clone().into(),
969 ));
970
971 client.request(request.unwrap()).await
972 };
973
974 match req_result {
975 Err(err) => {
976 if let common::Retry::After(d) = dlg.http_error(&err) {
977 sleep(d).await;
978 continue;
979 }
980 dlg.finished(false);
981 return Err(common::Error::HttpError(err));
982 }
983 Ok(res) => {
984 let (mut parts, body) = res.into_parts();
985 let mut body = common::Body::new(body);
986 if !parts.status.is_success() {
987 let bytes = common::to_bytes(body).await.unwrap_or_default();
988 let error = serde_json::from_str(&common::to_string(&bytes));
989 let response = common::to_response(parts, bytes.into());
990
991 if let common::Retry::After(d) =
992 dlg.http_failure(&response, error.as_ref().ok())
993 {
994 sleep(d).await;
995 continue;
996 }
997
998 dlg.finished(false);
999
1000 return Err(match error {
1001 Ok(value) => common::Error::BadRequest(value),
1002 _ => common::Error::Failure(response),
1003 });
1004 }
1005 let response = {
1006 let bytes = common::to_bytes(body).await.unwrap_or_default();
1007 let encoded = common::to_string(&bytes);
1008 match serde_json::from_str(&encoded) {
1009 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1010 Err(error) => {
1011 dlg.response_json_decode_error(&encoded, &error);
1012 return Err(common::Error::JsonDecodeError(
1013 encoded.to_string(),
1014 error,
1015 ));
1016 }
1017 }
1018 };
1019
1020 dlg.finished(true);
1021 return Ok(response);
1022 }
1023 }
1024 }
1025 }
1026
1027 ///
1028 /// Sets the *request* property to the given value.
1029 ///
1030 /// Even though the property as already been set when instantiating this call,
1031 /// we provide this method for API completeness.
1032 pub fn request(mut self, new_value: QueryRequest) -> RecordQueryRecordCall<'a, C> {
1033 self._request = new_value;
1034 self
1035 }
1036 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1037 /// while executing the actual API request.
1038 ///
1039 /// ````text
1040 /// It should be used to handle progress information, and to implement a certain level of resilience.
1041 /// ````
1042 ///
1043 /// Sets the *delegate* property to the given value.
1044 pub fn delegate(
1045 mut self,
1046 new_value: &'a mut dyn common::Delegate,
1047 ) -> RecordQueryRecordCall<'a, C> {
1048 self._delegate = Some(new_value);
1049 self
1050 }
1051
1052 /// Set any additional parameter of the query string used in the request.
1053 /// It should be used to set parameters which are not yet available through their own
1054 /// setters.
1055 ///
1056 /// Please note that this method must not be used to set any of the known parameters
1057 /// which have their own setter method. If done anyway, the request will fail.
1058 ///
1059 /// # Additional Parameters
1060 ///
1061 /// * *$.xgafv* (query-string) - V1 error format.
1062 /// * *access_token* (query-string) - OAuth access token.
1063 /// * *alt* (query-string) - Data format for response.
1064 /// * *callback* (query-string) - JSONP
1065 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1066 /// * *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.
1067 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1068 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1069 /// * *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.
1070 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1071 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1072 pub fn param<T>(mut self, name: T, value: T) -> RecordQueryRecordCall<'a, C>
1073 where
1074 T: AsRef<str>,
1075 {
1076 self._additional_params
1077 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1078 self
1079 }
1080}