google_appstate1/
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 for this application
17    Full,
18}
19
20impl AsRef<str> for Scope {
21    fn as_ref(&self) -> &str {
22        match *self {
23            Scope::Full => "https://www.googleapis.com/auth/appstate",
24        }
25    }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30    fn default() -> Scope {
31        Scope::Full
32    }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all AppState related resource activities
40///
41/// # Examples
42///
43/// Instantiate a new hub
44///
45/// ```test_harness,no_run
46/// extern crate hyper;
47/// extern crate hyper_rustls;
48/// extern crate google_appstate1 as appstate1;
49/// use appstate1::api::UpdateRequest;
50/// use appstate1::{Result, Error};
51/// # async fn dox() {
52/// use appstate1::{AppState, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
53///
54/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
55/// // `client_secret`, among other things.
56/// let secret: yup_oauth2::ApplicationSecret = Default::default();
57/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
58/// // unless you replace  `None` with the desired Flow.
59/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
60/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
61/// // retrieve them from storage.
62/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
63///     .with_native_roots()
64///     .unwrap()
65///     .https_only()
66///     .enable_http2()
67///     .build();
68///
69/// let executor = hyper_util::rt::TokioExecutor::new();
70/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
71///     secret,
72///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
73///     yup_oauth2::client::CustomHyperClientBuilder::from(
74///         hyper_util::client::legacy::Client::builder(executor).build(connector),
75///     ),
76/// ).build().await.unwrap();
77///
78/// let client = hyper_util::client::legacy::Client::builder(
79///     hyper_util::rt::TokioExecutor::new()
80/// )
81/// .build(
82///     hyper_rustls::HttpsConnectorBuilder::new()
83///         .with_native_roots()
84///         .unwrap()
85///         .https_or_http()
86///         .enable_http2()
87///         .build()
88/// );
89/// let mut hub = AppState::new(client, auth);
90/// // As the method needs a request, you would usually fill it with the desired information
91/// // into the respective structure. Some of the parts shown here might not be applicable !
92/// // Values shown here are possibly random and not representative !
93/// let mut req = UpdateRequest::default();
94///
95/// // You can configure optional parameters by calling the respective setters at will, and
96/// // execute the final call using `doit()`.
97/// // Values shown here are possibly random and not representative !
98/// let result = hub.states().update(req, -28)
99///              .current_state_version("At")
100///              .doit().await;
101///
102/// match result {
103///     Err(e) => match e {
104///         // The Error enum provides details about what exactly happened.
105///         // You can also just use its `Debug`, `Display` or `Error` traits
106///          Error::HttpError(_)
107///         |Error::Io(_)
108///         |Error::MissingAPIKey
109///         |Error::MissingToken(_)
110///         |Error::Cancelled
111///         |Error::UploadSizeLimitExceeded(_, _)
112///         |Error::Failure(_)
113///         |Error::BadRequest(_)
114///         |Error::FieldClash(_)
115///         |Error::JsonDecodeError(_, _) => println!("{}", e),
116///     },
117///     Ok(res) => println!("Success: {:?}", res),
118/// }
119/// # }
120/// ```
121#[derive(Clone)]
122pub struct AppState<C> {
123    pub client: common::Client<C>,
124    pub auth: Box<dyn common::GetToken>,
125    _user_agent: String,
126    _base_url: String,
127    _root_url: String,
128}
129
130impl<C> common::Hub for AppState<C> {}
131
132impl<'a, C> AppState<C> {
133    pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> AppState<C> {
134        AppState {
135            client,
136            auth: Box::new(auth),
137            _user_agent: "google-api-rust-client/7.0.0".to_string(),
138            _base_url: "https://www.googleapis.com/appstate/v1/".to_string(),
139            _root_url: "https://www.googleapis.com/".to_string(),
140        }
141    }
142
143    pub fn states(&'a self) -> StateMethods<'a, C> {
144        StateMethods { hub: self }
145    }
146
147    /// Set the user-agent header field to use in all requests to the server.
148    /// It defaults to `google-api-rust-client/7.0.0`.
149    ///
150    /// Returns the previously set user-agent.
151    pub fn user_agent(&mut self, agent_name: String) -> String {
152        std::mem::replace(&mut self._user_agent, agent_name)
153    }
154
155    /// Set the base url to use in all requests to the server.
156    /// It defaults to `https://www.googleapis.com/appstate/v1/`.
157    ///
158    /// Returns the previously set base url.
159    pub fn base_url(&mut self, new_base_url: String) -> String {
160        std::mem::replace(&mut self._base_url, new_base_url)
161    }
162
163    /// Set the root url to use in all requests to the server.
164    /// It defaults to `https://www.googleapis.com/`.
165    ///
166    /// Returns the previously set root url.
167    pub fn root_url(&mut self, new_root_url: String) -> String {
168        std::mem::replace(&mut self._root_url, new_root_url)
169    }
170}
171
172// ############
173// SCHEMAS ###
174// ##########
175/// This is a JSON template for an app state resource.
176///
177/// # Activities
178///
179/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
180/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
181///
182/// * [get states](StateGetCall) (response)
183#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
184#[serde_with::serde_as]
185#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
186pub struct GetResponse {
187    /// The current app state version.
188    #[serde(rename = "currentStateVersion")]
189    pub current_state_version: Option<String>,
190    /// The requested data.
191    pub data: Option<String>,
192    /// Uniquely identifies the type of this resource. Value is always the fixed string appstate#getResponse.
193    pub kind: Option<String>,
194    /// The key for the data.
195    #[serde(rename = "stateKey")]
196    pub state_key: Option<i32>,
197}
198
199impl common::ResponseResult for GetResponse {}
200
201/// This is a JSON template to convert a list-response for app state.
202///
203/// # Activities
204///
205/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
206/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
207///
208/// * [list states](StateListCall) (response)
209#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
210#[serde_with::serde_as]
211#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
212pub struct ListResponse {
213    /// The app state data.
214    pub items: Option<Vec<GetResponse>>,
215    /// Uniquely identifies the type of this resource. Value is always the fixed string appstate#listResponse.
216    pub kind: Option<String>,
217    /// The maximum number of keys allowed for this user.
218    #[serde(rename = "maximumKeyCount")]
219    pub maximum_key_count: Option<i32>,
220}
221
222impl common::ResponseResult for ListResponse {}
223
224/// This is a JSON template for a requests which update app state
225///
226/// # Activities
227///
228/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
229/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
230///
231/// * [update states](StateUpdateCall) (request)
232#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
233#[serde_with::serde_as]
234#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
235pub struct UpdateRequest {
236    /// The new app state data that your application is trying to update with.
237    pub data: Option<String>,
238    /// Uniquely identifies the type of this resource. Value is always the fixed string appstate#updateRequest.
239    pub kind: Option<String>,
240}
241
242impl common::RequestValue for UpdateRequest {}
243
244/// This is a JSON template for an app state write result.
245///
246/// # Activities
247///
248/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
249/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
250///
251/// * [clear states](StateClearCall) (response)
252/// * [update states](StateUpdateCall) (response)
253#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
254#[serde_with::serde_as]
255#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
256pub struct WriteResult {
257    /// The version of the data for this key on the server.
258    #[serde(rename = "currentStateVersion")]
259    pub current_state_version: Option<String>,
260    /// Uniquely identifies the type of this resource. Value is always the fixed string appstate#writeResult.
261    pub kind: Option<String>,
262    /// The written key.
263    #[serde(rename = "stateKey")]
264    pub state_key: Option<i32>,
265}
266
267impl common::ResponseResult for WriteResult {}
268
269// ###################
270// MethodBuilders ###
271// #################
272
273/// A builder providing access to all methods supported on *state* resources.
274/// It is not used directly, but through the [`AppState`] hub.
275///
276/// # Example
277///
278/// Instantiate a resource builder
279///
280/// ```test_harness,no_run
281/// extern crate hyper;
282/// extern crate hyper_rustls;
283/// extern crate google_appstate1 as appstate1;
284///
285/// # async fn dox() {
286/// use appstate1::{AppState, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
287///
288/// let secret: yup_oauth2::ApplicationSecret = Default::default();
289/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
290///     .with_native_roots()
291///     .unwrap()
292///     .https_only()
293///     .enable_http2()
294///     .build();
295///
296/// let executor = hyper_util::rt::TokioExecutor::new();
297/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
298///     secret,
299///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
300///     yup_oauth2::client::CustomHyperClientBuilder::from(
301///         hyper_util::client::legacy::Client::builder(executor).build(connector),
302///     ),
303/// ).build().await.unwrap();
304///
305/// let client = hyper_util::client::legacy::Client::builder(
306///     hyper_util::rt::TokioExecutor::new()
307/// )
308/// .build(
309///     hyper_rustls::HttpsConnectorBuilder::new()
310///         .with_native_roots()
311///         .unwrap()
312///         .https_or_http()
313///         .enable_http2()
314///         .build()
315/// );
316/// let mut hub = AppState::new(client, auth);
317/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
318/// // like `clear(...)`, `delete(...)`, `get(...)`, `list(...)` and `update(...)`
319/// // to build up your call.
320/// let rb = hub.states();
321/// # }
322/// ```
323pub struct StateMethods<'a, C>
324where
325    C: 'a,
326{
327    hub: &'a AppState<C>,
328}
329
330impl<'a, C> common::MethodsBuilder for StateMethods<'a, C> {}
331
332impl<'a, C> StateMethods<'a, C> {
333    /// Create a builder to help you perform the following task:
334    ///
335    /// Clears (sets to empty) the data for the passed key if and only if the passed version matches the currently stored version. This method results in a conflict error on version mismatch.
336    ///
337    /// # Arguments
338    ///
339    /// * `stateKey` - The key for the data to be retrieved.
340    pub fn clear(&self, state_key: i32) -> StateClearCall<'a, C> {
341        StateClearCall {
342            hub: self.hub,
343            _state_key: state_key,
344            _current_data_version: Default::default(),
345            _delegate: Default::default(),
346            _additional_params: Default::default(),
347            _scopes: Default::default(),
348        }
349    }
350
351    /// Create a builder to help you perform the following task:
352    ///
353    /// Deletes a key and the data associated with it. The key is removed and no longer counts against the key quota. Note that since this method is not safe in the face of concurrent modifications, it should only be used for development and testing purposes. Invoking this method in shipping code can result in data loss and data corruption.
354    ///
355    /// # Arguments
356    ///
357    /// * `stateKey` - The key for the data to be retrieved.
358    pub fn delete(&self, state_key: i32) -> StateDeleteCall<'a, C> {
359        StateDeleteCall {
360            hub: self.hub,
361            _state_key: state_key,
362            _delegate: Default::default(),
363            _additional_params: Default::default(),
364            _scopes: Default::default(),
365        }
366    }
367
368    /// Create a builder to help you perform the following task:
369    ///
370    /// Retrieves the data corresponding to the passed key. If the key does not exist on the server, an HTTP 404 will be returned.
371    ///
372    /// # Arguments
373    ///
374    /// * `stateKey` - The key for the data to be retrieved.
375    pub fn get(&self, state_key: i32) -> StateGetCall<'a, C> {
376        StateGetCall {
377            hub: self.hub,
378            _state_key: state_key,
379            _delegate: Default::default(),
380            _additional_params: Default::default(),
381            _scopes: Default::default(),
382        }
383    }
384
385    /// Create a builder to help you perform the following task:
386    ///
387    /// Lists all the states keys, and optionally the state data.
388    pub fn list(&self) -> StateListCall<'a, C> {
389        StateListCall {
390            hub: self.hub,
391            _include_data: Default::default(),
392            _delegate: Default::default(),
393            _additional_params: Default::default(),
394            _scopes: Default::default(),
395        }
396    }
397
398    /// Create a builder to help you perform the following task:
399    ///
400    /// Update the data associated with the input key if and only if the passed version matches the currently stored version. This method is safe in the face of concurrent writes. Maximum per-key size is 128KB.
401    ///
402    /// # Arguments
403    ///
404    /// * `request` - No description provided.
405    /// * `stateKey` - The key for the data to be retrieved.
406    pub fn update(&self, request: UpdateRequest, state_key: i32) -> StateUpdateCall<'a, C> {
407        StateUpdateCall {
408            hub: self.hub,
409            _request: request,
410            _state_key: state_key,
411            _current_state_version: Default::default(),
412            _delegate: Default::default(),
413            _additional_params: Default::default(),
414            _scopes: Default::default(),
415        }
416    }
417}
418
419// ###################
420// CallBuilders   ###
421// #################
422
423/// Clears (sets to empty) the data for the passed key if and only if the passed version matches the currently stored version. This method results in a conflict error on version mismatch.
424///
425/// A builder for the *clear* method supported by a *state* resource.
426/// It is not used directly, but through a [`StateMethods`] instance.
427///
428/// # Example
429///
430/// Instantiate a resource method builder
431///
432/// ```test_harness,no_run
433/// # extern crate hyper;
434/// # extern crate hyper_rustls;
435/// # extern crate google_appstate1 as appstate1;
436/// # async fn dox() {
437/// # use appstate1::{AppState, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
438///
439/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
440/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
441/// #     .with_native_roots()
442/// #     .unwrap()
443/// #     .https_only()
444/// #     .enable_http2()
445/// #     .build();
446///
447/// # let executor = hyper_util::rt::TokioExecutor::new();
448/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
449/// #     secret,
450/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
451/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
452/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
453/// #     ),
454/// # ).build().await.unwrap();
455///
456/// # let client = hyper_util::client::legacy::Client::builder(
457/// #     hyper_util::rt::TokioExecutor::new()
458/// # )
459/// # .build(
460/// #     hyper_rustls::HttpsConnectorBuilder::new()
461/// #         .with_native_roots()
462/// #         .unwrap()
463/// #         .https_or_http()
464/// #         .enable_http2()
465/// #         .build()
466/// # );
467/// # let mut hub = AppState::new(client, auth);
468/// // You can configure optional parameters by calling the respective setters at will, and
469/// // execute the final call using `doit()`.
470/// // Values shown here are possibly random and not representative !
471/// let result = hub.states().clear(-8)
472///              .current_data_version("sed")
473///              .doit().await;
474/// # }
475/// ```
476pub struct StateClearCall<'a, C>
477where
478    C: 'a,
479{
480    hub: &'a AppState<C>,
481    _state_key: i32,
482    _current_data_version: Option<String>,
483    _delegate: Option<&'a mut dyn common::Delegate>,
484    _additional_params: HashMap<String, String>,
485    _scopes: BTreeSet<String>,
486}
487
488impl<'a, C> common::CallBuilder for StateClearCall<'a, C> {}
489
490impl<'a, C> StateClearCall<'a, C>
491where
492    C: common::Connector,
493{
494    /// Perform the operation you have build so far.
495    pub async fn doit(mut self) -> common::Result<(common::Response, WriteResult)> {
496        use std::borrow::Cow;
497        use std::io::{Read, Seek};
498
499        use common::{url::Params, ToParts};
500        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
501
502        let mut dd = common::DefaultDelegate;
503        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
504        dlg.begin(common::MethodInfo {
505            id: "appstate.states.clear",
506            http_method: hyper::Method::POST,
507        });
508
509        for &field in ["alt", "stateKey", "currentDataVersion"].iter() {
510            if self._additional_params.contains_key(field) {
511                dlg.finished(false);
512                return Err(common::Error::FieldClash(field));
513            }
514        }
515
516        let mut params = Params::with_capacity(4 + self._additional_params.len());
517        params.push("stateKey", self._state_key.to_string());
518        if let Some(value) = self._current_data_version.as_ref() {
519            params.push("currentDataVersion", value);
520        }
521
522        params.extend(self._additional_params.iter());
523
524        params.push("alt", "json");
525        let mut url = self.hub._base_url.clone() + "states/{stateKey}/clear";
526        if self._scopes.is_empty() {
527            self._scopes.insert(Scope::Full.as_ref().to_string());
528        }
529
530        #[allow(clippy::single_element_loop)]
531        for &(find_this, param_name) in [("{stateKey}", "stateKey")].iter() {
532            url = params.uri_replacement(url, param_name, find_this, false);
533        }
534        {
535            let to_remove = ["stateKey"];
536            params.remove_params(&to_remove);
537        }
538
539        let url = params.parse_with_url(&url);
540
541        loop {
542            let token = match self
543                .hub
544                .auth
545                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
546                .await
547            {
548                Ok(token) => token,
549                Err(e) => match dlg.token(e) {
550                    Ok(token) => token,
551                    Err(e) => {
552                        dlg.finished(false);
553                        return Err(common::Error::MissingToken(e));
554                    }
555                },
556            };
557            let mut req_result = {
558                let client = &self.hub.client;
559                dlg.pre_request();
560                let mut req_builder = hyper::Request::builder()
561                    .method(hyper::Method::POST)
562                    .uri(url.as_str())
563                    .header(USER_AGENT, self.hub._user_agent.clone());
564
565                if let Some(token) = token.as_ref() {
566                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
567                }
568
569                let request = req_builder
570                    .header(CONTENT_LENGTH, 0_u64)
571                    .body(common::to_body::<String>(None));
572
573                client.request(request.unwrap()).await
574            };
575
576            match req_result {
577                Err(err) => {
578                    if let common::Retry::After(d) = dlg.http_error(&err) {
579                        sleep(d).await;
580                        continue;
581                    }
582                    dlg.finished(false);
583                    return Err(common::Error::HttpError(err));
584                }
585                Ok(res) => {
586                    let (mut parts, body) = res.into_parts();
587                    let mut body = common::Body::new(body);
588                    if !parts.status.is_success() {
589                        let bytes = common::to_bytes(body).await.unwrap_or_default();
590                        let error = serde_json::from_str(&common::to_string(&bytes));
591                        let response = common::to_response(parts, bytes.into());
592
593                        if let common::Retry::After(d) =
594                            dlg.http_failure(&response, error.as_ref().ok())
595                        {
596                            sleep(d).await;
597                            continue;
598                        }
599
600                        dlg.finished(false);
601
602                        return Err(match error {
603                            Ok(value) => common::Error::BadRequest(value),
604                            _ => common::Error::Failure(response),
605                        });
606                    }
607                    let response = {
608                        let bytes = common::to_bytes(body).await.unwrap_or_default();
609                        let encoded = common::to_string(&bytes);
610                        match serde_json::from_str(&encoded) {
611                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
612                            Err(error) => {
613                                dlg.response_json_decode_error(&encoded, &error);
614                                return Err(common::Error::JsonDecodeError(
615                                    encoded.to_string(),
616                                    error,
617                                ));
618                            }
619                        }
620                    };
621
622                    dlg.finished(true);
623                    return Ok(response);
624                }
625            }
626        }
627    }
628
629    /// The key for the data to be retrieved.
630    ///
631    /// Sets the *state key* path property to the given value.
632    ///
633    /// Even though the property as already been set when instantiating this call,
634    /// we provide this method for API completeness.
635    pub fn state_key(mut self, new_value: i32) -> StateClearCall<'a, C> {
636        self._state_key = new_value;
637        self
638    }
639    /// The version of the data to be cleared. Version strings are returned by the server.
640    ///
641    /// Sets the *current data version* query property to the given value.
642    pub fn current_data_version(mut self, new_value: &str) -> StateClearCall<'a, C> {
643        self._current_data_version = Some(new_value.to_string());
644        self
645    }
646    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
647    /// while executing the actual API request.
648    ///
649    /// ````text
650    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
651    /// ````
652    ///
653    /// Sets the *delegate* property to the given value.
654    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> StateClearCall<'a, C> {
655        self._delegate = Some(new_value);
656        self
657    }
658
659    /// Set any additional parameter of the query string used in the request.
660    /// It should be used to set parameters which are not yet available through their own
661    /// setters.
662    ///
663    /// Please note that this method must not be used to set any of the known parameters
664    /// which have their own setter method. If done anyway, the request will fail.
665    ///
666    /// # Additional Parameters
667    ///
668    /// * *alt* (query-string) - Data format for the response.
669    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
670    /// * *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.
671    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
672    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
673    /// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
674    /// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
675    pub fn param<T>(mut self, name: T, value: T) -> StateClearCall<'a, C>
676    where
677        T: AsRef<str>,
678    {
679        self._additional_params
680            .insert(name.as_ref().to_string(), value.as_ref().to_string());
681        self
682    }
683
684    /// Identifies the authorization scope for the method you are building.
685    ///
686    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
687    /// [`Scope::Full`].
688    ///
689    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
690    /// tokens for more than one scope.
691    ///
692    /// Usually there is more than one suitable scope to authorize an operation, some of which may
693    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
694    /// sufficient, a read-write scope will do as well.
695    pub fn add_scope<St>(mut self, scope: St) -> StateClearCall<'a, C>
696    where
697        St: AsRef<str>,
698    {
699        self._scopes.insert(String::from(scope.as_ref()));
700        self
701    }
702    /// Identifies the authorization scope(s) for the method you are building.
703    ///
704    /// See [`Self::add_scope()`] for details.
705    pub fn add_scopes<I, St>(mut self, scopes: I) -> StateClearCall<'a, C>
706    where
707        I: IntoIterator<Item = St>,
708        St: AsRef<str>,
709    {
710        self._scopes
711            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
712        self
713    }
714
715    /// Removes all scopes, and no default scope will be used either.
716    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
717    /// for details).
718    pub fn clear_scopes(mut self) -> StateClearCall<'a, C> {
719        self._scopes.clear();
720        self
721    }
722}
723
724/// Deletes a key and the data associated with it. The key is removed and no longer counts against the key quota. Note that since this method is not safe in the face of concurrent modifications, it should only be used for development and testing purposes. Invoking this method in shipping code can result in data loss and data corruption.
725///
726/// A builder for the *delete* method supported by a *state* resource.
727/// It is not used directly, but through a [`StateMethods`] instance.
728///
729/// # Example
730///
731/// Instantiate a resource method builder
732///
733/// ```test_harness,no_run
734/// # extern crate hyper;
735/// # extern crate hyper_rustls;
736/// # extern crate google_appstate1 as appstate1;
737/// # async fn dox() {
738/// # use appstate1::{AppState, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
739///
740/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
741/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
742/// #     .with_native_roots()
743/// #     .unwrap()
744/// #     .https_only()
745/// #     .enable_http2()
746/// #     .build();
747///
748/// # let executor = hyper_util::rt::TokioExecutor::new();
749/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
750/// #     secret,
751/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
752/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
753/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
754/// #     ),
755/// # ).build().await.unwrap();
756///
757/// # let client = hyper_util::client::legacy::Client::builder(
758/// #     hyper_util::rt::TokioExecutor::new()
759/// # )
760/// # .build(
761/// #     hyper_rustls::HttpsConnectorBuilder::new()
762/// #         .with_native_roots()
763/// #         .unwrap()
764/// #         .https_or_http()
765/// #         .enable_http2()
766/// #         .build()
767/// # );
768/// # let mut hub = AppState::new(client, auth);
769/// // You can configure optional parameters by calling the respective setters at will, and
770/// // execute the final call using `doit()`.
771/// // Values shown here are possibly random and not representative !
772/// let result = hub.states().delete(-2)
773///              .doit().await;
774/// # }
775/// ```
776pub struct StateDeleteCall<'a, C>
777where
778    C: 'a,
779{
780    hub: &'a AppState<C>,
781    _state_key: i32,
782    _delegate: Option<&'a mut dyn common::Delegate>,
783    _additional_params: HashMap<String, String>,
784    _scopes: BTreeSet<String>,
785}
786
787impl<'a, C> common::CallBuilder for StateDeleteCall<'a, C> {}
788
789impl<'a, C> StateDeleteCall<'a, C>
790where
791    C: common::Connector,
792{
793    /// Perform the operation you have build so far.
794    pub async fn doit(mut self) -> common::Result<common::Response> {
795        use std::borrow::Cow;
796        use std::io::{Read, Seek};
797
798        use common::{url::Params, ToParts};
799        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
800
801        let mut dd = common::DefaultDelegate;
802        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
803        dlg.begin(common::MethodInfo {
804            id: "appstate.states.delete",
805            http_method: hyper::Method::DELETE,
806        });
807
808        for &field in ["stateKey"].iter() {
809            if self._additional_params.contains_key(field) {
810                dlg.finished(false);
811                return Err(common::Error::FieldClash(field));
812            }
813        }
814
815        let mut params = Params::with_capacity(2 + self._additional_params.len());
816        params.push("stateKey", self._state_key.to_string());
817
818        params.extend(self._additional_params.iter());
819
820        let mut url = self.hub._base_url.clone() + "states/{stateKey}";
821        if self._scopes.is_empty() {
822            self._scopes.insert(Scope::Full.as_ref().to_string());
823        }
824
825        #[allow(clippy::single_element_loop)]
826        for &(find_this, param_name) in [("{stateKey}", "stateKey")].iter() {
827            url = params.uri_replacement(url, param_name, find_this, false);
828        }
829        {
830            let to_remove = ["stateKey"];
831            params.remove_params(&to_remove);
832        }
833
834        let url = params.parse_with_url(&url);
835
836        loop {
837            let token = match self
838                .hub
839                .auth
840                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
841                .await
842            {
843                Ok(token) => token,
844                Err(e) => match dlg.token(e) {
845                    Ok(token) => token,
846                    Err(e) => {
847                        dlg.finished(false);
848                        return Err(common::Error::MissingToken(e));
849                    }
850                },
851            };
852            let mut req_result = {
853                let client = &self.hub.client;
854                dlg.pre_request();
855                let mut req_builder = hyper::Request::builder()
856                    .method(hyper::Method::DELETE)
857                    .uri(url.as_str())
858                    .header(USER_AGENT, self.hub._user_agent.clone());
859
860                if let Some(token) = token.as_ref() {
861                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
862                }
863
864                let request = req_builder
865                    .header(CONTENT_LENGTH, 0_u64)
866                    .body(common::to_body::<String>(None));
867
868                client.request(request.unwrap()).await
869            };
870
871            match req_result {
872                Err(err) => {
873                    if let common::Retry::After(d) = dlg.http_error(&err) {
874                        sleep(d).await;
875                        continue;
876                    }
877                    dlg.finished(false);
878                    return Err(common::Error::HttpError(err));
879                }
880                Ok(res) => {
881                    let (mut parts, body) = res.into_parts();
882                    let mut body = common::Body::new(body);
883                    if !parts.status.is_success() {
884                        let bytes = common::to_bytes(body).await.unwrap_or_default();
885                        let error = serde_json::from_str(&common::to_string(&bytes));
886                        let response = common::to_response(parts, bytes.into());
887
888                        if let common::Retry::After(d) =
889                            dlg.http_failure(&response, error.as_ref().ok())
890                        {
891                            sleep(d).await;
892                            continue;
893                        }
894
895                        dlg.finished(false);
896
897                        return Err(match error {
898                            Ok(value) => common::Error::BadRequest(value),
899                            _ => common::Error::Failure(response),
900                        });
901                    }
902                    let response = common::Response::from_parts(parts, body);
903
904                    dlg.finished(true);
905                    return Ok(response);
906                }
907            }
908        }
909    }
910
911    /// The key for the data to be retrieved.
912    ///
913    /// Sets the *state key* path property to the given value.
914    ///
915    /// Even though the property as already been set when instantiating this call,
916    /// we provide this method for API completeness.
917    pub fn state_key(mut self, new_value: i32) -> StateDeleteCall<'a, C> {
918        self._state_key = new_value;
919        self
920    }
921    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
922    /// while executing the actual API request.
923    ///
924    /// ````text
925    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
926    /// ````
927    ///
928    /// Sets the *delegate* property to the given value.
929    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> StateDeleteCall<'a, C> {
930        self._delegate = Some(new_value);
931        self
932    }
933
934    /// Set any additional parameter of the query string used in the request.
935    /// It should be used to set parameters which are not yet available through their own
936    /// setters.
937    ///
938    /// Please note that this method must not be used to set any of the known parameters
939    /// which have their own setter method. If done anyway, the request will fail.
940    ///
941    /// # Additional Parameters
942    ///
943    /// * *alt* (query-string) - Data format for the response.
944    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
945    /// * *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.
946    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
947    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
948    /// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
949    /// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
950    pub fn param<T>(mut self, name: T, value: T) -> StateDeleteCall<'a, C>
951    where
952        T: AsRef<str>,
953    {
954        self._additional_params
955            .insert(name.as_ref().to_string(), value.as_ref().to_string());
956        self
957    }
958
959    /// Identifies the authorization scope for the method you are building.
960    ///
961    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
962    /// [`Scope::Full`].
963    ///
964    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
965    /// tokens for more than one scope.
966    ///
967    /// Usually there is more than one suitable scope to authorize an operation, some of which may
968    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
969    /// sufficient, a read-write scope will do as well.
970    pub fn add_scope<St>(mut self, scope: St) -> StateDeleteCall<'a, C>
971    where
972        St: AsRef<str>,
973    {
974        self._scopes.insert(String::from(scope.as_ref()));
975        self
976    }
977    /// Identifies the authorization scope(s) for the method you are building.
978    ///
979    /// See [`Self::add_scope()`] for details.
980    pub fn add_scopes<I, St>(mut self, scopes: I) -> StateDeleteCall<'a, C>
981    where
982        I: IntoIterator<Item = St>,
983        St: AsRef<str>,
984    {
985        self._scopes
986            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
987        self
988    }
989
990    /// Removes all scopes, and no default scope will be used either.
991    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
992    /// for details).
993    pub fn clear_scopes(mut self) -> StateDeleteCall<'a, C> {
994        self._scopes.clear();
995        self
996    }
997}
998
999/// Retrieves the data corresponding to the passed key. If the key does not exist on the server, an HTTP 404 will be returned.
1000///
1001/// A builder for the *get* method supported by a *state* resource.
1002/// It is not used directly, but through a [`StateMethods`] instance.
1003///
1004/// # Example
1005///
1006/// Instantiate a resource method builder
1007///
1008/// ```test_harness,no_run
1009/// # extern crate hyper;
1010/// # extern crate hyper_rustls;
1011/// # extern crate google_appstate1 as appstate1;
1012/// # async fn dox() {
1013/// # use appstate1::{AppState, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1014///
1015/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1016/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1017/// #     .with_native_roots()
1018/// #     .unwrap()
1019/// #     .https_only()
1020/// #     .enable_http2()
1021/// #     .build();
1022///
1023/// # let executor = hyper_util::rt::TokioExecutor::new();
1024/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1025/// #     secret,
1026/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1027/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1028/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1029/// #     ),
1030/// # ).build().await.unwrap();
1031///
1032/// # let client = hyper_util::client::legacy::Client::builder(
1033/// #     hyper_util::rt::TokioExecutor::new()
1034/// # )
1035/// # .build(
1036/// #     hyper_rustls::HttpsConnectorBuilder::new()
1037/// #         .with_native_roots()
1038/// #         .unwrap()
1039/// #         .https_or_http()
1040/// #         .enable_http2()
1041/// #         .build()
1042/// # );
1043/// # let mut hub = AppState::new(client, auth);
1044/// // You can configure optional parameters by calling the respective setters at will, and
1045/// // execute the final call using `doit()`.
1046/// // Values shown here are possibly random and not representative !
1047/// let result = hub.states().get(-59)
1048///              .doit().await;
1049/// # }
1050/// ```
1051pub struct StateGetCall<'a, C>
1052where
1053    C: 'a,
1054{
1055    hub: &'a AppState<C>,
1056    _state_key: i32,
1057    _delegate: Option<&'a mut dyn common::Delegate>,
1058    _additional_params: HashMap<String, String>,
1059    _scopes: BTreeSet<String>,
1060}
1061
1062impl<'a, C> common::CallBuilder for StateGetCall<'a, C> {}
1063
1064impl<'a, C> StateGetCall<'a, C>
1065where
1066    C: common::Connector,
1067{
1068    /// Perform the operation you have build so far.
1069    pub async fn doit(mut self) -> common::Result<(common::Response, GetResponse)> {
1070        use std::borrow::Cow;
1071        use std::io::{Read, Seek};
1072
1073        use common::{url::Params, ToParts};
1074        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1075
1076        let mut dd = common::DefaultDelegate;
1077        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1078        dlg.begin(common::MethodInfo {
1079            id: "appstate.states.get",
1080            http_method: hyper::Method::GET,
1081        });
1082
1083        for &field in ["alt", "stateKey"].iter() {
1084            if self._additional_params.contains_key(field) {
1085                dlg.finished(false);
1086                return Err(common::Error::FieldClash(field));
1087            }
1088        }
1089
1090        let mut params = Params::with_capacity(3 + self._additional_params.len());
1091        params.push("stateKey", self._state_key.to_string());
1092
1093        params.extend(self._additional_params.iter());
1094
1095        params.push("alt", "json");
1096        let mut url = self.hub._base_url.clone() + "states/{stateKey}";
1097        if self._scopes.is_empty() {
1098            self._scopes.insert(Scope::Full.as_ref().to_string());
1099        }
1100
1101        #[allow(clippy::single_element_loop)]
1102        for &(find_this, param_name) in [("{stateKey}", "stateKey")].iter() {
1103            url = params.uri_replacement(url, param_name, find_this, false);
1104        }
1105        {
1106            let to_remove = ["stateKey"];
1107            params.remove_params(&to_remove);
1108        }
1109
1110        let url = params.parse_with_url(&url);
1111
1112        loop {
1113            let token = match self
1114                .hub
1115                .auth
1116                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1117                .await
1118            {
1119                Ok(token) => token,
1120                Err(e) => match dlg.token(e) {
1121                    Ok(token) => token,
1122                    Err(e) => {
1123                        dlg.finished(false);
1124                        return Err(common::Error::MissingToken(e));
1125                    }
1126                },
1127            };
1128            let mut req_result = {
1129                let client = &self.hub.client;
1130                dlg.pre_request();
1131                let mut req_builder = hyper::Request::builder()
1132                    .method(hyper::Method::GET)
1133                    .uri(url.as_str())
1134                    .header(USER_AGENT, self.hub._user_agent.clone());
1135
1136                if let Some(token) = token.as_ref() {
1137                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1138                }
1139
1140                let request = req_builder
1141                    .header(CONTENT_LENGTH, 0_u64)
1142                    .body(common::to_body::<String>(None));
1143
1144                client.request(request.unwrap()).await
1145            };
1146
1147            match req_result {
1148                Err(err) => {
1149                    if let common::Retry::After(d) = dlg.http_error(&err) {
1150                        sleep(d).await;
1151                        continue;
1152                    }
1153                    dlg.finished(false);
1154                    return Err(common::Error::HttpError(err));
1155                }
1156                Ok(res) => {
1157                    let (mut parts, body) = res.into_parts();
1158                    let mut body = common::Body::new(body);
1159                    if !parts.status.is_success() {
1160                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1161                        let error = serde_json::from_str(&common::to_string(&bytes));
1162                        let response = common::to_response(parts, bytes.into());
1163
1164                        if let common::Retry::After(d) =
1165                            dlg.http_failure(&response, error.as_ref().ok())
1166                        {
1167                            sleep(d).await;
1168                            continue;
1169                        }
1170
1171                        dlg.finished(false);
1172
1173                        return Err(match error {
1174                            Ok(value) => common::Error::BadRequest(value),
1175                            _ => common::Error::Failure(response),
1176                        });
1177                    }
1178                    let response = {
1179                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1180                        let encoded = common::to_string(&bytes);
1181                        match serde_json::from_str(&encoded) {
1182                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1183                            Err(error) => {
1184                                dlg.response_json_decode_error(&encoded, &error);
1185                                return Err(common::Error::JsonDecodeError(
1186                                    encoded.to_string(),
1187                                    error,
1188                                ));
1189                            }
1190                        }
1191                    };
1192
1193                    dlg.finished(true);
1194                    return Ok(response);
1195                }
1196            }
1197        }
1198    }
1199
1200    /// The key for the data to be retrieved.
1201    ///
1202    /// Sets the *state key* path property to the given value.
1203    ///
1204    /// Even though the property as already been set when instantiating this call,
1205    /// we provide this method for API completeness.
1206    pub fn state_key(mut self, new_value: i32) -> StateGetCall<'a, C> {
1207        self._state_key = new_value;
1208        self
1209    }
1210    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1211    /// while executing the actual API request.
1212    ///
1213    /// ````text
1214    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1215    /// ````
1216    ///
1217    /// Sets the *delegate* property to the given value.
1218    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> StateGetCall<'a, C> {
1219        self._delegate = Some(new_value);
1220        self
1221    }
1222
1223    /// Set any additional parameter of the query string used in the request.
1224    /// It should be used to set parameters which are not yet available through their own
1225    /// setters.
1226    ///
1227    /// Please note that this method must not be used to set any of the known parameters
1228    /// which have their own setter method. If done anyway, the request will fail.
1229    ///
1230    /// # Additional Parameters
1231    ///
1232    /// * *alt* (query-string) - Data format for the response.
1233    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1234    /// * *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.
1235    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1236    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1237    /// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
1238    /// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
1239    pub fn param<T>(mut self, name: T, value: T) -> StateGetCall<'a, C>
1240    where
1241        T: AsRef<str>,
1242    {
1243        self._additional_params
1244            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1245        self
1246    }
1247
1248    /// Identifies the authorization scope for the method you are building.
1249    ///
1250    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1251    /// [`Scope::Full`].
1252    ///
1253    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1254    /// tokens for more than one scope.
1255    ///
1256    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1257    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1258    /// sufficient, a read-write scope will do as well.
1259    pub fn add_scope<St>(mut self, scope: St) -> StateGetCall<'a, C>
1260    where
1261        St: AsRef<str>,
1262    {
1263        self._scopes.insert(String::from(scope.as_ref()));
1264        self
1265    }
1266    /// Identifies the authorization scope(s) for the method you are building.
1267    ///
1268    /// See [`Self::add_scope()`] for details.
1269    pub fn add_scopes<I, St>(mut self, scopes: I) -> StateGetCall<'a, C>
1270    where
1271        I: IntoIterator<Item = St>,
1272        St: AsRef<str>,
1273    {
1274        self._scopes
1275            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1276        self
1277    }
1278
1279    /// Removes all scopes, and no default scope will be used either.
1280    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1281    /// for details).
1282    pub fn clear_scopes(mut self) -> StateGetCall<'a, C> {
1283        self._scopes.clear();
1284        self
1285    }
1286}
1287
1288/// Lists all the states keys, and optionally the state data.
1289///
1290/// A builder for the *list* method supported by a *state* resource.
1291/// It is not used directly, but through a [`StateMethods`] instance.
1292///
1293/// # Example
1294///
1295/// Instantiate a resource method builder
1296///
1297/// ```test_harness,no_run
1298/// # extern crate hyper;
1299/// # extern crate hyper_rustls;
1300/// # extern crate google_appstate1 as appstate1;
1301/// # async fn dox() {
1302/// # use appstate1::{AppState, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1303///
1304/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1305/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1306/// #     .with_native_roots()
1307/// #     .unwrap()
1308/// #     .https_only()
1309/// #     .enable_http2()
1310/// #     .build();
1311///
1312/// # let executor = hyper_util::rt::TokioExecutor::new();
1313/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1314/// #     secret,
1315/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1316/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1317/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1318/// #     ),
1319/// # ).build().await.unwrap();
1320///
1321/// # let client = hyper_util::client::legacy::Client::builder(
1322/// #     hyper_util::rt::TokioExecutor::new()
1323/// # )
1324/// # .build(
1325/// #     hyper_rustls::HttpsConnectorBuilder::new()
1326/// #         .with_native_roots()
1327/// #         .unwrap()
1328/// #         .https_or_http()
1329/// #         .enable_http2()
1330/// #         .build()
1331/// # );
1332/// # let mut hub = AppState::new(client, auth);
1333/// // You can configure optional parameters by calling the respective setters at will, and
1334/// // execute the final call using `doit()`.
1335/// // Values shown here are possibly random and not representative !
1336/// let result = hub.states().list()
1337///              .include_data(true)
1338///              .doit().await;
1339/// # }
1340/// ```
1341pub struct StateListCall<'a, C>
1342where
1343    C: 'a,
1344{
1345    hub: &'a AppState<C>,
1346    _include_data: Option<bool>,
1347    _delegate: Option<&'a mut dyn common::Delegate>,
1348    _additional_params: HashMap<String, String>,
1349    _scopes: BTreeSet<String>,
1350}
1351
1352impl<'a, C> common::CallBuilder for StateListCall<'a, C> {}
1353
1354impl<'a, C> StateListCall<'a, C>
1355where
1356    C: common::Connector,
1357{
1358    /// Perform the operation you have build so far.
1359    pub async fn doit(mut self) -> common::Result<(common::Response, ListResponse)> {
1360        use std::borrow::Cow;
1361        use std::io::{Read, Seek};
1362
1363        use common::{url::Params, ToParts};
1364        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1365
1366        let mut dd = common::DefaultDelegate;
1367        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1368        dlg.begin(common::MethodInfo {
1369            id: "appstate.states.list",
1370            http_method: hyper::Method::GET,
1371        });
1372
1373        for &field in ["alt", "includeData"].iter() {
1374            if self._additional_params.contains_key(field) {
1375                dlg.finished(false);
1376                return Err(common::Error::FieldClash(field));
1377            }
1378        }
1379
1380        let mut params = Params::with_capacity(3 + self._additional_params.len());
1381        if let Some(value) = self._include_data.as_ref() {
1382            params.push("includeData", value.to_string());
1383        }
1384
1385        params.extend(self._additional_params.iter());
1386
1387        params.push("alt", "json");
1388        let mut url = self.hub._base_url.clone() + "states";
1389        if self._scopes.is_empty() {
1390            self._scopes.insert(Scope::Full.as_ref().to_string());
1391        }
1392
1393        let url = params.parse_with_url(&url);
1394
1395        loop {
1396            let token = match self
1397                .hub
1398                .auth
1399                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1400                .await
1401            {
1402                Ok(token) => token,
1403                Err(e) => match dlg.token(e) {
1404                    Ok(token) => token,
1405                    Err(e) => {
1406                        dlg.finished(false);
1407                        return Err(common::Error::MissingToken(e));
1408                    }
1409                },
1410            };
1411            let mut req_result = {
1412                let client = &self.hub.client;
1413                dlg.pre_request();
1414                let mut req_builder = hyper::Request::builder()
1415                    .method(hyper::Method::GET)
1416                    .uri(url.as_str())
1417                    .header(USER_AGENT, self.hub._user_agent.clone());
1418
1419                if let Some(token) = token.as_ref() {
1420                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1421                }
1422
1423                let request = req_builder
1424                    .header(CONTENT_LENGTH, 0_u64)
1425                    .body(common::to_body::<String>(None));
1426
1427                client.request(request.unwrap()).await
1428            };
1429
1430            match req_result {
1431                Err(err) => {
1432                    if let common::Retry::After(d) = dlg.http_error(&err) {
1433                        sleep(d).await;
1434                        continue;
1435                    }
1436                    dlg.finished(false);
1437                    return Err(common::Error::HttpError(err));
1438                }
1439                Ok(res) => {
1440                    let (mut parts, body) = res.into_parts();
1441                    let mut body = common::Body::new(body);
1442                    if !parts.status.is_success() {
1443                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1444                        let error = serde_json::from_str(&common::to_string(&bytes));
1445                        let response = common::to_response(parts, bytes.into());
1446
1447                        if let common::Retry::After(d) =
1448                            dlg.http_failure(&response, error.as_ref().ok())
1449                        {
1450                            sleep(d).await;
1451                            continue;
1452                        }
1453
1454                        dlg.finished(false);
1455
1456                        return Err(match error {
1457                            Ok(value) => common::Error::BadRequest(value),
1458                            _ => common::Error::Failure(response),
1459                        });
1460                    }
1461                    let response = {
1462                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1463                        let encoded = common::to_string(&bytes);
1464                        match serde_json::from_str(&encoded) {
1465                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1466                            Err(error) => {
1467                                dlg.response_json_decode_error(&encoded, &error);
1468                                return Err(common::Error::JsonDecodeError(
1469                                    encoded.to_string(),
1470                                    error,
1471                                ));
1472                            }
1473                        }
1474                    };
1475
1476                    dlg.finished(true);
1477                    return Ok(response);
1478                }
1479            }
1480        }
1481    }
1482
1483    /// Whether to include the full data in addition to the version number
1484    ///
1485    /// Sets the *include data* query property to the given value.
1486    pub fn include_data(mut self, new_value: bool) -> StateListCall<'a, C> {
1487        self._include_data = Some(new_value);
1488        self
1489    }
1490    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1491    /// while executing the actual API request.
1492    ///
1493    /// ````text
1494    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1495    /// ````
1496    ///
1497    /// Sets the *delegate* property to the given value.
1498    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> StateListCall<'a, C> {
1499        self._delegate = Some(new_value);
1500        self
1501    }
1502
1503    /// Set any additional parameter of the query string used in the request.
1504    /// It should be used to set parameters which are not yet available through their own
1505    /// setters.
1506    ///
1507    /// Please note that this method must not be used to set any of the known parameters
1508    /// which have their own setter method. If done anyway, the request will fail.
1509    ///
1510    /// # Additional Parameters
1511    ///
1512    /// * *alt* (query-string) - Data format for the response.
1513    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1514    /// * *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.
1515    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1516    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1517    /// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
1518    /// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
1519    pub fn param<T>(mut self, name: T, value: T) -> StateListCall<'a, C>
1520    where
1521        T: AsRef<str>,
1522    {
1523        self._additional_params
1524            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1525        self
1526    }
1527
1528    /// Identifies the authorization scope for the method you are building.
1529    ///
1530    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1531    /// [`Scope::Full`].
1532    ///
1533    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1534    /// tokens for more than one scope.
1535    ///
1536    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1537    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1538    /// sufficient, a read-write scope will do as well.
1539    pub fn add_scope<St>(mut self, scope: St) -> StateListCall<'a, C>
1540    where
1541        St: AsRef<str>,
1542    {
1543        self._scopes.insert(String::from(scope.as_ref()));
1544        self
1545    }
1546    /// Identifies the authorization scope(s) for the method you are building.
1547    ///
1548    /// See [`Self::add_scope()`] for details.
1549    pub fn add_scopes<I, St>(mut self, scopes: I) -> StateListCall<'a, C>
1550    where
1551        I: IntoIterator<Item = St>,
1552        St: AsRef<str>,
1553    {
1554        self._scopes
1555            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1556        self
1557    }
1558
1559    /// Removes all scopes, and no default scope will be used either.
1560    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1561    /// for details).
1562    pub fn clear_scopes(mut self) -> StateListCall<'a, C> {
1563        self._scopes.clear();
1564        self
1565    }
1566}
1567
1568/// Update the data associated with the input key if and only if the passed version matches the currently stored version. This method is safe in the face of concurrent writes. Maximum per-key size is 128KB.
1569///
1570/// A builder for the *update* method supported by a *state* resource.
1571/// It is not used directly, but through a [`StateMethods`] instance.
1572///
1573/// # Example
1574///
1575/// Instantiate a resource method builder
1576///
1577/// ```test_harness,no_run
1578/// # extern crate hyper;
1579/// # extern crate hyper_rustls;
1580/// # extern crate google_appstate1 as appstate1;
1581/// use appstate1::api::UpdateRequest;
1582/// # async fn dox() {
1583/// # use appstate1::{AppState, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1584///
1585/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1586/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1587/// #     .with_native_roots()
1588/// #     .unwrap()
1589/// #     .https_only()
1590/// #     .enable_http2()
1591/// #     .build();
1592///
1593/// # let executor = hyper_util::rt::TokioExecutor::new();
1594/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1595/// #     secret,
1596/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1597/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1598/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1599/// #     ),
1600/// # ).build().await.unwrap();
1601///
1602/// # let client = hyper_util::client::legacy::Client::builder(
1603/// #     hyper_util::rt::TokioExecutor::new()
1604/// # )
1605/// # .build(
1606/// #     hyper_rustls::HttpsConnectorBuilder::new()
1607/// #         .with_native_roots()
1608/// #         .unwrap()
1609/// #         .https_or_http()
1610/// #         .enable_http2()
1611/// #         .build()
1612/// # );
1613/// # let mut hub = AppState::new(client, auth);
1614/// // As the method needs a request, you would usually fill it with the desired information
1615/// // into the respective structure. Some of the parts shown here might not be applicable !
1616/// // Values shown here are possibly random and not representative !
1617/// let mut req = UpdateRequest::default();
1618///
1619/// // You can configure optional parameters by calling the respective setters at will, and
1620/// // execute the final call using `doit()`.
1621/// // Values shown here are possibly random and not representative !
1622/// let result = hub.states().update(req, -20)
1623///              .current_state_version("ipsum")
1624///              .doit().await;
1625/// # }
1626/// ```
1627pub struct StateUpdateCall<'a, C>
1628where
1629    C: 'a,
1630{
1631    hub: &'a AppState<C>,
1632    _request: UpdateRequest,
1633    _state_key: i32,
1634    _current_state_version: Option<String>,
1635    _delegate: Option<&'a mut dyn common::Delegate>,
1636    _additional_params: HashMap<String, String>,
1637    _scopes: BTreeSet<String>,
1638}
1639
1640impl<'a, C> common::CallBuilder for StateUpdateCall<'a, C> {}
1641
1642impl<'a, C> StateUpdateCall<'a, C>
1643where
1644    C: common::Connector,
1645{
1646    /// Perform the operation you have build so far.
1647    pub async fn doit(mut self) -> common::Result<(common::Response, WriteResult)> {
1648        use std::borrow::Cow;
1649        use std::io::{Read, Seek};
1650
1651        use common::{url::Params, ToParts};
1652        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1653
1654        let mut dd = common::DefaultDelegate;
1655        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1656        dlg.begin(common::MethodInfo {
1657            id: "appstate.states.update",
1658            http_method: hyper::Method::PUT,
1659        });
1660
1661        for &field in ["alt", "stateKey", "currentStateVersion"].iter() {
1662            if self._additional_params.contains_key(field) {
1663                dlg.finished(false);
1664                return Err(common::Error::FieldClash(field));
1665            }
1666        }
1667
1668        let mut params = Params::with_capacity(5 + self._additional_params.len());
1669        params.push("stateKey", self._state_key.to_string());
1670        if let Some(value) = self._current_state_version.as_ref() {
1671            params.push("currentStateVersion", value);
1672        }
1673
1674        params.extend(self._additional_params.iter());
1675
1676        params.push("alt", "json");
1677        let mut url = self.hub._base_url.clone() + "states/{stateKey}";
1678        if self._scopes.is_empty() {
1679            self._scopes.insert(Scope::Full.as_ref().to_string());
1680        }
1681
1682        #[allow(clippy::single_element_loop)]
1683        for &(find_this, param_name) in [("{stateKey}", "stateKey")].iter() {
1684            url = params.uri_replacement(url, param_name, find_this, false);
1685        }
1686        {
1687            let to_remove = ["stateKey"];
1688            params.remove_params(&to_remove);
1689        }
1690
1691        let url = params.parse_with_url(&url);
1692
1693        let mut json_mime_type = mime::APPLICATION_JSON;
1694        let mut request_value_reader = {
1695            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1696            common::remove_json_null_values(&mut value);
1697            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1698            serde_json::to_writer(&mut dst, &value).unwrap();
1699            dst
1700        };
1701        let request_size = request_value_reader
1702            .seek(std::io::SeekFrom::End(0))
1703            .unwrap();
1704        request_value_reader
1705            .seek(std::io::SeekFrom::Start(0))
1706            .unwrap();
1707
1708        loop {
1709            let token = match self
1710                .hub
1711                .auth
1712                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1713                .await
1714            {
1715                Ok(token) => token,
1716                Err(e) => match dlg.token(e) {
1717                    Ok(token) => token,
1718                    Err(e) => {
1719                        dlg.finished(false);
1720                        return Err(common::Error::MissingToken(e));
1721                    }
1722                },
1723            };
1724            request_value_reader
1725                .seek(std::io::SeekFrom::Start(0))
1726                .unwrap();
1727            let mut req_result = {
1728                let client = &self.hub.client;
1729                dlg.pre_request();
1730                let mut req_builder = hyper::Request::builder()
1731                    .method(hyper::Method::PUT)
1732                    .uri(url.as_str())
1733                    .header(USER_AGENT, self.hub._user_agent.clone());
1734
1735                if let Some(token) = token.as_ref() {
1736                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1737                }
1738
1739                let request = req_builder
1740                    .header(CONTENT_TYPE, json_mime_type.to_string())
1741                    .header(CONTENT_LENGTH, request_size as u64)
1742                    .body(common::to_body(
1743                        request_value_reader.get_ref().clone().into(),
1744                    ));
1745
1746                client.request(request.unwrap()).await
1747            };
1748
1749            match req_result {
1750                Err(err) => {
1751                    if let common::Retry::After(d) = dlg.http_error(&err) {
1752                        sleep(d).await;
1753                        continue;
1754                    }
1755                    dlg.finished(false);
1756                    return Err(common::Error::HttpError(err));
1757                }
1758                Ok(res) => {
1759                    let (mut parts, body) = res.into_parts();
1760                    let mut body = common::Body::new(body);
1761                    if !parts.status.is_success() {
1762                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1763                        let error = serde_json::from_str(&common::to_string(&bytes));
1764                        let response = common::to_response(parts, bytes.into());
1765
1766                        if let common::Retry::After(d) =
1767                            dlg.http_failure(&response, error.as_ref().ok())
1768                        {
1769                            sleep(d).await;
1770                            continue;
1771                        }
1772
1773                        dlg.finished(false);
1774
1775                        return Err(match error {
1776                            Ok(value) => common::Error::BadRequest(value),
1777                            _ => common::Error::Failure(response),
1778                        });
1779                    }
1780                    let response = {
1781                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1782                        let encoded = common::to_string(&bytes);
1783                        match serde_json::from_str(&encoded) {
1784                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1785                            Err(error) => {
1786                                dlg.response_json_decode_error(&encoded, &error);
1787                                return Err(common::Error::JsonDecodeError(
1788                                    encoded.to_string(),
1789                                    error,
1790                                ));
1791                            }
1792                        }
1793                    };
1794
1795                    dlg.finished(true);
1796                    return Ok(response);
1797                }
1798            }
1799        }
1800    }
1801
1802    ///
1803    /// Sets the *request* property to the given value.
1804    ///
1805    /// Even though the property as already been set when instantiating this call,
1806    /// we provide this method for API completeness.
1807    pub fn request(mut self, new_value: UpdateRequest) -> StateUpdateCall<'a, C> {
1808        self._request = new_value;
1809        self
1810    }
1811    /// The key for the data to be retrieved.
1812    ///
1813    /// Sets the *state key* path property to the given value.
1814    ///
1815    /// Even though the property as already been set when instantiating this call,
1816    /// we provide this method for API completeness.
1817    pub fn state_key(mut self, new_value: i32) -> StateUpdateCall<'a, C> {
1818        self._state_key = new_value;
1819        self
1820    }
1821    /// The version of the app state your application is attempting to update. If this does not match the current version, this method will return a conflict error. If there is no data stored on the server for this key, the update will succeed irrespective of the value of this parameter.
1822    ///
1823    /// Sets the *current state version* query property to the given value.
1824    pub fn current_state_version(mut self, new_value: &str) -> StateUpdateCall<'a, C> {
1825        self._current_state_version = Some(new_value.to_string());
1826        self
1827    }
1828    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1829    /// while executing the actual API request.
1830    ///
1831    /// ````text
1832    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1833    /// ````
1834    ///
1835    /// Sets the *delegate* property to the given value.
1836    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> StateUpdateCall<'a, C> {
1837        self._delegate = Some(new_value);
1838        self
1839    }
1840
1841    /// Set any additional parameter of the query string used in the request.
1842    /// It should be used to set parameters which are not yet available through their own
1843    /// setters.
1844    ///
1845    /// Please note that this method must not be used to set any of the known parameters
1846    /// which have their own setter method. If done anyway, the request will fail.
1847    ///
1848    /// # Additional Parameters
1849    ///
1850    /// * *alt* (query-string) - Data format for the response.
1851    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1852    /// * *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.
1853    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1854    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1855    /// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
1856    /// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
1857    pub fn param<T>(mut self, name: T, value: T) -> StateUpdateCall<'a, C>
1858    where
1859        T: AsRef<str>,
1860    {
1861        self._additional_params
1862            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1863        self
1864    }
1865
1866    /// Identifies the authorization scope for the method you are building.
1867    ///
1868    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1869    /// [`Scope::Full`].
1870    ///
1871    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1872    /// tokens for more than one scope.
1873    ///
1874    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1875    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1876    /// sufficient, a read-write scope will do as well.
1877    pub fn add_scope<St>(mut self, scope: St) -> StateUpdateCall<'a, C>
1878    where
1879        St: AsRef<str>,
1880    {
1881        self._scopes.insert(String::from(scope.as_ref()));
1882        self
1883    }
1884    /// Identifies the authorization scope(s) for the method you are building.
1885    ///
1886    /// See [`Self::add_scope()`] for details.
1887    pub fn add_scopes<I, St>(mut self, scopes: I) -> StateUpdateCall<'a, C>
1888    where
1889        I: IntoIterator<Item = St>,
1890        St: AsRef<str>,
1891    {
1892        self._scopes
1893            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1894        self
1895    }
1896
1897    /// Removes all scopes, and no default scope will be used either.
1898    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1899    /// for details).
1900    pub fn clear_scopes(mut self) -> StateUpdateCall<'a, C> {
1901        self._scopes.clear();
1902        self
1903    }
1904}