rusoto_personalize_runtime/
generated.rs

1// =================================================================
2//
3//                           * WARNING *
4//
5//                    This file is generated!
6//
7//  Changes made to this file will be overwritten. If changes are
8//  required to the generated code, the service_crategen project
9//  must be updated to generate the changes.
10//
11// =================================================================
12
13use std::error::Error;
14use std::fmt;
15
16use async_trait::async_trait;
17use rusoto_core::credential::ProvideAwsCredentials;
18use rusoto_core::region;
19use rusoto_core::request::{BufferedHttpResponse, DispatchSignedRequest};
20use rusoto_core::{Client, RusotoError};
21
22use rusoto_core::proto;
23use rusoto_core::signature::SignedRequest;
24#[allow(unused_imports)]
25use serde::{Deserialize, Serialize};
26use serde_json;
27#[derive(Clone, Debug, Default, PartialEq, Serialize)]
28#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
29pub struct GetPersonalizedRankingRequest {
30    /// <p>The Amazon Resource Name (ARN) of the campaign to use for generating the personalized ranking.</p>
31    #[serde(rename = "campaignArn")]
32    pub campaign_arn: String,
33    /// <p>The contextual metadata to use when getting recommendations. Contextual metadata includes any interaction information that might be relevant when getting a user's recommendations, such as the user's current location or device type.</p>
34    #[serde(rename = "context")]
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub context: Option<::std::collections::HashMap<String, String>>,
37    /// <p>A list of items (itemId's) to rank. If an item was not included in the training dataset, the item is appended to the end of the reranked list. The maximum is 500.</p>
38    #[serde(rename = "inputList")]
39    pub input_list: Vec<String>,
40    /// <p>The user for which you want the campaign to provide a personalized ranking.</p>
41    #[serde(rename = "userId")]
42    pub user_id: String,
43}
44
45#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
46#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
47pub struct GetPersonalizedRankingResponse {
48    /// <p>A list of items in order of most likely interest to the user. The maximum is 500.</p>
49    #[serde(rename = "personalizedRanking")]
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub personalized_ranking: Option<Vec<PredictedItem>>,
52}
53
54#[derive(Clone, Debug, Default, PartialEq, Serialize)]
55#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
56pub struct GetRecommendationsRequest {
57    /// <p>The Amazon Resource Name (ARN) of the campaign to use for getting recommendations.</p>
58    #[serde(rename = "campaignArn")]
59    pub campaign_arn: String,
60    /// <p>The contextual metadata to use when getting recommendations. Contextual metadata includes any interaction information that might be relevant when getting a user's recommendations, such as the user's current location or device type.</p>
61    #[serde(rename = "context")]
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub context: Option<::std::collections::HashMap<String, String>>,
64    /// <p>The ARN of the filter to apply to the returned recommendations. For more information, see Using Filters with Amazon Personalize.</p>
65    #[serde(rename = "filterArn")]
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub filter_arn: Option<String>,
68    /// <p>The item ID to provide recommendations for.</p> <p>Required for <code>RELATED_ITEMS</code> recipe type.</p>
69    #[serde(rename = "itemId")]
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub item_id: Option<String>,
72    /// <p>The number of results to return. The default is 25. The maximum is 500.</p>
73    #[serde(rename = "numResults")]
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub num_results: Option<i64>,
76    /// <p>The user ID to provide recommendations for.</p> <p>Required for <code>USER_PERSONALIZATION</code> recipe type.</p>
77    #[serde(rename = "userId")]
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub user_id: Option<String>,
80}
81
82#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
83#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
84pub struct GetRecommendationsResponse {
85    /// <p>A list of recommendations sorted in ascending order by prediction score. There can be a maximum of 500 items in the list.</p>
86    #[serde(rename = "itemList")]
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub item_list: Option<Vec<PredictedItem>>,
89}
90
91/// <p>An object that identifies an item.</p> <p>The and APIs return a list of <code>PredictedItem</code>s.</p>
92#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
93#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
94pub struct PredictedItem {
95    /// <p>The recommended item ID.</p>
96    #[serde(rename = "itemId")]
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub item_id: Option<String>,
99    /// <p>A numeric representation of the model's certainty that the item will be the next user selection. For more information on scoring logic, see <a>how-scores-work</a>.</p>
100    #[serde(rename = "score")]
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub score: Option<f64>,
103}
104
105/// Errors returned by GetPersonalizedRanking
106#[derive(Debug, PartialEq)]
107pub enum GetPersonalizedRankingError {
108    /// <p>Provide a valid value for the field or parameter.</p>
109    InvalidInput(String),
110    /// <p>The specified resource does not exist.</p>
111    ResourceNotFound(String),
112}
113
114impl GetPersonalizedRankingError {
115    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetPersonalizedRankingError> {
116        if let Some(err) = proto::json::Error::parse_rest(&res) {
117            match err.typ.as_str() {
118                "InvalidInputException" => {
119                    return RusotoError::Service(GetPersonalizedRankingError::InvalidInput(err.msg))
120                }
121                "ResourceNotFoundException" => {
122                    return RusotoError::Service(GetPersonalizedRankingError::ResourceNotFound(
123                        err.msg,
124                    ))
125                }
126                "ValidationException" => return RusotoError::Validation(err.msg),
127                _ => {}
128            }
129        }
130        RusotoError::Unknown(res)
131    }
132}
133impl fmt::Display for GetPersonalizedRankingError {
134    #[allow(unused_variables)]
135    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
136        match *self {
137            GetPersonalizedRankingError::InvalidInput(ref cause) => write!(f, "{}", cause),
138            GetPersonalizedRankingError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
139        }
140    }
141}
142impl Error for GetPersonalizedRankingError {}
143/// Errors returned by GetRecommendations
144#[derive(Debug, PartialEq)]
145pub enum GetRecommendationsError {
146    /// <p>Provide a valid value for the field or parameter.</p>
147    InvalidInput(String),
148    /// <p>The specified resource does not exist.</p>
149    ResourceNotFound(String),
150}
151
152impl GetRecommendationsError {
153    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetRecommendationsError> {
154        if let Some(err) = proto::json::Error::parse_rest(&res) {
155            match err.typ.as_str() {
156                "InvalidInputException" => {
157                    return RusotoError::Service(GetRecommendationsError::InvalidInput(err.msg))
158                }
159                "ResourceNotFoundException" => {
160                    return RusotoError::Service(GetRecommendationsError::ResourceNotFound(err.msg))
161                }
162                "ValidationException" => return RusotoError::Validation(err.msg),
163                _ => {}
164            }
165        }
166        RusotoError::Unknown(res)
167    }
168}
169impl fmt::Display for GetRecommendationsError {
170    #[allow(unused_variables)]
171    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
172        match *self {
173            GetRecommendationsError::InvalidInput(ref cause) => write!(f, "{}", cause),
174            GetRecommendationsError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
175        }
176    }
177}
178impl Error for GetRecommendationsError {}
179/// Trait representing the capabilities of the Amazon Personalize Runtime API. Amazon Personalize Runtime clients implement this trait.
180#[async_trait]
181pub trait PersonalizeRuntime {
182    /// <p><p>Re-ranks a list of recommended items for the given user. The first item in the list is deemed the most likely item to be of interest to the user.</p> <note> <p>The solution backing the campaign must have been created using a recipe of type PERSONALIZED_RANKING.</p> </note></p>
183    async fn get_personalized_ranking(
184        &self,
185        input: GetPersonalizedRankingRequest,
186    ) -> Result<GetPersonalizedRankingResponse, RusotoError<GetPersonalizedRankingError>>;
187
188    /// <p><p>Returns a list of recommended items. The required input depends on the recipe type used to create the solution backing the campaign, as follows:</p> <ul> <li> <p>RELATED<em>ITEMS - <code>itemId</code> required, <code>userId</code> not used</p> </li> <li> <p>USER</em>PERSONALIZATION - <code>itemId</code> optional, <code>userId</code> required</p> </li> </ul> <note> <p>Campaigns that are backed by a solution created using a recipe of type PERSONALIZED_RANKING use the API.</p> </note></p>
189    async fn get_recommendations(
190        &self,
191        input: GetRecommendationsRequest,
192    ) -> Result<GetRecommendationsResponse, RusotoError<GetRecommendationsError>>;
193}
194/// A client for the Amazon Personalize Runtime API.
195#[derive(Clone)]
196pub struct PersonalizeRuntimeClient {
197    client: Client,
198    region: region::Region,
199}
200
201impl PersonalizeRuntimeClient {
202    /// Creates a client backed by the default tokio event loop.
203    ///
204    /// The client will use the default credentials provider and tls client.
205    pub fn new(region: region::Region) -> PersonalizeRuntimeClient {
206        PersonalizeRuntimeClient {
207            client: Client::shared(),
208            region,
209        }
210    }
211
212    pub fn new_with<P, D>(
213        request_dispatcher: D,
214        credentials_provider: P,
215        region: region::Region,
216    ) -> PersonalizeRuntimeClient
217    where
218        P: ProvideAwsCredentials + Send + Sync + 'static,
219        D: DispatchSignedRequest + Send + Sync + 'static,
220    {
221        PersonalizeRuntimeClient {
222            client: Client::new_with(credentials_provider, request_dispatcher),
223            region,
224        }
225    }
226
227    pub fn new_with_client(client: Client, region: region::Region) -> PersonalizeRuntimeClient {
228        PersonalizeRuntimeClient { client, region }
229    }
230}
231
232#[async_trait]
233impl PersonalizeRuntime for PersonalizeRuntimeClient {
234    /// <p><p>Re-ranks a list of recommended items for the given user. The first item in the list is deemed the most likely item to be of interest to the user.</p> <note> <p>The solution backing the campaign must have been created using a recipe of type PERSONALIZED_RANKING.</p> </note></p>
235    #[allow(unused_mut)]
236    async fn get_personalized_ranking(
237        &self,
238        input: GetPersonalizedRankingRequest,
239    ) -> Result<GetPersonalizedRankingResponse, RusotoError<GetPersonalizedRankingError>> {
240        let request_uri = "/personalize-ranking";
241
242        let mut request = SignedRequest::new("POST", "personalize", &self.region, &request_uri);
243        request.set_content_type("application/x-amz-json-1.1".to_owned());
244
245        request.set_endpoint_prefix("personalize-runtime".to_string());
246        let encoded = Some(serde_json::to_vec(&input).unwrap());
247        request.set_payload(encoded);
248
249        let mut response = self
250            .client
251            .sign_and_dispatch(request)
252            .await
253            .map_err(RusotoError::from)?;
254        if response.status.is_success() {
255            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
256            let result = proto::json::ResponsePayload::new(&response)
257                .deserialize::<GetPersonalizedRankingResponse, _>()?;
258
259            Ok(result)
260        } else {
261            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
262            Err(GetPersonalizedRankingError::from_response(response))
263        }
264    }
265
266    /// <p><p>Returns a list of recommended items. The required input depends on the recipe type used to create the solution backing the campaign, as follows:</p> <ul> <li> <p>RELATED<em>ITEMS - <code>itemId</code> required, <code>userId</code> not used</p> </li> <li> <p>USER</em>PERSONALIZATION - <code>itemId</code> optional, <code>userId</code> required</p> </li> </ul> <note> <p>Campaigns that are backed by a solution created using a recipe of type PERSONALIZED_RANKING use the API.</p> </note></p>
267    #[allow(unused_mut)]
268    async fn get_recommendations(
269        &self,
270        input: GetRecommendationsRequest,
271    ) -> Result<GetRecommendationsResponse, RusotoError<GetRecommendationsError>> {
272        let request_uri = "/recommendations";
273
274        let mut request = SignedRequest::new("POST", "personalize", &self.region, &request_uri);
275        request.set_content_type("application/x-amz-json-1.1".to_owned());
276
277        request.set_endpoint_prefix("personalize-runtime".to_string());
278        let encoded = Some(serde_json::to_vec(&input).unwrap());
279        request.set_payload(encoded);
280
281        let mut response = self
282            .client
283            .sign_and_dispatch(request)
284            .await
285            .map_err(RusotoError::from)?;
286        if response.status.is_success() {
287            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
288            let result = proto::json::ResponsePayload::new(&response)
289                .deserialize::<GetRecommendationsResponse, _>()?;
290
291            Ok(result)
292        } else {
293            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
294            Err(GetRecommendationsError::from_response(response))
295        }
296    }
297}