google_prediction1d6/api.rs
1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16 /// View and manage your data across Google Cloud Platform services
17 CloudPlatform,
18
19 /// Manage your data and permissions in Google Cloud Storage
20 DevstorageFullControl,
21
22 /// View your data in Google Cloud Storage
23 DevstorageReadOnly,
24
25 /// Manage your data in Google Cloud Storage
26 DevstorageReadWrite,
27
28 /// Manage your data in the Google Prediction API
29 Full,
30}
31
32impl AsRef<str> for Scope {
33 fn as_ref(&self) -> &str {
34 match *self {
35 Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
36 Scope::DevstorageFullControl => {
37 "https://www.googleapis.com/auth/devstorage.full_control"
38 }
39 Scope::DevstorageReadOnly => "https://www.googleapis.com/auth/devstorage.read_only",
40 Scope::DevstorageReadWrite => "https://www.googleapis.com/auth/devstorage.read_write",
41 Scope::Full => "https://www.googleapis.com/auth/prediction",
42 }
43 }
44}
45
46#[allow(clippy::derivable_impls)]
47impl Default for Scope {
48 fn default() -> Scope {
49 Scope::Full
50 }
51}
52
53// ########
54// HUB ###
55// ######
56
57/// Central instance to access all Prediction related resource activities
58///
59/// # Examples
60///
61/// Instantiate a new hub
62///
63/// ```test_harness,no_run
64/// extern crate hyper;
65/// extern crate hyper_rustls;
66/// extern crate google_prediction1d6 as prediction1d6;
67/// use prediction1d6::api::Update;
68/// use prediction1d6::{Result, Error};
69/// # async fn dox() {
70/// use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
71///
72/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
73/// // `client_secret`, among other things.
74/// let secret: yup_oauth2::ApplicationSecret = Default::default();
75/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
76/// // unless you replace `None` with the desired Flow.
77/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
78/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
79/// // retrieve them from storage.
80/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
81/// .with_native_roots()
82/// .unwrap()
83/// .https_only()
84/// .enable_http2()
85/// .build();
86///
87/// let executor = hyper_util::rt::TokioExecutor::new();
88/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
89/// secret,
90/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
91/// yup_oauth2::client::CustomHyperClientBuilder::from(
92/// hyper_util::client::legacy::Client::builder(executor).build(connector),
93/// ),
94/// ).build().await.unwrap();
95///
96/// let client = hyper_util::client::legacy::Client::builder(
97/// hyper_util::rt::TokioExecutor::new()
98/// )
99/// .build(
100/// hyper_rustls::HttpsConnectorBuilder::new()
101/// .with_native_roots()
102/// .unwrap()
103/// .https_or_http()
104/// .enable_http2()
105/// .build()
106/// );
107/// let mut hub = Prediction::new(client, auth);
108/// // As the method needs a request, you would usually fill it with the desired information
109/// // into the respective structure. Some of the parts shown here might not be applicable !
110/// // Values shown here are possibly random and not representative !
111/// let mut req = Update::default();
112///
113/// // You can configure optional parameters by calling the respective setters at will, and
114/// // execute the final call using `doit()`.
115/// // Values shown here are possibly random and not representative !
116/// let result = hub.trainedmodels().update(req, "project", "id")
117/// .doit().await;
118///
119/// match result {
120/// Err(e) => match e {
121/// // The Error enum provides details about what exactly happened.
122/// // You can also just use its `Debug`, `Display` or `Error` traits
123/// Error::HttpError(_)
124/// |Error::Io(_)
125/// |Error::MissingAPIKey
126/// |Error::MissingToken(_)
127/// |Error::Cancelled
128/// |Error::UploadSizeLimitExceeded(_, _)
129/// |Error::Failure(_)
130/// |Error::BadRequest(_)
131/// |Error::FieldClash(_)
132/// |Error::JsonDecodeError(_, _) => println!("{}", e),
133/// },
134/// Ok(res) => println!("Success: {:?}", res),
135/// }
136/// # }
137/// ```
138#[derive(Clone)]
139pub struct Prediction<C> {
140 pub client: common::Client<C>,
141 pub auth: Box<dyn common::GetToken>,
142 _user_agent: String,
143 _base_url: String,
144 _root_url: String,
145}
146
147impl<C> common::Hub for Prediction<C> {}
148
149impl<'a, C> Prediction<C> {
150 pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> Prediction<C> {
151 Prediction {
152 client,
153 auth: Box::new(auth),
154 _user_agent: "google-api-rust-client/7.0.0".to_string(),
155 _base_url: "https://www.googleapis.com/prediction/v1.6/projects/".to_string(),
156 _root_url: "https://www.googleapis.com/".to_string(),
157 }
158 }
159
160 pub fn hostedmodels(&'a self) -> HostedmodelMethods<'a, C> {
161 HostedmodelMethods { hub: self }
162 }
163 pub fn trainedmodels(&'a self) -> TrainedmodelMethods<'a, C> {
164 TrainedmodelMethods { hub: self }
165 }
166
167 /// Set the user-agent header field to use in all requests to the server.
168 /// It defaults to `google-api-rust-client/7.0.0`.
169 ///
170 /// Returns the previously set user-agent.
171 pub fn user_agent(&mut self, agent_name: String) -> String {
172 std::mem::replace(&mut self._user_agent, agent_name)
173 }
174
175 /// Set the base url to use in all requests to the server.
176 /// It defaults to `https://www.googleapis.com/prediction/v1.6/projects/`.
177 ///
178 /// Returns the previously set base url.
179 pub fn base_url(&mut self, new_base_url: String) -> String {
180 std::mem::replace(&mut self._base_url, new_base_url)
181 }
182
183 /// Set the root url to use in all requests to the server.
184 /// It defaults to `https://www.googleapis.com/`.
185 ///
186 /// Returns the previously set root url.
187 pub fn root_url(&mut self, new_root_url: String) -> String {
188 std::mem::replace(&mut self._root_url, new_root_url)
189 }
190}
191
192// ############
193// SCHEMAS ###
194// ##########
195/// There is no detailed description.
196///
197/// # Activities
198///
199/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
200/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
201///
202/// * [analyze trainedmodels](TrainedmodelAnalyzeCall) (response)
203#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
204#[serde_with::serde_as]
205#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
206pub struct Analyze {
207 /// Description of the data the model was trained on.
208 #[serde(rename = "dataDescription")]
209 pub data_description: Option<AnalyzeDataDescription>,
210 /// List of errors with the data.
211 pub errors: Option<Vec<HashMap<String, String>>>,
212 /// The unique name for the predictive model.
213 pub id: Option<String>,
214 /// What kind of resource this is.
215 pub kind: Option<String>,
216 /// Description of the model.
217 #[serde(rename = "modelDescription")]
218 pub model_description: Option<AnalyzeModelDescription>,
219 /// A URL to re-request this resource.
220 #[serde(rename = "selfLink")]
221 pub self_link: Option<String>,
222}
223
224impl common::ResponseResult for Analyze {}
225
226/// There is no detailed description.
227///
228/// # Activities
229///
230/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
231/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
232///
233/// * [predict hostedmodels](HostedmodelPredictCall) (request)
234/// * [predict trainedmodels](TrainedmodelPredictCall) (request)
235#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
236#[serde_with::serde_as]
237#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
238pub struct Input {
239 /// Input to the model for a prediction.
240 pub input: Option<InputInput>,
241}
242
243impl common::RequestValue for Input {}
244
245/// There is no detailed description.
246///
247/// # Activities
248///
249/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
250/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
251///
252/// * [insert trainedmodels](TrainedmodelInsertCall) (request)
253#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
254#[serde_with::serde_as]
255#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
256pub struct Insert {
257 /// The unique name for the predictive model.
258 pub id: Option<String>,
259 /// Type of predictive model (classification or regression).
260 #[serde(rename = "modelType")]
261 pub model_type: Option<String>,
262 /// The Id of the model to be copied over.
263 #[serde(rename = "sourceModel")]
264 pub source_model: Option<String>,
265 /// Google storage location of the training data file.
266 #[serde(rename = "storageDataLocation")]
267 pub storage_data_location: Option<String>,
268 /// Google storage location of the preprocessing pmml file.
269 #[serde(rename = "storagePMMLLocation")]
270 pub storage_pmml_location: Option<String>,
271 /// Google storage location of the pmml model file.
272 #[serde(rename = "storagePMMLModelLocation")]
273 pub storage_pmml_model_location: Option<String>,
274 /// Instances to train model on.
275 #[serde(rename = "trainingInstances")]
276 pub training_instances: Option<Vec<InsertTrainingInstances>>,
277 /// A class weighting function, which allows the importance weights for class labels to be specified (Categorical models only).
278 pub utility: Option<Vec<HashMap<String, f64>>>,
279}
280
281impl common::RequestValue for Insert {}
282
283/// There is no detailed description.
284///
285/// # Activities
286///
287/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
288/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
289///
290/// * [get trainedmodels](TrainedmodelGetCall) (response)
291/// * [insert trainedmodels](TrainedmodelInsertCall) (response)
292/// * [update trainedmodels](TrainedmodelUpdateCall) (response)
293#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
294#[serde_with::serde_as]
295#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
296pub struct Insert2 {
297 /// Insert time of the model (as a RFC 3339 timestamp).
298 pub created: Option<chrono::DateTime<chrono::offset::Utc>>,
299 /// The unique name for the predictive model.
300 pub id: Option<String>,
301 /// What kind of resource this is.
302 pub kind: Option<String>,
303 /// Model metadata.
304 #[serde(rename = "modelInfo")]
305 pub model_info: Option<Insert2ModelInfo>,
306 /// Type of predictive model (CLASSIFICATION or REGRESSION).
307 #[serde(rename = "modelType")]
308 pub model_type: Option<String>,
309 /// A URL to re-request this resource.
310 #[serde(rename = "selfLink")]
311 pub self_link: Option<String>,
312 /// Google storage location of the training data file.
313 #[serde(rename = "storageDataLocation")]
314 pub storage_data_location: Option<String>,
315 /// Google storage location of the preprocessing pmml file.
316 #[serde(rename = "storagePMMLLocation")]
317 pub storage_pmml_location: Option<String>,
318 /// Google storage location of the pmml model file.
319 #[serde(rename = "storagePMMLModelLocation")]
320 pub storage_pmml_model_location: Option<String>,
321 /// Training completion time (as a RFC 3339 timestamp).
322 #[serde(rename = "trainingComplete")]
323 pub training_complete: Option<chrono::DateTime<chrono::offset::Utc>>,
324 /// The current status of the training job. This can be one of following: RUNNING; DONE; ERROR; ERROR: TRAINING JOB NOT FOUND
325 #[serde(rename = "trainingStatus")]
326 pub training_status: Option<String>,
327}
328
329impl common::ResponseResult for Insert2 {}
330
331/// There is no detailed description.
332///
333/// # Activities
334///
335/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
336/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
337///
338/// * [list trainedmodels](TrainedmodelListCall) (response)
339#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
340#[serde_with::serde_as]
341#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
342pub struct List {
343 /// List of models.
344 pub items: Option<Vec<Insert2>>,
345 /// What kind of resource this is.
346 pub kind: Option<String>,
347 /// Pagination token to fetch the next page, if one exists.
348 #[serde(rename = "nextPageToken")]
349 pub next_page_token: Option<String>,
350 /// A URL to re-request this resource.
351 #[serde(rename = "selfLink")]
352 pub self_link: Option<String>,
353}
354
355impl common::ResponseResult for List {}
356
357/// There is no detailed description.
358///
359/// # Activities
360///
361/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
362/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
363///
364/// * [predict hostedmodels](HostedmodelPredictCall) (response)
365/// * [predict trainedmodels](TrainedmodelPredictCall) (response)
366#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
367#[serde_with::serde_as]
368#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
369pub struct Output {
370 /// The unique name for the predictive model.
371 pub id: Option<String>,
372 /// What kind of resource this is.
373 pub kind: Option<String>,
374 /// The most likely class label (Categorical models only).
375 #[serde(rename = "outputLabel")]
376 pub output_label: Option<String>,
377 /// A list of class labels with their estimated probabilities (Categorical models only).
378 #[serde(rename = "outputMulti")]
379 pub output_multi: Option<Vec<OutputOutputMulti>>,
380 /// The estimated regression value (Regression models only).
381 #[serde(rename = "outputValue")]
382 pub output_value: Option<String>,
383 /// A URL to re-request this resource.
384 #[serde(rename = "selfLink")]
385 pub self_link: Option<String>,
386}
387
388impl common::ResponseResult for Output {}
389
390/// There is no detailed description.
391///
392/// # Activities
393///
394/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
395/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
396///
397/// * [update trainedmodels](TrainedmodelUpdateCall) (request)
398#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
399#[serde_with::serde_as]
400#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
401pub struct Update {
402 /// The input features for this instance.
403 #[serde(rename = "csvInstance")]
404 pub csv_instance: Option<Vec<serde_json::Value>>,
405 /// The generic output value - could be regression or class label.
406 pub output: Option<String>,
407}
408
409impl common::RequestValue for Update {}
410
411/// Description of the data the model was trained on.
412///
413/// This type is not used in any activity, and only used as *part* of another schema.
414///
415#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
416#[serde_with::serde_as]
417#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
418pub struct AnalyzeDataDescription {
419 /// Description of the input features in the data set.
420 pub features: Option<Vec<AnalyzeDataDescriptionFeatures>>,
421 /// Description of the output value or label.
422 #[serde(rename = "outputFeature")]
423 pub output_feature: Option<AnalyzeDataDescriptionOutputFeature>,
424}
425
426impl common::NestedType for AnalyzeDataDescription {}
427impl common::Part for AnalyzeDataDescription {}
428
429/// Description of the input features in the data set.
430///
431/// This type is not used in any activity, and only used as *part* of another schema.
432///
433#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
434#[serde_with::serde_as]
435#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
436pub struct AnalyzeDataDescriptionFeatures {
437 /// Description of the categorical values of this feature.
438 pub categorical: Option<AnalyzeDataDescriptionFeaturesCategorical>,
439 /// The feature index.
440 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
441 pub index: Option<i64>,
442 /// Description of the numeric values of this feature.
443 pub numeric: Option<AnalyzeDataDescriptionFeaturesNumeric>,
444 /// Description of multiple-word text values of this feature.
445 pub text: Option<AnalyzeDataDescriptionFeaturesText>,
446}
447
448impl common::NestedType for AnalyzeDataDescriptionFeatures {}
449impl common::Part for AnalyzeDataDescriptionFeatures {}
450
451/// Description of the categorical values of this feature.
452///
453/// This type is not used in any activity, and only used as *part* of another schema.
454///
455#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
456#[serde_with::serde_as]
457#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
458pub struct AnalyzeDataDescriptionFeaturesCategorical {
459 /// Number of categorical values for this feature in the data.
460 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
461 pub count: Option<i64>,
462 /// List of all the categories for this feature in the data set.
463 pub values: Option<Vec<AnalyzeDataDescriptionFeaturesCategoricalValues>>,
464}
465
466impl common::NestedType for AnalyzeDataDescriptionFeaturesCategorical {}
467impl common::Part for AnalyzeDataDescriptionFeaturesCategorical {}
468
469/// List of all the categories for this feature in the data set.
470///
471/// This type is not used in any activity, and only used as *part* of another schema.
472///
473#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
474#[serde_with::serde_as]
475#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
476pub struct AnalyzeDataDescriptionFeaturesCategoricalValues {
477 /// Number of times this feature had this value.
478 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
479 pub count: Option<i64>,
480 /// The category name.
481 pub value: Option<String>,
482}
483
484impl common::NestedType for AnalyzeDataDescriptionFeaturesCategoricalValues {}
485impl common::Part for AnalyzeDataDescriptionFeaturesCategoricalValues {}
486
487/// Description of the numeric values of this feature.
488///
489/// This type is not used in any activity, and only used as *part* of another schema.
490///
491#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
492#[serde_with::serde_as]
493#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
494pub struct AnalyzeDataDescriptionFeaturesNumeric {
495 /// Number of numeric values for this feature in the data set.
496 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
497 pub count: Option<i64>,
498 /// Mean of the numeric values of this feature in the data set.
499 pub mean: Option<String>,
500 /// Variance of the numeric values of this feature in the data set.
501 pub variance: Option<String>,
502}
503
504impl common::NestedType for AnalyzeDataDescriptionFeaturesNumeric {}
505impl common::Part for AnalyzeDataDescriptionFeaturesNumeric {}
506
507/// Description of multiple-word text values of this feature.
508///
509/// This type is not used in any activity, and only used as *part* of another schema.
510///
511#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
512#[serde_with::serde_as]
513#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
514pub struct AnalyzeDataDescriptionFeaturesText {
515 /// Number of multiple-word text values for this feature.
516 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
517 pub count: Option<i64>,
518}
519
520impl common::NestedType for AnalyzeDataDescriptionFeaturesText {}
521impl common::Part for AnalyzeDataDescriptionFeaturesText {}
522
523/// Description of the output value or label.
524///
525/// This type is not used in any activity, and only used as *part* of another schema.
526///
527#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
528#[serde_with::serde_as]
529#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
530pub struct AnalyzeDataDescriptionOutputFeature {
531 /// Description of the output values in the data set.
532 pub numeric: Option<AnalyzeDataDescriptionOutputFeatureNumeric>,
533 /// Description of the output labels in the data set.
534 pub text: Option<Vec<AnalyzeDataDescriptionOutputFeatureText>>,
535}
536
537impl common::NestedType for AnalyzeDataDescriptionOutputFeature {}
538impl common::Part for AnalyzeDataDescriptionOutputFeature {}
539
540/// Description of the output values in the data set.
541///
542/// This type is not used in any activity, and only used as *part* of another schema.
543///
544#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
545#[serde_with::serde_as]
546#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
547pub struct AnalyzeDataDescriptionOutputFeatureNumeric {
548 /// Number of numeric output values in the data set.
549 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
550 pub count: Option<i64>,
551 /// Mean of the output values in the data set.
552 pub mean: Option<String>,
553 /// Variance of the output values in the data set.
554 pub variance: Option<String>,
555}
556
557impl common::NestedType for AnalyzeDataDescriptionOutputFeatureNumeric {}
558impl common::Part for AnalyzeDataDescriptionOutputFeatureNumeric {}
559
560/// Description of the output labels in the data set.
561///
562/// This type is not used in any activity, and only used as *part* of another schema.
563///
564#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
565#[serde_with::serde_as]
566#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
567pub struct AnalyzeDataDescriptionOutputFeatureText {
568 /// Number of times the output label occurred in the data set.
569 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
570 pub count: Option<i64>,
571 /// The output label.
572 pub value: Option<String>,
573}
574
575impl common::NestedType for AnalyzeDataDescriptionOutputFeatureText {}
576impl common::Part for AnalyzeDataDescriptionOutputFeatureText {}
577
578/// Description of the model.
579///
580/// This type is not used in any activity, and only used as *part* of another schema.
581///
582#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
583#[serde_with::serde_as]
584#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
585pub struct AnalyzeModelDescription {
586 /// An output confusion matrix. This shows an estimate for how this model will do in predictions. This is first indexed by the true class label. For each true class label, this provides a pair {predicted_label, count}, where count is the estimated number of times the model will predict the predicted label given the true label. Will not output if more then 100 classes (Categorical models only).
587 #[serde(rename = "confusionMatrix")]
588 pub confusion_matrix: Option<HashMap<String, HashMap<String, String>>>,
589 /// A list of the confusion matrix row totals.
590 #[serde(rename = "confusionMatrixRowTotals")]
591 pub confusion_matrix_row_totals: Option<HashMap<String, String>>,
592 /// Basic information about the model.
593 pub modelinfo: Option<Insert2>,
594}
595
596impl common::NestedType for AnalyzeModelDescription {}
597impl common::Part for AnalyzeModelDescription {}
598
599/// Input to the model for a prediction.
600///
601/// This type is not used in any activity, and only used as *part* of another schema.
602///
603#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
604#[serde_with::serde_as]
605#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
606pub struct InputInput {
607 /// A list of input features, these can be strings or doubles.
608 #[serde(rename = "csvInstance")]
609 pub csv_instance: Option<Vec<serde_json::Value>>,
610}
611
612impl common::NestedType for InputInput {}
613impl common::Part for InputInput {}
614
615/// Instances to train model on.
616///
617/// This type is not used in any activity, and only used as *part* of another schema.
618///
619#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
620#[serde_with::serde_as]
621#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
622pub struct InsertTrainingInstances {
623 /// The input features for this instance.
624 #[serde(rename = "csvInstance")]
625 pub csv_instance: Option<Vec<serde_json::Value>>,
626 /// The generic output value - could be regression or class label.
627 pub output: Option<String>,
628}
629
630impl common::NestedType for InsertTrainingInstances {}
631impl common::Part for InsertTrainingInstances {}
632
633/// Model metadata.
634///
635/// This type is not used in any activity, and only used as *part* of another schema.
636///
637#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
638#[serde_with::serde_as]
639#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
640pub struct Insert2ModelInfo {
641 /// Estimated accuracy of model taking utility weights into account (Categorical models only).
642 #[serde(rename = "classWeightedAccuracy")]
643 pub class_weighted_accuracy: Option<String>,
644 /// A number between 0.0 and 1.0, where 1.0 is 100% accurate. This is an estimate, based on the amount and quality of the training data, of the estimated prediction accuracy. You can use this is a guide to decide whether the results are accurate enough for your needs. This estimate will be more reliable if your real input data is similar to your training data (Categorical models only).
645 #[serde(rename = "classificationAccuracy")]
646 pub classification_accuracy: Option<String>,
647 /// An estimated mean squared error. The can be used to measure the quality of the predicted model (Regression models only).
648 #[serde(rename = "meanSquaredError")]
649 pub mean_squared_error: Option<String>,
650 /// Type of predictive model (CLASSIFICATION or REGRESSION).
651 #[serde(rename = "modelType")]
652 pub model_type: Option<String>,
653 /// Number of valid data instances used in the trained model.
654 #[serde(rename = "numberInstances")]
655 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
656 pub number_instances: Option<i64>,
657 /// Number of class labels in the trained model (Categorical models only).
658 #[serde(rename = "numberLabels")]
659 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
660 pub number_labels: Option<i64>,
661}
662
663impl common::NestedType for Insert2ModelInfo {}
664impl common::Part for Insert2ModelInfo {}
665
666/// A list of class labels with their estimated probabilities (Categorical models only).
667///
668/// This type is not used in any activity, and only used as *part* of another schema.
669///
670#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
671#[serde_with::serde_as]
672#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
673pub struct OutputOutputMulti {
674 /// The class label.
675 pub label: Option<String>,
676 /// The probability of the class label.
677 pub score: Option<String>,
678}
679
680impl common::NestedType for OutputOutputMulti {}
681impl common::Part for OutputOutputMulti {}
682
683// ###################
684// MethodBuilders ###
685// #################
686
687/// A builder providing access to all methods supported on *hostedmodel* resources.
688/// It is not used directly, but through the [`Prediction`] hub.
689///
690/// # Example
691///
692/// Instantiate a resource builder
693///
694/// ```test_harness,no_run
695/// extern crate hyper;
696/// extern crate hyper_rustls;
697/// extern crate google_prediction1d6 as prediction1d6;
698///
699/// # async fn dox() {
700/// use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
701///
702/// let secret: yup_oauth2::ApplicationSecret = Default::default();
703/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
704/// .with_native_roots()
705/// .unwrap()
706/// .https_only()
707/// .enable_http2()
708/// .build();
709///
710/// let executor = hyper_util::rt::TokioExecutor::new();
711/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
712/// secret,
713/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
714/// yup_oauth2::client::CustomHyperClientBuilder::from(
715/// hyper_util::client::legacy::Client::builder(executor).build(connector),
716/// ),
717/// ).build().await.unwrap();
718///
719/// let client = hyper_util::client::legacy::Client::builder(
720/// hyper_util::rt::TokioExecutor::new()
721/// )
722/// .build(
723/// hyper_rustls::HttpsConnectorBuilder::new()
724/// .with_native_roots()
725/// .unwrap()
726/// .https_or_http()
727/// .enable_http2()
728/// .build()
729/// );
730/// let mut hub = Prediction::new(client, auth);
731/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
732/// // like `predict(...)`
733/// // to build up your call.
734/// let rb = hub.hostedmodels();
735/// # }
736/// ```
737pub struct HostedmodelMethods<'a, C>
738where
739 C: 'a,
740{
741 hub: &'a Prediction<C>,
742}
743
744impl<'a, C> common::MethodsBuilder for HostedmodelMethods<'a, C> {}
745
746impl<'a, C> HostedmodelMethods<'a, C> {
747 /// Create a builder to help you perform the following task:
748 ///
749 /// Submit input and request an output against a hosted model.
750 ///
751 /// # Arguments
752 ///
753 /// * `request` - No description provided.
754 /// * `project` - The project associated with the model.
755 /// * `hostedModelName` - The name of a hosted model.
756 pub fn predict(
757 &self,
758 request: Input,
759 project: &str,
760 hosted_model_name: &str,
761 ) -> HostedmodelPredictCall<'a, C> {
762 HostedmodelPredictCall {
763 hub: self.hub,
764 _request: request,
765 _project: project.to_string(),
766 _hosted_model_name: hosted_model_name.to_string(),
767 _delegate: Default::default(),
768 _additional_params: Default::default(),
769 _scopes: Default::default(),
770 }
771 }
772}
773
774/// A builder providing access to all methods supported on *trainedmodel* resources.
775/// It is not used directly, but through the [`Prediction`] hub.
776///
777/// # Example
778///
779/// Instantiate a resource builder
780///
781/// ```test_harness,no_run
782/// extern crate hyper;
783/// extern crate hyper_rustls;
784/// extern crate google_prediction1d6 as prediction1d6;
785///
786/// # async fn dox() {
787/// use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
788///
789/// let secret: yup_oauth2::ApplicationSecret = Default::default();
790/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
791/// .with_native_roots()
792/// .unwrap()
793/// .https_only()
794/// .enable_http2()
795/// .build();
796///
797/// let executor = hyper_util::rt::TokioExecutor::new();
798/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
799/// secret,
800/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
801/// yup_oauth2::client::CustomHyperClientBuilder::from(
802/// hyper_util::client::legacy::Client::builder(executor).build(connector),
803/// ),
804/// ).build().await.unwrap();
805///
806/// let client = hyper_util::client::legacy::Client::builder(
807/// hyper_util::rt::TokioExecutor::new()
808/// )
809/// .build(
810/// hyper_rustls::HttpsConnectorBuilder::new()
811/// .with_native_roots()
812/// .unwrap()
813/// .https_or_http()
814/// .enable_http2()
815/// .build()
816/// );
817/// let mut hub = Prediction::new(client, auth);
818/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
819/// // like `analyze(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `predict(...)` and `update(...)`
820/// // to build up your call.
821/// let rb = hub.trainedmodels();
822/// # }
823/// ```
824pub struct TrainedmodelMethods<'a, C>
825where
826 C: 'a,
827{
828 hub: &'a Prediction<C>,
829}
830
831impl<'a, C> common::MethodsBuilder for TrainedmodelMethods<'a, C> {}
832
833impl<'a, C> TrainedmodelMethods<'a, C> {
834 /// Create a builder to help you perform the following task:
835 ///
836 /// Get analysis of the model and the data the model was trained on.
837 ///
838 /// # Arguments
839 ///
840 /// * `project` - The project associated with the model.
841 /// * `id` - The unique name for the predictive model.
842 pub fn analyze(&self, project: &str, id: &str) -> TrainedmodelAnalyzeCall<'a, C> {
843 TrainedmodelAnalyzeCall {
844 hub: self.hub,
845 _project: project.to_string(),
846 _id: id.to_string(),
847 _delegate: Default::default(),
848 _additional_params: Default::default(),
849 _scopes: Default::default(),
850 }
851 }
852
853 /// Create a builder to help you perform the following task:
854 ///
855 /// Delete a trained model.
856 ///
857 /// # Arguments
858 ///
859 /// * `project` - The project associated with the model.
860 /// * `id` - The unique name for the predictive model.
861 pub fn delete(&self, project: &str, id: &str) -> TrainedmodelDeleteCall<'a, C> {
862 TrainedmodelDeleteCall {
863 hub: self.hub,
864 _project: project.to_string(),
865 _id: id.to_string(),
866 _delegate: Default::default(),
867 _additional_params: Default::default(),
868 _scopes: Default::default(),
869 }
870 }
871
872 /// Create a builder to help you perform the following task:
873 ///
874 /// Check training status of your model.
875 ///
876 /// # Arguments
877 ///
878 /// * `project` - The project associated with the model.
879 /// * `id` - The unique name for the predictive model.
880 pub fn get(&self, project: &str, id: &str) -> TrainedmodelGetCall<'a, C> {
881 TrainedmodelGetCall {
882 hub: self.hub,
883 _project: project.to_string(),
884 _id: id.to_string(),
885 _delegate: Default::default(),
886 _additional_params: Default::default(),
887 _scopes: Default::default(),
888 }
889 }
890
891 /// Create a builder to help you perform the following task:
892 ///
893 /// Train a Prediction API model.
894 ///
895 /// # Arguments
896 ///
897 /// * `request` - No description provided.
898 /// * `project` - The project associated with the model.
899 pub fn insert(&self, request: Insert, project: &str) -> TrainedmodelInsertCall<'a, C> {
900 TrainedmodelInsertCall {
901 hub: self.hub,
902 _request: request,
903 _project: project.to_string(),
904 _delegate: Default::default(),
905 _additional_params: Default::default(),
906 _scopes: Default::default(),
907 }
908 }
909
910 /// Create a builder to help you perform the following task:
911 ///
912 /// List available models.
913 ///
914 /// # Arguments
915 ///
916 /// * `project` - The project associated with the model.
917 pub fn list(&self, project: &str) -> TrainedmodelListCall<'a, C> {
918 TrainedmodelListCall {
919 hub: self.hub,
920 _project: project.to_string(),
921 _page_token: Default::default(),
922 _max_results: Default::default(),
923 _delegate: Default::default(),
924 _additional_params: Default::default(),
925 _scopes: Default::default(),
926 }
927 }
928
929 /// Create a builder to help you perform the following task:
930 ///
931 /// Submit model id and request a prediction.
932 ///
933 /// # Arguments
934 ///
935 /// * `request` - No description provided.
936 /// * `project` - The project associated with the model.
937 /// * `id` - The unique name for the predictive model.
938 pub fn predict(
939 &self,
940 request: Input,
941 project: &str,
942 id: &str,
943 ) -> TrainedmodelPredictCall<'a, C> {
944 TrainedmodelPredictCall {
945 hub: self.hub,
946 _request: request,
947 _project: project.to_string(),
948 _id: id.to_string(),
949 _delegate: Default::default(),
950 _additional_params: Default::default(),
951 _scopes: Default::default(),
952 }
953 }
954
955 /// Create a builder to help you perform the following task:
956 ///
957 /// Add new data to a trained model.
958 ///
959 /// # Arguments
960 ///
961 /// * `request` - No description provided.
962 /// * `project` - The project associated with the model.
963 /// * `id` - The unique name for the predictive model.
964 pub fn update(
965 &self,
966 request: Update,
967 project: &str,
968 id: &str,
969 ) -> TrainedmodelUpdateCall<'a, C> {
970 TrainedmodelUpdateCall {
971 hub: self.hub,
972 _request: request,
973 _project: project.to_string(),
974 _id: id.to_string(),
975 _delegate: Default::default(),
976 _additional_params: Default::default(),
977 _scopes: Default::default(),
978 }
979 }
980}
981
982// ###################
983// CallBuilders ###
984// #################
985
986/// Submit input and request an output against a hosted model.
987///
988/// A builder for the *predict* method supported by a *hostedmodel* resource.
989/// It is not used directly, but through a [`HostedmodelMethods`] instance.
990///
991/// # Example
992///
993/// Instantiate a resource method builder
994///
995/// ```test_harness,no_run
996/// # extern crate hyper;
997/// # extern crate hyper_rustls;
998/// # extern crate google_prediction1d6 as prediction1d6;
999/// use prediction1d6::api::Input;
1000/// # async fn dox() {
1001/// # use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1002///
1003/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1004/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1005/// # .with_native_roots()
1006/// # .unwrap()
1007/// # .https_only()
1008/// # .enable_http2()
1009/// # .build();
1010///
1011/// # let executor = hyper_util::rt::TokioExecutor::new();
1012/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1013/// # secret,
1014/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1015/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1016/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1017/// # ),
1018/// # ).build().await.unwrap();
1019///
1020/// # let client = hyper_util::client::legacy::Client::builder(
1021/// # hyper_util::rt::TokioExecutor::new()
1022/// # )
1023/// # .build(
1024/// # hyper_rustls::HttpsConnectorBuilder::new()
1025/// # .with_native_roots()
1026/// # .unwrap()
1027/// # .https_or_http()
1028/// # .enable_http2()
1029/// # .build()
1030/// # );
1031/// # let mut hub = Prediction::new(client, auth);
1032/// // As the method needs a request, you would usually fill it with the desired information
1033/// // into the respective structure. Some of the parts shown here might not be applicable !
1034/// // Values shown here are possibly random and not representative !
1035/// let mut req = Input::default();
1036///
1037/// // You can configure optional parameters by calling the respective setters at will, and
1038/// // execute the final call using `doit()`.
1039/// // Values shown here are possibly random and not representative !
1040/// let result = hub.hostedmodels().predict(req, "project", "hostedModelName")
1041/// .doit().await;
1042/// # }
1043/// ```
1044pub struct HostedmodelPredictCall<'a, C>
1045where
1046 C: 'a,
1047{
1048 hub: &'a Prediction<C>,
1049 _request: Input,
1050 _project: String,
1051 _hosted_model_name: String,
1052 _delegate: Option<&'a mut dyn common::Delegate>,
1053 _additional_params: HashMap<String, String>,
1054 _scopes: BTreeSet<String>,
1055}
1056
1057impl<'a, C> common::CallBuilder for HostedmodelPredictCall<'a, C> {}
1058
1059impl<'a, C> HostedmodelPredictCall<'a, C>
1060where
1061 C: common::Connector,
1062{
1063 /// Perform the operation you have build so far.
1064 pub async fn doit(mut self) -> common::Result<(common::Response, Output)> {
1065 use std::borrow::Cow;
1066 use std::io::{Read, Seek};
1067
1068 use common::{url::Params, ToParts};
1069 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1070
1071 let mut dd = common::DefaultDelegate;
1072 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1073 dlg.begin(common::MethodInfo {
1074 id: "prediction.hostedmodels.predict",
1075 http_method: hyper::Method::POST,
1076 });
1077
1078 for &field in ["alt", "project", "hostedModelName"].iter() {
1079 if self._additional_params.contains_key(field) {
1080 dlg.finished(false);
1081 return Err(common::Error::FieldClash(field));
1082 }
1083 }
1084
1085 let mut params = Params::with_capacity(5 + self._additional_params.len());
1086 params.push("project", self._project);
1087 params.push("hostedModelName", self._hosted_model_name);
1088
1089 params.extend(self._additional_params.iter());
1090
1091 params.push("alt", "json");
1092 let mut url =
1093 self.hub._base_url.clone() + "{project}/hostedmodels/{hostedModelName}/predict";
1094 if self._scopes.is_empty() {
1095 self._scopes
1096 .insert(Scope::CloudPlatform.as_ref().to_string());
1097 }
1098
1099 #[allow(clippy::single_element_loop)]
1100 for &(find_this, param_name) in [
1101 ("{project}", "project"),
1102 ("{hostedModelName}", "hostedModelName"),
1103 ]
1104 .iter()
1105 {
1106 url = params.uri_replacement(url, param_name, find_this, false);
1107 }
1108 {
1109 let to_remove = ["hostedModelName", "project"];
1110 params.remove_params(&to_remove);
1111 }
1112
1113 let url = params.parse_with_url(&url);
1114
1115 let mut json_mime_type = mime::APPLICATION_JSON;
1116 let mut request_value_reader = {
1117 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1118 common::remove_json_null_values(&mut value);
1119 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1120 serde_json::to_writer(&mut dst, &value).unwrap();
1121 dst
1122 };
1123 let request_size = request_value_reader
1124 .seek(std::io::SeekFrom::End(0))
1125 .unwrap();
1126 request_value_reader
1127 .seek(std::io::SeekFrom::Start(0))
1128 .unwrap();
1129
1130 loop {
1131 let token = match self
1132 .hub
1133 .auth
1134 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1135 .await
1136 {
1137 Ok(token) => token,
1138 Err(e) => match dlg.token(e) {
1139 Ok(token) => token,
1140 Err(e) => {
1141 dlg.finished(false);
1142 return Err(common::Error::MissingToken(e));
1143 }
1144 },
1145 };
1146 request_value_reader
1147 .seek(std::io::SeekFrom::Start(0))
1148 .unwrap();
1149 let mut req_result = {
1150 let client = &self.hub.client;
1151 dlg.pre_request();
1152 let mut req_builder = hyper::Request::builder()
1153 .method(hyper::Method::POST)
1154 .uri(url.as_str())
1155 .header(USER_AGENT, self.hub._user_agent.clone());
1156
1157 if let Some(token) = token.as_ref() {
1158 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1159 }
1160
1161 let request = req_builder
1162 .header(CONTENT_TYPE, json_mime_type.to_string())
1163 .header(CONTENT_LENGTH, request_size as u64)
1164 .body(common::to_body(
1165 request_value_reader.get_ref().clone().into(),
1166 ));
1167
1168 client.request(request.unwrap()).await
1169 };
1170
1171 match req_result {
1172 Err(err) => {
1173 if let common::Retry::After(d) = dlg.http_error(&err) {
1174 sleep(d).await;
1175 continue;
1176 }
1177 dlg.finished(false);
1178 return Err(common::Error::HttpError(err));
1179 }
1180 Ok(res) => {
1181 let (mut parts, body) = res.into_parts();
1182 let mut body = common::Body::new(body);
1183 if !parts.status.is_success() {
1184 let bytes = common::to_bytes(body).await.unwrap_or_default();
1185 let error = serde_json::from_str(&common::to_string(&bytes));
1186 let response = common::to_response(parts, bytes.into());
1187
1188 if let common::Retry::After(d) =
1189 dlg.http_failure(&response, error.as_ref().ok())
1190 {
1191 sleep(d).await;
1192 continue;
1193 }
1194
1195 dlg.finished(false);
1196
1197 return Err(match error {
1198 Ok(value) => common::Error::BadRequest(value),
1199 _ => common::Error::Failure(response),
1200 });
1201 }
1202 let response = {
1203 let bytes = common::to_bytes(body).await.unwrap_or_default();
1204 let encoded = common::to_string(&bytes);
1205 match serde_json::from_str(&encoded) {
1206 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1207 Err(error) => {
1208 dlg.response_json_decode_error(&encoded, &error);
1209 return Err(common::Error::JsonDecodeError(
1210 encoded.to_string(),
1211 error,
1212 ));
1213 }
1214 }
1215 };
1216
1217 dlg.finished(true);
1218 return Ok(response);
1219 }
1220 }
1221 }
1222 }
1223
1224 ///
1225 /// Sets the *request* property to the given value.
1226 ///
1227 /// Even though the property as already been set when instantiating this call,
1228 /// we provide this method for API completeness.
1229 pub fn request(mut self, new_value: Input) -> HostedmodelPredictCall<'a, C> {
1230 self._request = new_value;
1231 self
1232 }
1233 /// The project associated with the model.
1234 ///
1235 /// Sets the *project* path property to the given value.
1236 ///
1237 /// Even though the property as already been set when instantiating this call,
1238 /// we provide this method for API completeness.
1239 pub fn project(mut self, new_value: &str) -> HostedmodelPredictCall<'a, C> {
1240 self._project = new_value.to_string();
1241 self
1242 }
1243 /// The name of a hosted model.
1244 ///
1245 /// Sets the *hosted model name* path property to the given value.
1246 ///
1247 /// Even though the property as already been set when instantiating this call,
1248 /// we provide this method for API completeness.
1249 pub fn hosted_model_name(mut self, new_value: &str) -> HostedmodelPredictCall<'a, C> {
1250 self._hosted_model_name = new_value.to_string();
1251 self
1252 }
1253 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1254 /// while executing the actual API request.
1255 ///
1256 /// ````text
1257 /// It should be used to handle progress information, and to implement a certain level of resilience.
1258 /// ````
1259 ///
1260 /// Sets the *delegate* property to the given value.
1261 pub fn delegate(
1262 mut self,
1263 new_value: &'a mut dyn common::Delegate,
1264 ) -> HostedmodelPredictCall<'a, C> {
1265 self._delegate = Some(new_value);
1266 self
1267 }
1268
1269 /// Set any additional parameter of the query string used in the request.
1270 /// It should be used to set parameters which are not yet available through their own
1271 /// setters.
1272 ///
1273 /// Please note that this method must not be used to set any of the known parameters
1274 /// which have their own setter method. If done anyway, the request will fail.
1275 ///
1276 /// # Additional Parameters
1277 ///
1278 /// * *alt* (query-string) - Data format for the response.
1279 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1280 /// * *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.
1281 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1282 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1283 /// * *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. Overrides userIp if both are provided.
1284 /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
1285 pub fn param<T>(mut self, name: T, value: T) -> HostedmodelPredictCall<'a, C>
1286 where
1287 T: AsRef<str>,
1288 {
1289 self._additional_params
1290 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1291 self
1292 }
1293
1294 /// Identifies the authorization scope for the method you are building.
1295 ///
1296 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1297 /// [`Scope::CloudPlatform`].
1298 ///
1299 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1300 /// tokens for more than one scope.
1301 ///
1302 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1303 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1304 /// sufficient, a read-write scope will do as well.
1305 pub fn add_scope<St>(mut self, scope: St) -> HostedmodelPredictCall<'a, C>
1306 where
1307 St: AsRef<str>,
1308 {
1309 self._scopes.insert(String::from(scope.as_ref()));
1310 self
1311 }
1312 /// Identifies the authorization scope(s) for the method you are building.
1313 ///
1314 /// See [`Self::add_scope()`] for details.
1315 pub fn add_scopes<I, St>(mut self, scopes: I) -> HostedmodelPredictCall<'a, C>
1316 where
1317 I: IntoIterator<Item = St>,
1318 St: AsRef<str>,
1319 {
1320 self._scopes
1321 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1322 self
1323 }
1324
1325 /// Removes all scopes, and no default scope will be used either.
1326 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1327 /// for details).
1328 pub fn clear_scopes(mut self) -> HostedmodelPredictCall<'a, C> {
1329 self._scopes.clear();
1330 self
1331 }
1332}
1333
1334/// Get analysis of the model and the data the model was trained on.
1335///
1336/// A builder for the *analyze* method supported by a *trainedmodel* resource.
1337/// It is not used directly, but through a [`TrainedmodelMethods`] instance.
1338///
1339/// # Example
1340///
1341/// Instantiate a resource method builder
1342///
1343/// ```test_harness,no_run
1344/// # extern crate hyper;
1345/// # extern crate hyper_rustls;
1346/// # extern crate google_prediction1d6 as prediction1d6;
1347/// # async fn dox() {
1348/// # use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1349///
1350/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1351/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1352/// # .with_native_roots()
1353/// # .unwrap()
1354/// # .https_only()
1355/// # .enable_http2()
1356/// # .build();
1357///
1358/// # let executor = hyper_util::rt::TokioExecutor::new();
1359/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1360/// # secret,
1361/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1362/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1363/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1364/// # ),
1365/// # ).build().await.unwrap();
1366///
1367/// # let client = hyper_util::client::legacy::Client::builder(
1368/// # hyper_util::rt::TokioExecutor::new()
1369/// # )
1370/// # .build(
1371/// # hyper_rustls::HttpsConnectorBuilder::new()
1372/// # .with_native_roots()
1373/// # .unwrap()
1374/// # .https_or_http()
1375/// # .enable_http2()
1376/// # .build()
1377/// # );
1378/// # let mut hub = Prediction::new(client, auth);
1379/// // You can configure optional parameters by calling the respective setters at will, and
1380/// // execute the final call using `doit()`.
1381/// // Values shown here are possibly random and not representative !
1382/// let result = hub.trainedmodels().analyze("project", "id")
1383/// .doit().await;
1384/// # }
1385/// ```
1386pub struct TrainedmodelAnalyzeCall<'a, C>
1387where
1388 C: 'a,
1389{
1390 hub: &'a Prediction<C>,
1391 _project: String,
1392 _id: String,
1393 _delegate: Option<&'a mut dyn common::Delegate>,
1394 _additional_params: HashMap<String, String>,
1395 _scopes: BTreeSet<String>,
1396}
1397
1398impl<'a, C> common::CallBuilder for TrainedmodelAnalyzeCall<'a, C> {}
1399
1400impl<'a, C> TrainedmodelAnalyzeCall<'a, C>
1401where
1402 C: common::Connector,
1403{
1404 /// Perform the operation you have build so far.
1405 pub async fn doit(mut self) -> common::Result<(common::Response, Analyze)> {
1406 use std::borrow::Cow;
1407 use std::io::{Read, Seek};
1408
1409 use common::{url::Params, ToParts};
1410 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1411
1412 let mut dd = common::DefaultDelegate;
1413 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1414 dlg.begin(common::MethodInfo {
1415 id: "prediction.trainedmodels.analyze",
1416 http_method: hyper::Method::GET,
1417 });
1418
1419 for &field in ["alt", "project", "id"].iter() {
1420 if self._additional_params.contains_key(field) {
1421 dlg.finished(false);
1422 return Err(common::Error::FieldClash(field));
1423 }
1424 }
1425
1426 let mut params = Params::with_capacity(4 + self._additional_params.len());
1427 params.push("project", self._project);
1428 params.push("id", self._id);
1429
1430 params.extend(self._additional_params.iter());
1431
1432 params.push("alt", "json");
1433 let mut url = self.hub._base_url.clone() + "{project}/trainedmodels/{id}/analyze";
1434 if self._scopes.is_empty() {
1435 self._scopes
1436 .insert(Scope::CloudPlatform.as_ref().to_string());
1437 }
1438
1439 #[allow(clippy::single_element_loop)]
1440 for &(find_this, param_name) in [("{project}", "project"), ("{id}", "id")].iter() {
1441 url = params.uri_replacement(url, param_name, find_this, false);
1442 }
1443 {
1444 let to_remove = ["id", "project"];
1445 params.remove_params(&to_remove);
1446 }
1447
1448 let url = params.parse_with_url(&url);
1449
1450 loop {
1451 let token = match self
1452 .hub
1453 .auth
1454 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1455 .await
1456 {
1457 Ok(token) => token,
1458 Err(e) => match dlg.token(e) {
1459 Ok(token) => token,
1460 Err(e) => {
1461 dlg.finished(false);
1462 return Err(common::Error::MissingToken(e));
1463 }
1464 },
1465 };
1466 let mut req_result = {
1467 let client = &self.hub.client;
1468 dlg.pre_request();
1469 let mut req_builder = hyper::Request::builder()
1470 .method(hyper::Method::GET)
1471 .uri(url.as_str())
1472 .header(USER_AGENT, self.hub._user_agent.clone());
1473
1474 if let Some(token) = token.as_ref() {
1475 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1476 }
1477
1478 let request = req_builder
1479 .header(CONTENT_LENGTH, 0_u64)
1480 .body(common::to_body::<String>(None));
1481
1482 client.request(request.unwrap()).await
1483 };
1484
1485 match req_result {
1486 Err(err) => {
1487 if let common::Retry::After(d) = dlg.http_error(&err) {
1488 sleep(d).await;
1489 continue;
1490 }
1491 dlg.finished(false);
1492 return Err(common::Error::HttpError(err));
1493 }
1494 Ok(res) => {
1495 let (mut parts, body) = res.into_parts();
1496 let mut body = common::Body::new(body);
1497 if !parts.status.is_success() {
1498 let bytes = common::to_bytes(body).await.unwrap_or_default();
1499 let error = serde_json::from_str(&common::to_string(&bytes));
1500 let response = common::to_response(parts, bytes.into());
1501
1502 if let common::Retry::After(d) =
1503 dlg.http_failure(&response, error.as_ref().ok())
1504 {
1505 sleep(d).await;
1506 continue;
1507 }
1508
1509 dlg.finished(false);
1510
1511 return Err(match error {
1512 Ok(value) => common::Error::BadRequest(value),
1513 _ => common::Error::Failure(response),
1514 });
1515 }
1516 let response = {
1517 let bytes = common::to_bytes(body).await.unwrap_or_default();
1518 let encoded = common::to_string(&bytes);
1519 match serde_json::from_str(&encoded) {
1520 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1521 Err(error) => {
1522 dlg.response_json_decode_error(&encoded, &error);
1523 return Err(common::Error::JsonDecodeError(
1524 encoded.to_string(),
1525 error,
1526 ));
1527 }
1528 }
1529 };
1530
1531 dlg.finished(true);
1532 return Ok(response);
1533 }
1534 }
1535 }
1536 }
1537
1538 /// The project associated with the model.
1539 ///
1540 /// Sets the *project* path property to the given value.
1541 ///
1542 /// Even though the property as already been set when instantiating this call,
1543 /// we provide this method for API completeness.
1544 pub fn project(mut self, new_value: &str) -> TrainedmodelAnalyzeCall<'a, C> {
1545 self._project = new_value.to_string();
1546 self
1547 }
1548 /// The unique name for the predictive model.
1549 ///
1550 /// Sets the *id* path property to the given value.
1551 ///
1552 /// Even though the property as already been set when instantiating this call,
1553 /// we provide this method for API completeness.
1554 pub fn id(mut self, new_value: &str) -> TrainedmodelAnalyzeCall<'a, C> {
1555 self._id = new_value.to_string();
1556 self
1557 }
1558 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1559 /// while executing the actual API request.
1560 ///
1561 /// ````text
1562 /// It should be used to handle progress information, and to implement a certain level of resilience.
1563 /// ````
1564 ///
1565 /// Sets the *delegate* property to the given value.
1566 pub fn delegate(
1567 mut self,
1568 new_value: &'a mut dyn common::Delegate,
1569 ) -> TrainedmodelAnalyzeCall<'a, C> {
1570 self._delegate = Some(new_value);
1571 self
1572 }
1573
1574 /// Set any additional parameter of the query string used in the request.
1575 /// It should be used to set parameters which are not yet available through their own
1576 /// setters.
1577 ///
1578 /// Please note that this method must not be used to set any of the known parameters
1579 /// which have their own setter method. If done anyway, the request will fail.
1580 ///
1581 /// # Additional Parameters
1582 ///
1583 /// * *alt* (query-string) - Data format for the response.
1584 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1585 /// * *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.
1586 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1587 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1588 /// * *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. Overrides userIp if both are provided.
1589 /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
1590 pub fn param<T>(mut self, name: T, value: T) -> TrainedmodelAnalyzeCall<'a, C>
1591 where
1592 T: AsRef<str>,
1593 {
1594 self._additional_params
1595 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1596 self
1597 }
1598
1599 /// Identifies the authorization scope for the method you are building.
1600 ///
1601 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1602 /// [`Scope::CloudPlatform`].
1603 ///
1604 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1605 /// tokens for more than one scope.
1606 ///
1607 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1608 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1609 /// sufficient, a read-write scope will do as well.
1610 pub fn add_scope<St>(mut self, scope: St) -> TrainedmodelAnalyzeCall<'a, C>
1611 where
1612 St: AsRef<str>,
1613 {
1614 self._scopes.insert(String::from(scope.as_ref()));
1615 self
1616 }
1617 /// Identifies the authorization scope(s) for the method you are building.
1618 ///
1619 /// See [`Self::add_scope()`] for details.
1620 pub fn add_scopes<I, St>(mut self, scopes: I) -> TrainedmodelAnalyzeCall<'a, C>
1621 where
1622 I: IntoIterator<Item = St>,
1623 St: AsRef<str>,
1624 {
1625 self._scopes
1626 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1627 self
1628 }
1629
1630 /// Removes all scopes, and no default scope will be used either.
1631 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1632 /// for details).
1633 pub fn clear_scopes(mut self) -> TrainedmodelAnalyzeCall<'a, C> {
1634 self._scopes.clear();
1635 self
1636 }
1637}
1638
1639/// Delete a trained model.
1640///
1641/// A builder for the *delete* method supported by a *trainedmodel* resource.
1642/// It is not used directly, but through a [`TrainedmodelMethods`] instance.
1643///
1644/// # Example
1645///
1646/// Instantiate a resource method builder
1647///
1648/// ```test_harness,no_run
1649/// # extern crate hyper;
1650/// # extern crate hyper_rustls;
1651/// # extern crate google_prediction1d6 as prediction1d6;
1652/// # async fn dox() {
1653/// # use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1654///
1655/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1656/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1657/// # .with_native_roots()
1658/// # .unwrap()
1659/// # .https_only()
1660/// # .enable_http2()
1661/// # .build();
1662///
1663/// # let executor = hyper_util::rt::TokioExecutor::new();
1664/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1665/// # secret,
1666/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1667/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1668/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1669/// # ),
1670/// # ).build().await.unwrap();
1671///
1672/// # let client = hyper_util::client::legacy::Client::builder(
1673/// # hyper_util::rt::TokioExecutor::new()
1674/// # )
1675/// # .build(
1676/// # hyper_rustls::HttpsConnectorBuilder::new()
1677/// # .with_native_roots()
1678/// # .unwrap()
1679/// # .https_or_http()
1680/// # .enable_http2()
1681/// # .build()
1682/// # );
1683/// # let mut hub = Prediction::new(client, auth);
1684/// // You can configure optional parameters by calling the respective setters at will, and
1685/// // execute the final call using `doit()`.
1686/// // Values shown here are possibly random and not representative !
1687/// let result = hub.trainedmodels().delete("project", "id")
1688/// .doit().await;
1689/// # }
1690/// ```
1691pub struct TrainedmodelDeleteCall<'a, C>
1692where
1693 C: 'a,
1694{
1695 hub: &'a Prediction<C>,
1696 _project: String,
1697 _id: String,
1698 _delegate: Option<&'a mut dyn common::Delegate>,
1699 _additional_params: HashMap<String, String>,
1700 _scopes: BTreeSet<String>,
1701}
1702
1703impl<'a, C> common::CallBuilder for TrainedmodelDeleteCall<'a, C> {}
1704
1705impl<'a, C> TrainedmodelDeleteCall<'a, C>
1706where
1707 C: common::Connector,
1708{
1709 /// Perform the operation you have build so far.
1710 pub async fn doit(mut self) -> common::Result<common::Response> {
1711 use std::borrow::Cow;
1712 use std::io::{Read, Seek};
1713
1714 use common::{url::Params, ToParts};
1715 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1716
1717 let mut dd = common::DefaultDelegate;
1718 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1719 dlg.begin(common::MethodInfo {
1720 id: "prediction.trainedmodels.delete",
1721 http_method: hyper::Method::DELETE,
1722 });
1723
1724 for &field in ["project", "id"].iter() {
1725 if self._additional_params.contains_key(field) {
1726 dlg.finished(false);
1727 return Err(common::Error::FieldClash(field));
1728 }
1729 }
1730
1731 let mut params = Params::with_capacity(3 + self._additional_params.len());
1732 params.push("project", self._project);
1733 params.push("id", self._id);
1734
1735 params.extend(self._additional_params.iter());
1736
1737 let mut url = self.hub._base_url.clone() + "{project}/trainedmodels/{id}";
1738 if self._scopes.is_empty() {
1739 self._scopes
1740 .insert(Scope::CloudPlatform.as_ref().to_string());
1741 }
1742
1743 #[allow(clippy::single_element_loop)]
1744 for &(find_this, param_name) in [("{project}", "project"), ("{id}", "id")].iter() {
1745 url = params.uri_replacement(url, param_name, find_this, false);
1746 }
1747 {
1748 let to_remove = ["id", "project"];
1749 params.remove_params(&to_remove);
1750 }
1751
1752 let url = params.parse_with_url(&url);
1753
1754 loop {
1755 let token = match self
1756 .hub
1757 .auth
1758 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1759 .await
1760 {
1761 Ok(token) => token,
1762 Err(e) => match dlg.token(e) {
1763 Ok(token) => token,
1764 Err(e) => {
1765 dlg.finished(false);
1766 return Err(common::Error::MissingToken(e));
1767 }
1768 },
1769 };
1770 let mut req_result = {
1771 let client = &self.hub.client;
1772 dlg.pre_request();
1773 let mut req_builder = hyper::Request::builder()
1774 .method(hyper::Method::DELETE)
1775 .uri(url.as_str())
1776 .header(USER_AGENT, self.hub._user_agent.clone());
1777
1778 if let Some(token) = token.as_ref() {
1779 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1780 }
1781
1782 let request = req_builder
1783 .header(CONTENT_LENGTH, 0_u64)
1784 .body(common::to_body::<String>(None));
1785
1786 client.request(request.unwrap()).await
1787 };
1788
1789 match req_result {
1790 Err(err) => {
1791 if let common::Retry::After(d) = dlg.http_error(&err) {
1792 sleep(d).await;
1793 continue;
1794 }
1795 dlg.finished(false);
1796 return Err(common::Error::HttpError(err));
1797 }
1798 Ok(res) => {
1799 let (mut parts, body) = res.into_parts();
1800 let mut body = common::Body::new(body);
1801 if !parts.status.is_success() {
1802 let bytes = common::to_bytes(body).await.unwrap_or_default();
1803 let error = serde_json::from_str(&common::to_string(&bytes));
1804 let response = common::to_response(parts, bytes.into());
1805
1806 if let common::Retry::After(d) =
1807 dlg.http_failure(&response, error.as_ref().ok())
1808 {
1809 sleep(d).await;
1810 continue;
1811 }
1812
1813 dlg.finished(false);
1814
1815 return Err(match error {
1816 Ok(value) => common::Error::BadRequest(value),
1817 _ => common::Error::Failure(response),
1818 });
1819 }
1820 let response = common::Response::from_parts(parts, body);
1821
1822 dlg.finished(true);
1823 return Ok(response);
1824 }
1825 }
1826 }
1827 }
1828
1829 /// The project associated with the model.
1830 ///
1831 /// Sets the *project* path property to the given value.
1832 ///
1833 /// Even though the property as already been set when instantiating this call,
1834 /// we provide this method for API completeness.
1835 pub fn project(mut self, new_value: &str) -> TrainedmodelDeleteCall<'a, C> {
1836 self._project = new_value.to_string();
1837 self
1838 }
1839 /// The unique name for the predictive model.
1840 ///
1841 /// Sets the *id* path property to the given value.
1842 ///
1843 /// Even though the property as already been set when instantiating this call,
1844 /// we provide this method for API completeness.
1845 pub fn id(mut self, new_value: &str) -> TrainedmodelDeleteCall<'a, C> {
1846 self._id = new_value.to_string();
1847 self
1848 }
1849 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1850 /// while executing the actual API request.
1851 ///
1852 /// ````text
1853 /// It should be used to handle progress information, and to implement a certain level of resilience.
1854 /// ````
1855 ///
1856 /// Sets the *delegate* property to the given value.
1857 pub fn delegate(
1858 mut self,
1859 new_value: &'a mut dyn common::Delegate,
1860 ) -> TrainedmodelDeleteCall<'a, C> {
1861 self._delegate = Some(new_value);
1862 self
1863 }
1864
1865 /// Set any additional parameter of the query string used in the request.
1866 /// It should be used to set parameters which are not yet available through their own
1867 /// setters.
1868 ///
1869 /// Please note that this method must not be used to set any of the known parameters
1870 /// which have their own setter method. If done anyway, the request will fail.
1871 ///
1872 /// # Additional Parameters
1873 ///
1874 /// * *alt* (query-string) - Data format for the response.
1875 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1876 /// * *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.
1877 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1878 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1879 /// * *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. Overrides userIp if both are provided.
1880 /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
1881 pub fn param<T>(mut self, name: T, value: T) -> TrainedmodelDeleteCall<'a, C>
1882 where
1883 T: AsRef<str>,
1884 {
1885 self._additional_params
1886 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1887 self
1888 }
1889
1890 /// Identifies the authorization scope for the method you are building.
1891 ///
1892 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1893 /// [`Scope::CloudPlatform`].
1894 ///
1895 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1896 /// tokens for more than one scope.
1897 ///
1898 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1899 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1900 /// sufficient, a read-write scope will do as well.
1901 pub fn add_scope<St>(mut self, scope: St) -> TrainedmodelDeleteCall<'a, C>
1902 where
1903 St: AsRef<str>,
1904 {
1905 self._scopes.insert(String::from(scope.as_ref()));
1906 self
1907 }
1908 /// Identifies the authorization scope(s) for the method you are building.
1909 ///
1910 /// See [`Self::add_scope()`] for details.
1911 pub fn add_scopes<I, St>(mut self, scopes: I) -> TrainedmodelDeleteCall<'a, C>
1912 where
1913 I: IntoIterator<Item = St>,
1914 St: AsRef<str>,
1915 {
1916 self._scopes
1917 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1918 self
1919 }
1920
1921 /// Removes all scopes, and no default scope will be used either.
1922 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1923 /// for details).
1924 pub fn clear_scopes(mut self) -> TrainedmodelDeleteCall<'a, C> {
1925 self._scopes.clear();
1926 self
1927 }
1928}
1929
1930/// Check training status of your model.
1931///
1932/// A builder for the *get* method supported by a *trainedmodel* resource.
1933/// It is not used directly, but through a [`TrainedmodelMethods`] instance.
1934///
1935/// # Example
1936///
1937/// Instantiate a resource method builder
1938///
1939/// ```test_harness,no_run
1940/// # extern crate hyper;
1941/// # extern crate hyper_rustls;
1942/// # extern crate google_prediction1d6 as prediction1d6;
1943/// # async fn dox() {
1944/// # use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1945///
1946/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1947/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1948/// # .with_native_roots()
1949/// # .unwrap()
1950/// # .https_only()
1951/// # .enable_http2()
1952/// # .build();
1953///
1954/// # let executor = hyper_util::rt::TokioExecutor::new();
1955/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1956/// # secret,
1957/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1958/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1959/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1960/// # ),
1961/// # ).build().await.unwrap();
1962///
1963/// # let client = hyper_util::client::legacy::Client::builder(
1964/// # hyper_util::rt::TokioExecutor::new()
1965/// # )
1966/// # .build(
1967/// # hyper_rustls::HttpsConnectorBuilder::new()
1968/// # .with_native_roots()
1969/// # .unwrap()
1970/// # .https_or_http()
1971/// # .enable_http2()
1972/// # .build()
1973/// # );
1974/// # let mut hub = Prediction::new(client, auth);
1975/// // You can configure optional parameters by calling the respective setters at will, and
1976/// // execute the final call using `doit()`.
1977/// // Values shown here are possibly random and not representative !
1978/// let result = hub.trainedmodels().get("project", "id")
1979/// .doit().await;
1980/// # }
1981/// ```
1982pub struct TrainedmodelGetCall<'a, C>
1983where
1984 C: 'a,
1985{
1986 hub: &'a Prediction<C>,
1987 _project: String,
1988 _id: String,
1989 _delegate: Option<&'a mut dyn common::Delegate>,
1990 _additional_params: HashMap<String, String>,
1991 _scopes: BTreeSet<String>,
1992}
1993
1994impl<'a, C> common::CallBuilder for TrainedmodelGetCall<'a, C> {}
1995
1996impl<'a, C> TrainedmodelGetCall<'a, C>
1997where
1998 C: common::Connector,
1999{
2000 /// Perform the operation you have build so far.
2001 pub async fn doit(mut self) -> common::Result<(common::Response, Insert2)> {
2002 use std::borrow::Cow;
2003 use std::io::{Read, Seek};
2004
2005 use common::{url::Params, ToParts};
2006 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2007
2008 let mut dd = common::DefaultDelegate;
2009 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2010 dlg.begin(common::MethodInfo {
2011 id: "prediction.trainedmodels.get",
2012 http_method: hyper::Method::GET,
2013 });
2014
2015 for &field in ["alt", "project", "id"].iter() {
2016 if self._additional_params.contains_key(field) {
2017 dlg.finished(false);
2018 return Err(common::Error::FieldClash(field));
2019 }
2020 }
2021
2022 let mut params = Params::with_capacity(4 + self._additional_params.len());
2023 params.push("project", self._project);
2024 params.push("id", self._id);
2025
2026 params.extend(self._additional_params.iter());
2027
2028 params.push("alt", "json");
2029 let mut url = self.hub._base_url.clone() + "{project}/trainedmodels/{id}";
2030 if self._scopes.is_empty() {
2031 self._scopes
2032 .insert(Scope::CloudPlatform.as_ref().to_string());
2033 }
2034
2035 #[allow(clippy::single_element_loop)]
2036 for &(find_this, param_name) in [("{project}", "project"), ("{id}", "id")].iter() {
2037 url = params.uri_replacement(url, param_name, find_this, false);
2038 }
2039 {
2040 let to_remove = ["id", "project"];
2041 params.remove_params(&to_remove);
2042 }
2043
2044 let url = params.parse_with_url(&url);
2045
2046 loop {
2047 let token = match self
2048 .hub
2049 .auth
2050 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2051 .await
2052 {
2053 Ok(token) => token,
2054 Err(e) => match dlg.token(e) {
2055 Ok(token) => token,
2056 Err(e) => {
2057 dlg.finished(false);
2058 return Err(common::Error::MissingToken(e));
2059 }
2060 },
2061 };
2062 let mut req_result = {
2063 let client = &self.hub.client;
2064 dlg.pre_request();
2065 let mut req_builder = hyper::Request::builder()
2066 .method(hyper::Method::GET)
2067 .uri(url.as_str())
2068 .header(USER_AGENT, self.hub._user_agent.clone());
2069
2070 if let Some(token) = token.as_ref() {
2071 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2072 }
2073
2074 let request = req_builder
2075 .header(CONTENT_LENGTH, 0_u64)
2076 .body(common::to_body::<String>(None));
2077
2078 client.request(request.unwrap()).await
2079 };
2080
2081 match req_result {
2082 Err(err) => {
2083 if let common::Retry::After(d) = dlg.http_error(&err) {
2084 sleep(d).await;
2085 continue;
2086 }
2087 dlg.finished(false);
2088 return Err(common::Error::HttpError(err));
2089 }
2090 Ok(res) => {
2091 let (mut parts, body) = res.into_parts();
2092 let mut body = common::Body::new(body);
2093 if !parts.status.is_success() {
2094 let bytes = common::to_bytes(body).await.unwrap_or_default();
2095 let error = serde_json::from_str(&common::to_string(&bytes));
2096 let response = common::to_response(parts, bytes.into());
2097
2098 if let common::Retry::After(d) =
2099 dlg.http_failure(&response, error.as_ref().ok())
2100 {
2101 sleep(d).await;
2102 continue;
2103 }
2104
2105 dlg.finished(false);
2106
2107 return Err(match error {
2108 Ok(value) => common::Error::BadRequest(value),
2109 _ => common::Error::Failure(response),
2110 });
2111 }
2112 let response = {
2113 let bytes = common::to_bytes(body).await.unwrap_or_default();
2114 let encoded = common::to_string(&bytes);
2115 match serde_json::from_str(&encoded) {
2116 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2117 Err(error) => {
2118 dlg.response_json_decode_error(&encoded, &error);
2119 return Err(common::Error::JsonDecodeError(
2120 encoded.to_string(),
2121 error,
2122 ));
2123 }
2124 }
2125 };
2126
2127 dlg.finished(true);
2128 return Ok(response);
2129 }
2130 }
2131 }
2132 }
2133
2134 /// The project associated with the model.
2135 ///
2136 /// Sets the *project* path property to the given value.
2137 ///
2138 /// Even though the property as already been set when instantiating this call,
2139 /// we provide this method for API completeness.
2140 pub fn project(mut self, new_value: &str) -> TrainedmodelGetCall<'a, C> {
2141 self._project = new_value.to_string();
2142 self
2143 }
2144 /// The unique name for the predictive model.
2145 ///
2146 /// Sets the *id* path property to the given value.
2147 ///
2148 /// Even though the property as already been set when instantiating this call,
2149 /// we provide this method for API completeness.
2150 pub fn id(mut self, new_value: &str) -> TrainedmodelGetCall<'a, C> {
2151 self._id = new_value.to_string();
2152 self
2153 }
2154 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2155 /// while executing the actual API request.
2156 ///
2157 /// ````text
2158 /// It should be used to handle progress information, and to implement a certain level of resilience.
2159 /// ````
2160 ///
2161 /// Sets the *delegate* property to the given value.
2162 pub fn delegate(
2163 mut self,
2164 new_value: &'a mut dyn common::Delegate,
2165 ) -> TrainedmodelGetCall<'a, C> {
2166 self._delegate = Some(new_value);
2167 self
2168 }
2169
2170 /// Set any additional parameter of the query string used in the request.
2171 /// It should be used to set parameters which are not yet available through their own
2172 /// setters.
2173 ///
2174 /// Please note that this method must not be used to set any of the known parameters
2175 /// which have their own setter method. If done anyway, the request will fail.
2176 ///
2177 /// # Additional Parameters
2178 ///
2179 /// * *alt* (query-string) - Data format for the response.
2180 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2181 /// * *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.
2182 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2183 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2184 /// * *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. Overrides userIp if both are provided.
2185 /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
2186 pub fn param<T>(mut self, name: T, value: T) -> TrainedmodelGetCall<'a, C>
2187 where
2188 T: AsRef<str>,
2189 {
2190 self._additional_params
2191 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2192 self
2193 }
2194
2195 /// Identifies the authorization scope for the method you are building.
2196 ///
2197 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2198 /// [`Scope::CloudPlatform`].
2199 ///
2200 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2201 /// tokens for more than one scope.
2202 ///
2203 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2204 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2205 /// sufficient, a read-write scope will do as well.
2206 pub fn add_scope<St>(mut self, scope: St) -> TrainedmodelGetCall<'a, C>
2207 where
2208 St: AsRef<str>,
2209 {
2210 self._scopes.insert(String::from(scope.as_ref()));
2211 self
2212 }
2213 /// Identifies the authorization scope(s) for the method you are building.
2214 ///
2215 /// See [`Self::add_scope()`] for details.
2216 pub fn add_scopes<I, St>(mut self, scopes: I) -> TrainedmodelGetCall<'a, C>
2217 where
2218 I: IntoIterator<Item = St>,
2219 St: AsRef<str>,
2220 {
2221 self._scopes
2222 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2223 self
2224 }
2225
2226 /// Removes all scopes, and no default scope will be used either.
2227 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2228 /// for details).
2229 pub fn clear_scopes(mut self) -> TrainedmodelGetCall<'a, C> {
2230 self._scopes.clear();
2231 self
2232 }
2233}
2234
2235/// Train a Prediction API model.
2236///
2237/// A builder for the *insert* method supported by a *trainedmodel* resource.
2238/// It is not used directly, but through a [`TrainedmodelMethods`] instance.
2239///
2240/// # Example
2241///
2242/// Instantiate a resource method builder
2243///
2244/// ```test_harness,no_run
2245/// # extern crate hyper;
2246/// # extern crate hyper_rustls;
2247/// # extern crate google_prediction1d6 as prediction1d6;
2248/// use prediction1d6::api::Insert;
2249/// # async fn dox() {
2250/// # use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2251///
2252/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2253/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2254/// # .with_native_roots()
2255/// # .unwrap()
2256/// # .https_only()
2257/// # .enable_http2()
2258/// # .build();
2259///
2260/// # let executor = hyper_util::rt::TokioExecutor::new();
2261/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2262/// # secret,
2263/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2264/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2265/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2266/// # ),
2267/// # ).build().await.unwrap();
2268///
2269/// # let client = hyper_util::client::legacy::Client::builder(
2270/// # hyper_util::rt::TokioExecutor::new()
2271/// # )
2272/// # .build(
2273/// # hyper_rustls::HttpsConnectorBuilder::new()
2274/// # .with_native_roots()
2275/// # .unwrap()
2276/// # .https_or_http()
2277/// # .enable_http2()
2278/// # .build()
2279/// # );
2280/// # let mut hub = Prediction::new(client, auth);
2281/// // As the method needs a request, you would usually fill it with the desired information
2282/// // into the respective structure. Some of the parts shown here might not be applicable !
2283/// // Values shown here are possibly random and not representative !
2284/// let mut req = Insert::default();
2285///
2286/// // You can configure optional parameters by calling the respective setters at will, and
2287/// // execute the final call using `doit()`.
2288/// // Values shown here are possibly random and not representative !
2289/// let result = hub.trainedmodels().insert(req, "project")
2290/// .doit().await;
2291/// # }
2292/// ```
2293pub struct TrainedmodelInsertCall<'a, C>
2294where
2295 C: 'a,
2296{
2297 hub: &'a Prediction<C>,
2298 _request: Insert,
2299 _project: String,
2300 _delegate: Option<&'a mut dyn common::Delegate>,
2301 _additional_params: HashMap<String, String>,
2302 _scopes: BTreeSet<String>,
2303}
2304
2305impl<'a, C> common::CallBuilder for TrainedmodelInsertCall<'a, C> {}
2306
2307impl<'a, C> TrainedmodelInsertCall<'a, C>
2308where
2309 C: common::Connector,
2310{
2311 /// Perform the operation you have build so far.
2312 pub async fn doit(mut self) -> common::Result<(common::Response, Insert2)> {
2313 use std::borrow::Cow;
2314 use std::io::{Read, Seek};
2315
2316 use common::{url::Params, ToParts};
2317 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2318
2319 let mut dd = common::DefaultDelegate;
2320 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2321 dlg.begin(common::MethodInfo {
2322 id: "prediction.trainedmodels.insert",
2323 http_method: hyper::Method::POST,
2324 });
2325
2326 for &field in ["alt", "project"].iter() {
2327 if self._additional_params.contains_key(field) {
2328 dlg.finished(false);
2329 return Err(common::Error::FieldClash(field));
2330 }
2331 }
2332
2333 let mut params = Params::with_capacity(4 + self._additional_params.len());
2334 params.push("project", self._project);
2335
2336 params.extend(self._additional_params.iter());
2337
2338 params.push("alt", "json");
2339 let mut url = self.hub._base_url.clone() + "{project}/trainedmodels";
2340 if self._scopes.is_empty() {
2341 self._scopes
2342 .insert(Scope::DevstorageReadOnly.as_ref().to_string());
2343 }
2344
2345 #[allow(clippy::single_element_loop)]
2346 for &(find_this, param_name) in [("{project}", "project")].iter() {
2347 url = params.uri_replacement(url, param_name, find_this, false);
2348 }
2349 {
2350 let to_remove = ["project"];
2351 params.remove_params(&to_remove);
2352 }
2353
2354 let url = params.parse_with_url(&url);
2355
2356 let mut json_mime_type = mime::APPLICATION_JSON;
2357 let mut request_value_reader = {
2358 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2359 common::remove_json_null_values(&mut value);
2360 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2361 serde_json::to_writer(&mut dst, &value).unwrap();
2362 dst
2363 };
2364 let request_size = request_value_reader
2365 .seek(std::io::SeekFrom::End(0))
2366 .unwrap();
2367 request_value_reader
2368 .seek(std::io::SeekFrom::Start(0))
2369 .unwrap();
2370
2371 loop {
2372 let token = match self
2373 .hub
2374 .auth
2375 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2376 .await
2377 {
2378 Ok(token) => token,
2379 Err(e) => match dlg.token(e) {
2380 Ok(token) => token,
2381 Err(e) => {
2382 dlg.finished(false);
2383 return Err(common::Error::MissingToken(e));
2384 }
2385 },
2386 };
2387 request_value_reader
2388 .seek(std::io::SeekFrom::Start(0))
2389 .unwrap();
2390 let mut req_result = {
2391 let client = &self.hub.client;
2392 dlg.pre_request();
2393 let mut req_builder = hyper::Request::builder()
2394 .method(hyper::Method::POST)
2395 .uri(url.as_str())
2396 .header(USER_AGENT, self.hub._user_agent.clone());
2397
2398 if let Some(token) = token.as_ref() {
2399 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2400 }
2401
2402 let request = req_builder
2403 .header(CONTENT_TYPE, json_mime_type.to_string())
2404 .header(CONTENT_LENGTH, request_size as u64)
2405 .body(common::to_body(
2406 request_value_reader.get_ref().clone().into(),
2407 ));
2408
2409 client.request(request.unwrap()).await
2410 };
2411
2412 match req_result {
2413 Err(err) => {
2414 if let common::Retry::After(d) = dlg.http_error(&err) {
2415 sleep(d).await;
2416 continue;
2417 }
2418 dlg.finished(false);
2419 return Err(common::Error::HttpError(err));
2420 }
2421 Ok(res) => {
2422 let (mut parts, body) = res.into_parts();
2423 let mut body = common::Body::new(body);
2424 if !parts.status.is_success() {
2425 let bytes = common::to_bytes(body).await.unwrap_or_default();
2426 let error = serde_json::from_str(&common::to_string(&bytes));
2427 let response = common::to_response(parts, bytes.into());
2428
2429 if let common::Retry::After(d) =
2430 dlg.http_failure(&response, error.as_ref().ok())
2431 {
2432 sleep(d).await;
2433 continue;
2434 }
2435
2436 dlg.finished(false);
2437
2438 return Err(match error {
2439 Ok(value) => common::Error::BadRequest(value),
2440 _ => common::Error::Failure(response),
2441 });
2442 }
2443 let response = {
2444 let bytes = common::to_bytes(body).await.unwrap_or_default();
2445 let encoded = common::to_string(&bytes);
2446 match serde_json::from_str(&encoded) {
2447 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2448 Err(error) => {
2449 dlg.response_json_decode_error(&encoded, &error);
2450 return Err(common::Error::JsonDecodeError(
2451 encoded.to_string(),
2452 error,
2453 ));
2454 }
2455 }
2456 };
2457
2458 dlg.finished(true);
2459 return Ok(response);
2460 }
2461 }
2462 }
2463 }
2464
2465 ///
2466 /// Sets the *request* property to the given value.
2467 ///
2468 /// Even though the property as already been set when instantiating this call,
2469 /// we provide this method for API completeness.
2470 pub fn request(mut self, new_value: Insert) -> TrainedmodelInsertCall<'a, C> {
2471 self._request = new_value;
2472 self
2473 }
2474 /// The project associated with the model.
2475 ///
2476 /// Sets the *project* path property to the given value.
2477 ///
2478 /// Even though the property as already been set when instantiating this call,
2479 /// we provide this method for API completeness.
2480 pub fn project(mut self, new_value: &str) -> TrainedmodelInsertCall<'a, C> {
2481 self._project = new_value.to_string();
2482 self
2483 }
2484 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2485 /// while executing the actual API request.
2486 ///
2487 /// ````text
2488 /// It should be used to handle progress information, and to implement a certain level of resilience.
2489 /// ````
2490 ///
2491 /// Sets the *delegate* property to the given value.
2492 pub fn delegate(
2493 mut self,
2494 new_value: &'a mut dyn common::Delegate,
2495 ) -> TrainedmodelInsertCall<'a, C> {
2496 self._delegate = Some(new_value);
2497 self
2498 }
2499
2500 /// Set any additional parameter of the query string used in the request.
2501 /// It should be used to set parameters which are not yet available through their own
2502 /// setters.
2503 ///
2504 /// Please note that this method must not be used to set any of the known parameters
2505 /// which have their own setter method. If done anyway, the request will fail.
2506 ///
2507 /// # Additional Parameters
2508 ///
2509 /// * *alt* (query-string) - Data format for the response.
2510 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2511 /// * *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.
2512 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2513 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2514 /// * *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. Overrides userIp if both are provided.
2515 /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
2516 pub fn param<T>(mut self, name: T, value: T) -> TrainedmodelInsertCall<'a, C>
2517 where
2518 T: AsRef<str>,
2519 {
2520 self._additional_params
2521 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2522 self
2523 }
2524
2525 /// Identifies the authorization scope for the method you are building.
2526 ///
2527 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2528 /// [`Scope::DevstorageReadOnly`].
2529 ///
2530 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2531 /// tokens for more than one scope.
2532 ///
2533 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2534 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2535 /// sufficient, a read-write scope will do as well.
2536 pub fn add_scope<St>(mut self, scope: St) -> TrainedmodelInsertCall<'a, C>
2537 where
2538 St: AsRef<str>,
2539 {
2540 self._scopes.insert(String::from(scope.as_ref()));
2541 self
2542 }
2543 /// Identifies the authorization scope(s) for the method you are building.
2544 ///
2545 /// See [`Self::add_scope()`] for details.
2546 pub fn add_scopes<I, St>(mut self, scopes: I) -> TrainedmodelInsertCall<'a, C>
2547 where
2548 I: IntoIterator<Item = St>,
2549 St: AsRef<str>,
2550 {
2551 self._scopes
2552 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2553 self
2554 }
2555
2556 /// Removes all scopes, and no default scope will be used either.
2557 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2558 /// for details).
2559 pub fn clear_scopes(mut self) -> TrainedmodelInsertCall<'a, C> {
2560 self._scopes.clear();
2561 self
2562 }
2563}
2564
2565/// List available models.
2566///
2567/// A builder for the *list* method supported by a *trainedmodel* resource.
2568/// It is not used directly, but through a [`TrainedmodelMethods`] instance.
2569///
2570/// # Example
2571///
2572/// Instantiate a resource method builder
2573///
2574/// ```test_harness,no_run
2575/// # extern crate hyper;
2576/// # extern crate hyper_rustls;
2577/// # extern crate google_prediction1d6 as prediction1d6;
2578/// # async fn dox() {
2579/// # use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2580///
2581/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2582/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2583/// # .with_native_roots()
2584/// # .unwrap()
2585/// # .https_only()
2586/// # .enable_http2()
2587/// # .build();
2588///
2589/// # let executor = hyper_util::rt::TokioExecutor::new();
2590/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2591/// # secret,
2592/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2593/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2594/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2595/// # ),
2596/// # ).build().await.unwrap();
2597///
2598/// # let client = hyper_util::client::legacy::Client::builder(
2599/// # hyper_util::rt::TokioExecutor::new()
2600/// # )
2601/// # .build(
2602/// # hyper_rustls::HttpsConnectorBuilder::new()
2603/// # .with_native_roots()
2604/// # .unwrap()
2605/// # .https_or_http()
2606/// # .enable_http2()
2607/// # .build()
2608/// # );
2609/// # let mut hub = Prediction::new(client, auth);
2610/// // You can configure optional parameters by calling the respective setters at will, and
2611/// // execute the final call using `doit()`.
2612/// // Values shown here are possibly random and not representative !
2613/// let result = hub.trainedmodels().list("project")
2614/// .page_token("eos")
2615/// .max_results(97)
2616/// .doit().await;
2617/// # }
2618/// ```
2619pub struct TrainedmodelListCall<'a, C>
2620where
2621 C: 'a,
2622{
2623 hub: &'a Prediction<C>,
2624 _project: String,
2625 _page_token: Option<String>,
2626 _max_results: Option<u32>,
2627 _delegate: Option<&'a mut dyn common::Delegate>,
2628 _additional_params: HashMap<String, String>,
2629 _scopes: BTreeSet<String>,
2630}
2631
2632impl<'a, C> common::CallBuilder for TrainedmodelListCall<'a, C> {}
2633
2634impl<'a, C> TrainedmodelListCall<'a, C>
2635where
2636 C: common::Connector,
2637{
2638 /// Perform the operation you have build so far.
2639 pub async fn doit(mut self) -> common::Result<(common::Response, List)> {
2640 use std::borrow::Cow;
2641 use std::io::{Read, Seek};
2642
2643 use common::{url::Params, ToParts};
2644 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2645
2646 let mut dd = common::DefaultDelegate;
2647 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2648 dlg.begin(common::MethodInfo {
2649 id: "prediction.trainedmodels.list",
2650 http_method: hyper::Method::GET,
2651 });
2652
2653 for &field in ["alt", "project", "pageToken", "maxResults"].iter() {
2654 if self._additional_params.contains_key(field) {
2655 dlg.finished(false);
2656 return Err(common::Error::FieldClash(field));
2657 }
2658 }
2659
2660 let mut params = Params::with_capacity(5 + self._additional_params.len());
2661 params.push("project", self._project);
2662 if let Some(value) = self._page_token.as_ref() {
2663 params.push("pageToken", value);
2664 }
2665 if let Some(value) = self._max_results.as_ref() {
2666 params.push("maxResults", value.to_string());
2667 }
2668
2669 params.extend(self._additional_params.iter());
2670
2671 params.push("alt", "json");
2672 let mut url = self.hub._base_url.clone() + "{project}/trainedmodels/list";
2673 if self._scopes.is_empty() {
2674 self._scopes
2675 .insert(Scope::CloudPlatform.as_ref().to_string());
2676 }
2677
2678 #[allow(clippy::single_element_loop)]
2679 for &(find_this, param_name) in [("{project}", "project")].iter() {
2680 url = params.uri_replacement(url, param_name, find_this, false);
2681 }
2682 {
2683 let to_remove = ["project"];
2684 params.remove_params(&to_remove);
2685 }
2686
2687 let url = params.parse_with_url(&url);
2688
2689 loop {
2690 let token = match self
2691 .hub
2692 .auth
2693 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2694 .await
2695 {
2696 Ok(token) => token,
2697 Err(e) => match dlg.token(e) {
2698 Ok(token) => token,
2699 Err(e) => {
2700 dlg.finished(false);
2701 return Err(common::Error::MissingToken(e));
2702 }
2703 },
2704 };
2705 let mut req_result = {
2706 let client = &self.hub.client;
2707 dlg.pre_request();
2708 let mut req_builder = hyper::Request::builder()
2709 .method(hyper::Method::GET)
2710 .uri(url.as_str())
2711 .header(USER_AGENT, self.hub._user_agent.clone());
2712
2713 if let Some(token) = token.as_ref() {
2714 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2715 }
2716
2717 let request = req_builder
2718 .header(CONTENT_LENGTH, 0_u64)
2719 .body(common::to_body::<String>(None));
2720
2721 client.request(request.unwrap()).await
2722 };
2723
2724 match req_result {
2725 Err(err) => {
2726 if let common::Retry::After(d) = dlg.http_error(&err) {
2727 sleep(d).await;
2728 continue;
2729 }
2730 dlg.finished(false);
2731 return Err(common::Error::HttpError(err));
2732 }
2733 Ok(res) => {
2734 let (mut parts, body) = res.into_parts();
2735 let mut body = common::Body::new(body);
2736 if !parts.status.is_success() {
2737 let bytes = common::to_bytes(body).await.unwrap_or_default();
2738 let error = serde_json::from_str(&common::to_string(&bytes));
2739 let response = common::to_response(parts, bytes.into());
2740
2741 if let common::Retry::After(d) =
2742 dlg.http_failure(&response, error.as_ref().ok())
2743 {
2744 sleep(d).await;
2745 continue;
2746 }
2747
2748 dlg.finished(false);
2749
2750 return Err(match error {
2751 Ok(value) => common::Error::BadRequest(value),
2752 _ => common::Error::Failure(response),
2753 });
2754 }
2755 let response = {
2756 let bytes = common::to_bytes(body).await.unwrap_or_default();
2757 let encoded = common::to_string(&bytes);
2758 match serde_json::from_str(&encoded) {
2759 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2760 Err(error) => {
2761 dlg.response_json_decode_error(&encoded, &error);
2762 return Err(common::Error::JsonDecodeError(
2763 encoded.to_string(),
2764 error,
2765 ));
2766 }
2767 }
2768 };
2769
2770 dlg.finished(true);
2771 return Ok(response);
2772 }
2773 }
2774 }
2775 }
2776
2777 /// The project associated with the model.
2778 ///
2779 /// Sets the *project* path property to the given value.
2780 ///
2781 /// Even though the property as already been set when instantiating this call,
2782 /// we provide this method for API completeness.
2783 pub fn project(mut self, new_value: &str) -> TrainedmodelListCall<'a, C> {
2784 self._project = new_value.to_string();
2785 self
2786 }
2787 /// Pagination token.
2788 ///
2789 /// Sets the *page token* query property to the given value.
2790 pub fn page_token(mut self, new_value: &str) -> TrainedmodelListCall<'a, C> {
2791 self._page_token = Some(new_value.to_string());
2792 self
2793 }
2794 /// Maximum number of results to return.
2795 ///
2796 /// Sets the *max results* query property to the given value.
2797 pub fn max_results(mut self, new_value: u32) -> TrainedmodelListCall<'a, C> {
2798 self._max_results = Some(new_value);
2799 self
2800 }
2801 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2802 /// while executing the actual API request.
2803 ///
2804 /// ````text
2805 /// It should be used to handle progress information, and to implement a certain level of resilience.
2806 /// ````
2807 ///
2808 /// Sets the *delegate* property to the given value.
2809 pub fn delegate(
2810 mut self,
2811 new_value: &'a mut dyn common::Delegate,
2812 ) -> TrainedmodelListCall<'a, C> {
2813 self._delegate = Some(new_value);
2814 self
2815 }
2816
2817 /// Set any additional parameter of the query string used in the request.
2818 /// It should be used to set parameters which are not yet available through their own
2819 /// setters.
2820 ///
2821 /// Please note that this method must not be used to set any of the known parameters
2822 /// which have their own setter method. If done anyway, the request will fail.
2823 ///
2824 /// # Additional Parameters
2825 ///
2826 /// * *alt* (query-string) - Data format for the response.
2827 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2828 /// * *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.
2829 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2830 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2831 /// * *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. Overrides userIp if both are provided.
2832 /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
2833 pub fn param<T>(mut self, name: T, value: T) -> TrainedmodelListCall<'a, C>
2834 where
2835 T: AsRef<str>,
2836 {
2837 self._additional_params
2838 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2839 self
2840 }
2841
2842 /// Identifies the authorization scope for the method you are building.
2843 ///
2844 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2845 /// [`Scope::CloudPlatform`].
2846 ///
2847 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2848 /// tokens for more than one scope.
2849 ///
2850 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2851 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2852 /// sufficient, a read-write scope will do as well.
2853 pub fn add_scope<St>(mut self, scope: St) -> TrainedmodelListCall<'a, C>
2854 where
2855 St: AsRef<str>,
2856 {
2857 self._scopes.insert(String::from(scope.as_ref()));
2858 self
2859 }
2860 /// Identifies the authorization scope(s) for the method you are building.
2861 ///
2862 /// See [`Self::add_scope()`] for details.
2863 pub fn add_scopes<I, St>(mut self, scopes: I) -> TrainedmodelListCall<'a, C>
2864 where
2865 I: IntoIterator<Item = St>,
2866 St: AsRef<str>,
2867 {
2868 self._scopes
2869 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2870 self
2871 }
2872
2873 /// Removes all scopes, and no default scope will be used either.
2874 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2875 /// for details).
2876 pub fn clear_scopes(mut self) -> TrainedmodelListCall<'a, C> {
2877 self._scopes.clear();
2878 self
2879 }
2880}
2881
2882/// Submit model id and request a prediction.
2883///
2884/// A builder for the *predict* method supported by a *trainedmodel* resource.
2885/// It is not used directly, but through a [`TrainedmodelMethods`] instance.
2886///
2887/// # Example
2888///
2889/// Instantiate a resource method builder
2890///
2891/// ```test_harness,no_run
2892/// # extern crate hyper;
2893/// # extern crate hyper_rustls;
2894/// # extern crate google_prediction1d6 as prediction1d6;
2895/// use prediction1d6::api::Input;
2896/// # async fn dox() {
2897/// # use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2898///
2899/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2900/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2901/// # .with_native_roots()
2902/// # .unwrap()
2903/// # .https_only()
2904/// # .enable_http2()
2905/// # .build();
2906///
2907/// # let executor = hyper_util::rt::TokioExecutor::new();
2908/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2909/// # secret,
2910/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2911/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2912/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2913/// # ),
2914/// # ).build().await.unwrap();
2915///
2916/// # let client = hyper_util::client::legacy::Client::builder(
2917/// # hyper_util::rt::TokioExecutor::new()
2918/// # )
2919/// # .build(
2920/// # hyper_rustls::HttpsConnectorBuilder::new()
2921/// # .with_native_roots()
2922/// # .unwrap()
2923/// # .https_or_http()
2924/// # .enable_http2()
2925/// # .build()
2926/// # );
2927/// # let mut hub = Prediction::new(client, auth);
2928/// // As the method needs a request, you would usually fill it with the desired information
2929/// // into the respective structure. Some of the parts shown here might not be applicable !
2930/// // Values shown here are possibly random and not representative !
2931/// let mut req = Input::default();
2932///
2933/// // You can configure optional parameters by calling the respective setters at will, and
2934/// // execute the final call using `doit()`.
2935/// // Values shown here are possibly random and not representative !
2936/// let result = hub.trainedmodels().predict(req, "project", "id")
2937/// .doit().await;
2938/// # }
2939/// ```
2940pub struct TrainedmodelPredictCall<'a, C>
2941where
2942 C: 'a,
2943{
2944 hub: &'a Prediction<C>,
2945 _request: Input,
2946 _project: String,
2947 _id: String,
2948 _delegate: Option<&'a mut dyn common::Delegate>,
2949 _additional_params: HashMap<String, String>,
2950 _scopes: BTreeSet<String>,
2951}
2952
2953impl<'a, C> common::CallBuilder for TrainedmodelPredictCall<'a, C> {}
2954
2955impl<'a, C> TrainedmodelPredictCall<'a, C>
2956where
2957 C: common::Connector,
2958{
2959 /// Perform the operation you have build so far.
2960 pub async fn doit(mut self) -> common::Result<(common::Response, Output)> {
2961 use std::borrow::Cow;
2962 use std::io::{Read, Seek};
2963
2964 use common::{url::Params, ToParts};
2965 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2966
2967 let mut dd = common::DefaultDelegate;
2968 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2969 dlg.begin(common::MethodInfo {
2970 id: "prediction.trainedmodels.predict",
2971 http_method: hyper::Method::POST,
2972 });
2973
2974 for &field in ["alt", "project", "id"].iter() {
2975 if self._additional_params.contains_key(field) {
2976 dlg.finished(false);
2977 return Err(common::Error::FieldClash(field));
2978 }
2979 }
2980
2981 let mut params = Params::with_capacity(5 + self._additional_params.len());
2982 params.push("project", self._project);
2983 params.push("id", self._id);
2984
2985 params.extend(self._additional_params.iter());
2986
2987 params.push("alt", "json");
2988 let mut url = self.hub._base_url.clone() + "{project}/trainedmodels/{id}/predict";
2989 if self._scopes.is_empty() {
2990 self._scopes
2991 .insert(Scope::CloudPlatform.as_ref().to_string());
2992 }
2993
2994 #[allow(clippy::single_element_loop)]
2995 for &(find_this, param_name) in [("{project}", "project"), ("{id}", "id")].iter() {
2996 url = params.uri_replacement(url, param_name, find_this, false);
2997 }
2998 {
2999 let to_remove = ["id", "project"];
3000 params.remove_params(&to_remove);
3001 }
3002
3003 let url = params.parse_with_url(&url);
3004
3005 let mut json_mime_type = mime::APPLICATION_JSON;
3006 let mut request_value_reader = {
3007 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
3008 common::remove_json_null_values(&mut value);
3009 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
3010 serde_json::to_writer(&mut dst, &value).unwrap();
3011 dst
3012 };
3013 let request_size = request_value_reader
3014 .seek(std::io::SeekFrom::End(0))
3015 .unwrap();
3016 request_value_reader
3017 .seek(std::io::SeekFrom::Start(0))
3018 .unwrap();
3019
3020 loop {
3021 let token = match self
3022 .hub
3023 .auth
3024 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3025 .await
3026 {
3027 Ok(token) => token,
3028 Err(e) => match dlg.token(e) {
3029 Ok(token) => token,
3030 Err(e) => {
3031 dlg.finished(false);
3032 return Err(common::Error::MissingToken(e));
3033 }
3034 },
3035 };
3036 request_value_reader
3037 .seek(std::io::SeekFrom::Start(0))
3038 .unwrap();
3039 let mut req_result = {
3040 let client = &self.hub.client;
3041 dlg.pre_request();
3042 let mut req_builder = hyper::Request::builder()
3043 .method(hyper::Method::POST)
3044 .uri(url.as_str())
3045 .header(USER_AGENT, self.hub._user_agent.clone());
3046
3047 if let Some(token) = token.as_ref() {
3048 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3049 }
3050
3051 let request = req_builder
3052 .header(CONTENT_TYPE, json_mime_type.to_string())
3053 .header(CONTENT_LENGTH, request_size as u64)
3054 .body(common::to_body(
3055 request_value_reader.get_ref().clone().into(),
3056 ));
3057
3058 client.request(request.unwrap()).await
3059 };
3060
3061 match req_result {
3062 Err(err) => {
3063 if let common::Retry::After(d) = dlg.http_error(&err) {
3064 sleep(d).await;
3065 continue;
3066 }
3067 dlg.finished(false);
3068 return Err(common::Error::HttpError(err));
3069 }
3070 Ok(res) => {
3071 let (mut parts, body) = res.into_parts();
3072 let mut body = common::Body::new(body);
3073 if !parts.status.is_success() {
3074 let bytes = common::to_bytes(body).await.unwrap_or_default();
3075 let error = serde_json::from_str(&common::to_string(&bytes));
3076 let response = common::to_response(parts, bytes.into());
3077
3078 if let common::Retry::After(d) =
3079 dlg.http_failure(&response, error.as_ref().ok())
3080 {
3081 sleep(d).await;
3082 continue;
3083 }
3084
3085 dlg.finished(false);
3086
3087 return Err(match error {
3088 Ok(value) => common::Error::BadRequest(value),
3089 _ => common::Error::Failure(response),
3090 });
3091 }
3092 let response = {
3093 let bytes = common::to_bytes(body).await.unwrap_or_default();
3094 let encoded = common::to_string(&bytes);
3095 match serde_json::from_str(&encoded) {
3096 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3097 Err(error) => {
3098 dlg.response_json_decode_error(&encoded, &error);
3099 return Err(common::Error::JsonDecodeError(
3100 encoded.to_string(),
3101 error,
3102 ));
3103 }
3104 }
3105 };
3106
3107 dlg.finished(true);
3108 return Ok(response);
3109 }
3110 }
3111 }
3112 }
3113
3114 ///
3115 /// Sets the *request* property to the given value.
3116 ///
3117 /// Even though the property as already been set when instantiating this call,
3118 /// we provide this method for API completeness.
3119 pub fn request(mut self, new_value: Input) -> TrainedmodelPredictCall<'a, C> {
3120 self._request = new_value;
3121 self
3122 }
3123 /// The project associated with the model.
3124 ///
3125 /// Sets the *project* path property to the given value.
3126 ///
3127 /// Even though the property as already been set when instantiating this call,
3128 /// we provide this method for API completeness.
3129 pub fn project(mut self, new_value: &str) -> TrainedmodelPredictCall<'a, C> {
3130 self._project = new_value.to_string();
3131 self
3132 }
3133 /// The unique name for the predictive model.
3134 ///
3135 /// Sets the *id* path property to the given value.
3136 ///
3137 /// Even though the property as already been set when instantiating this call,
3138 /// we provide this method for API completeness.
3139 pub fn id(mut self, new_value: &str) -> TrainedmodelPredictCall<'a, C> {
3140 self._id = new_value.to_string();
3141 self
3142 }
3143 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3144 /// while executing the actual API request.
3145 ///
3146 /// ````text
3147 /// It should be used to handle progress information, and to implement a certain level of resilience.
3148 /// ````
3149 ///
3150 /// Sets the *delegate* property to the given value.
3151 pub fn delegate(
3152 mut self,
3153 new_value: &'a mut dyn common::Delegate,
3154 ) -> TrainedmodelPredictCall<'a, C> {
3155 self._delegate = Some(new_value);
3156 self
3157 }
3158
3159 /// Set any additional parameter of the query string used in the request.
3160 /// It should be used to set parameters which are not yet available through their own
3161 /// setters.
3162 ///
3163 /// Please note that this method must not be used to set any of the known parameters
3164 /// which have their own setter method. If done anyway, the request will fail.
3165 ///
3166 /// # Additional Parameters
3167 ///
3168 /// * *alt* (query-string) - Data format for the response.
3169 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3170 /// * *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.
3171 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3172 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3173 /// * *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. Overrides userIp if both are provided.
3174 /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
3175 pub fn param<T>(mut self, name: T, value: T) -> TrainedmodelPredictCall<'a, C>
3176 where
3177 T: AsRef<str>,
3178 {
3179 self._additional_params
3180 .insert(name.as_ref().to_string(), value.as_ref().to_string());
3181 self
3182 }
3183
3184 /// Identifies the authorization scope for the method you are building.
3185 ///
3186 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3187 /// [`Scope::CloudPlatform`].
3188 ///
3189 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3190 /// tokens for more than one scope.
3191 ///
3192 /// Usually there is more than one suitable scope to authorize an operation, some of which may
3193 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3194 /// sufficient, a read-write scope will do as well.
3195 pub fn add_scope<St>(mut self, scope: St) -> TrainedmodelPredictCall<'a, C>
3196 where
3197 St: AsRef<str>,
3198 {
3199 self._scopes.insert(String::from(scope.as_ref()));
3200 self
3201 }
3202 /// Identifies the authorization scope(s) for the method you are building.
3203 ///
3204 /// See [`Self::add_scope()`] for details.
3205 pub fn add_scopes<I, St>(mut self, scopes: I) -> TrainedmodelPredictCall<'a, C>
3206 where
3207 I: IntoIterator<Item = St>,
3208 St: AsRef<str>,
3209 {
3210 self._scopes
3211 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3212 self
3213 }
3214
3215 /// Removes all scopes, and no default scope will be used either.
3216 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3217 /// for details).
3218 pub fn clear_scopes(mut self) -> TrainedmodelPredictCall<'a, C> {
3219 self._scopes.clear();
3220 self
3221 }
3222}
3223
3224/// Add new data to a trained model.
3225///
3226/// A builder for the *update* method supported by a *trainedmodel* resource.
3227/// It is not used directly, but through a [`TrainedmodelMethods`] instance.
3228///
3229/// # Example
3230///
3231/// Instantiate a resource method builder
3232///
3233/// ```test_harness,no_run
3234/// # extern crate hyper;
3235/// # extern crate hyper_rustls;
3236/// # extern crate google_prediction1d6 as prediction1d6;
3237/// use prediction1d6::api::Update;
3238/// # async fn dox() {
3239/// # use prediction1d6::{Prediction, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
3240///
3241/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
3242/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
3243/// # .with_native_roots()
3244/// # .unwrap()
3245/// # .https_only()
3246/// # .enable_http2()
3247/// # .build();
3248///
3249/// # let executor = hyper_util::rt::TokioExecutor::new();
3250/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
3251/// # secret,
3252/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
3253/// # yup_oauth2::client::CustomHyperClientBuilder::from(
3254/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
3255/// # ),
3256/// # ).build().await.unwrap();
3257///
3258/// # let client = hyper_util::client::legacy::Client::builder(
3259/// # hyper_util::rt::TokioExecutor::new()
3260/// # )
3261/// # .build(
3262/// # hyper_rustls::HttpsConnectorBuilder::new()
3263/// # .with_native_roots()
3264/// # .unwrap()
3265/// # .https_or_http()
3266/// # .enable_http2()
3267/// # .build()
3268/// # );
3269/// # let mut hub = Prediction::new(client, auth);
3270/// // As the method needs a request, you would usually fill it with the desired information
3271/// // into the respective structure. Some of the parts shown here might not be applicable !
3272/// // Values shown here are possibly random and not representative !
3273/// let mut req = Update::default();
3274///
3275/// // You can configure optional parameters by calling the respective setters at will, and
3276/// // execute the final call using `doit()`.
3277/// // Values shown here are possibly random and not representative !
3278/// let result = hub.trainedmodels().update(req, "project", "id")
3279/// .doit().await;
3280/// # }
3281/// ```
3282pub struct TrainedmodelUpdateCall<'a, C>
3283where
3284 C: 'a,
3285{
3286 hub: &'a Prediction<C>,
3287 _request: Update,
3288 _project: String,
3289 _id: String,
3290 _delegate: Option<&'a mut dyn common::Delegate>,
3291 _additional_params: HashMap<String, String>,
3292 _scopes: BTreeSet<String>,
3293}
3294
3295impl<'a, C> common::CallBuilder for TrainedmodelUpdateCall<'a, C> {}
3296
3297impl<'a, C> TrainedmodelUpdateCall<'a, C>
3298where
3299 C: common::Connector,
3300{
3301 /// Perform the operation you have build so far.
3302 pub async fn doit(mut self) -> common::Result<(common::Response, Insert2)> {
3303 use std::borrow::Cow;
3304 use std::io::{Read, Seek};
3305
3306 use common::{url::Params, ToParts};
3307 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
3308
3309 let mut dd = common::DefaultDelegate;
3310 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3311 dlg.begin(common::MethodInfo {
3312 id: "prediction.trainedmodels.update",
3313 http_method: hyper::Method::PUT,
3314 });
3315
3316 for &field in ["alt", "project", "id"].iter() {
3317 if self._additional_params.contains_key(field) {
3318 dlg.finished(false);
3319 return Err(common::Error::FieldClash(field));
3320 }
3321 }
3322
3323 let mut params = Params::with_capacity(5 + self._additional_params.len());
3324 params.push("project", self._project);
3325 params.push("id", self._id);
3326
3327 params.extend(self._additional_params.iter());
3328
3329 params.push("alt", "json");
3330 let mut url = self.hub._base_url.clone() + "{project}/trainedmodels/{id}";
3331 if self._scopes.is_empty() {
3332 self._scopes
3333 .insert(Scope::CloudPlatform.as_ref().to_string());
3334 }
3335
3336 #[allow(clippy::single_element_loop)]
3337 for &(find_this, param_name) in [("{project}", "project"), ("{id}", "id")].iter() {
3338 url = params.uri_replacement(url, param_name, find_this, false);
3339 }
3340 {
3341 let to_remove = ["id", "project"];
3342 params.remove_params(&to_remove);
3343 }
3344
3345 let url = params.parse_with_url(&url);
3346
3347 let mut json_mime_type = mime::APPLICATION_JSON;
3348 let mut request_value_reader = {
3349 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
3350 common::remove_json_null_values(&mut value);
3351 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
3352 serde_json::to_writer(&mut dst, &value).unwrap();
3353 dst
3354 };
3355 let request_size = request_value_reader
3356 .seek(std::io::SeekFrom::End(0))
3357 .unwrap();
3358 request_value_reader
3359 .seek(std::io::SeekFrom::Start(0))
3360 .unwrap();
3361
3362 loop {
3363 let token = match self
3364 .hub
3365 .auth
3366 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3367 .await
3368 {
3369 Ok(token) => token,
3370 Err(e) => match dlg.token(e) {
3371 Ok(token) => token,
3372 Err(e) => {
3373 dlg.finished(false);
3374 return Err(common::Error::MissingToken(e));
3375 }
3376 },
3377 };
3378 request_value_reader
3379 .seek(std::io::SeekFrom::Start(0))
3380 .unwrap();
3381 let mut req_result = {
3382 let client = &self.hub.client;
3383 dlg.pre_request();
3384 let mut req_builder = hyper::Request::builder()
3385 .method(hyper::Method::PUT)
3386 .uri(url.as_str())
3387 .header(USER_AGENT, self.hub._user_agent.clone());
3388
3389 if let Some(token) = token.as_ref() {
3390 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3391 }
3392
3393 let request = req_builder
3394 .header(CONTENT_TYPE, json_mime_type.to_string())
3395 .header(CONTENT_LENGTH, request_size as u64)
3396 .body(common::to_body(
3397 request_value_reader.get_ref().clone().into(),
3398 ));
3399
3400 client.request(request.unwrap()).await
3401 };
3402
3403 match req_result {
3404 Err(err) => {
3405 if let common::Retry::After(d) = dlg.http_error(&err) {
3406 sleep(d).await;
3407 continue;
3408 }
3409 dlg.finished(false);
3410 return Err(common::Error::HttpError(err));
3411 }
3412 Ok(res) => {
3413 let (mut parts, body) = res.into_parts();
3414 let mut body = common::Body::new(body);
3415 if !parts.status.is_success() {
3416 let bytes = common::to_bytes(body).await.unwrap_or_default();
3417 let error = serde_json::from_str(&common::to_string(&bytes));
3418 let response = common::to_response(parts, bytes.into());
3419
3420 if let common::Retry::After(d) =
3421 dlg.http_failure(&response, error.as_ref().ok())
3422 {
3423 sleep(d).await;
3424 continue;
3425 }
3426
3427 dlg.finished(false);
3428
3429 return Err(match error {
3430 Ok(value) => common::Error::BadRequest(value),
3431 _ => common::Error::Failure(response),
3432 });
3433 }
3434 let response = {
3435 let bytes = common::to_bytes(body).await.unwrap_or_default();
3436 let encoded = common::to_string(&bytes);
3437 match serde_json::from_str(&encoded) {
3438 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3439 Err(error) => {
3440 dlg.response_json_decode_error(&encoded, &error);
3441 return Err(common::Error::JsonDecodeError(
3442 encoded.to_string(),
3443 error,
3444 ));
3445 }
3446 }
3447 };
3448
3449 dlg.finished(true);
3450 return Ok(response);
3451 }
3452 }
3453 }
3454 }
3455
3456 ///
3457 /// Sets the *request* property to the given value.
3458 ///
3459 /// Even though the property as already been set when instantiating this call,
3460 /// we provide this method for API completeness.
3461 pub fn request(mut self, new_value: Update) -> TrainedmodelUpdateCall<'a, C> {
3462 self._request = new_value;
3463 self
3464 }
3465 /// The project associated with the model.
3466 ///
3467 /// Sets the *project* path property to the given value.
3468 ///
3469 /// Even though the property as already been set when instantiating this call,
3470 /// we provide this method for API completeness.
3471 pub fn project(mut self, new_value: &str) -> TrainedmodelUpdateCall<'a, C> {
3472 self._project = new_value.to_string();
3473 self
3474 }
3475 /// The unique name for the predictive model.
3476 ///
3477 /// Sets the *id* path property to the given value.
3478 ///
3479 /// Even though the property as already been set when instantiating this call,
3480 /// we provide this method for API completeness.
3481 pub fn id(mut self, new_value: &str) -> TrainedmodelUpdateCall<'a, C> {
3482 self._id = new_value.to_string();
3483 self
3484 }
3485 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3486 /// while executing the actual API request.
3487 ///
3488 /// ````text
3489 /// It should be used to handle progress information, and to implement a certain level of resilience.
3490 /// ````
3491 ///
3492 /// Sets the *delegate* property to the given value.
3493 pub fn delegate(
3494 mut self,
3495 new_value: &'a mut dyn common::Delegate,
3496 ) -> TrainedmodelUpdateCall<'a, C> {
3497 self._delegate = Some(new_value);
3498 self
3499 }
3500
3501 /// Set any additional parameter of the query string used in the request.
3502 /// It should be used to set parameters which are not yet available through their own
3503 /// setters.
3504 ///
3505 /// Please note that this method must not be used to set any of the known parameters
3506 /// which have their own setter method. If done anyway, the request will fail.
3507 ///
3508 /// # Additional Parameters
3509 ///
3510 /// * *alt* (query-string) - Data format for the response.
3511 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3512 /// * *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.
3513 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3514 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3515 /// * *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. Overrides userIp if both are provided.
3516 /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
3517 pub fn param<T>(mut self, name: T, value: T) -> TrainedmodelUpdateCall<'a, C>
3518 where
3519 T: AsRef<str>,
3520 {
3521 self._additional_params
3522 .insert(name.as_ref().to_string(), value.as_ref().to_string());
3523 self
3524 }
3525
3526 /// Identifies the authorization scope for the method you are building.
3527 ///
3528 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3529 /// [`Scope::CloudPlatform`].
3530 ///
3531 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3532 /// tokens for more than one scope.
3533 ///
3534 /// Usually there is more than one suitable scope to authorize an operation, some of which may
3535 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3536 /// sufficient, a read-write scope will do as well.
3537 pub fn add_scope<St>(mut self, scope: St) -> TrainedmodelUpdateCall<'a, C>
3538 where
3539 St: AsRef<str>,
3540 {
3541 self._scopes.insert(String::from(scope.as_ref()));
3542 self
3543 }
3544 /// Identifies the authorization scope(s) for the method you are building.
3545 ///
3546 /// See [`Self::add_scope()`] for details.
3547 pub fn add_scopes<I, St>(mut self, scopes: I) -> TrainedmodelUpdateCall<'a, C>
3548 where
3549 I: IntoIterator<Item = St>,
3550 St: AsRef<str>,
3551 {
3552 self._scopes
3553 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3554 self
3555 }
3556
3557 /// Removes all scopes, and no default scope will be used either.
3558 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3559 /// for details).
3560 pub fn clear_scopes(mut self) -> TrainedmodelUpdateCall<'a, C> {
3561 self._scopes.clear();
3562 self
3563 }
3564}