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