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