rusoto_sagemaker_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};
26#[derive(Clone, Debug, Default, PartialEq, Serialize)]
27#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
28pub struct InvokeEndpointInput {
29    /// <p>The desired MIME type of the inference in the response.</p>
30    #[serde(rename = "Accept")]
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub accept: Option<String>,
33    /// <p>Provides input data, in the format specified in the <code>ContentType</code> request header. Amazon SageMaker passes all of the data in the body to the model. </p> <p>For information about the format of the request body, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html">Common Data Formats-Inference</a>.</p>
34    #[serde(rename = "Body")]
35    #[serde(
36        deserialize_with = "::rusoto_core::serialization::SerdeBlob::deserialize_blob",
37        serialize_with = "::rusoto_core::serialization::SerdeBlob::serialize_blob",
38        default
39    )]
40    pub body: bytes::Bytes,
41    /// <p>The MIME type of the input data in the request body.</p>
42    #[serde(rename = "ContentType")]
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub content_type: Option<String>,
45    /// <p>Provides additional information about a request for an inference submitted to a model hosted at an Amazon SageMaker endpoint. The information is an opaque value that is forwarded verbatim. You could use this value, for example, to provide an ID that you can use to track a request or to provide other metadata that a service endpoint was programmed to process. The value must consist of no more than 1024 visible US-ASCII characters as specified in <a href="https://tools.ietf.org/html/rfc7230#section-3.2.6">Section 3.3.6. Field Value Components</a> of the Hypertext Transfer Protocol (HTTP/1.1). This feature is currently supported in the AWS SDKs but not in the Amazon SageMaker Python SDK.</p>
46    #[serde(rename = "CustomAttributes")]
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub custom_attributes: Option<String>,
49    /// <p>The name of the endpoint that you specified when you created the endpoint using the <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateEndpoint.html">CreateEndpoint</a> API. </p>
50    #[serde(rename = "EndpointName")]
51    pub endpoint_name: String,
52    /// <p>The model to request for inference when invoking a multi-model endpoint. </p>
53    #[serde(rename = "TargetModel")]
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub target_model: Option<String>,
56    /// <p>Specify the production variant to send the inference request to when invoking an endpoint that is running two or more variants. Note that this parameter overrides the default behavior for the endpoint, which is to distribute the invocation traffic based on the variant weights.</p>
57    #[serde(rename = "TargetVariant")]
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub target_variant: Option<String>,
60}
61
62#[derive(Clone, Debug, Default, PartialEq)]
63pub struct InvokeEndpointOutput {
64    /// <p>Includes the inference provided by the model.</p> <p>For information about the format of the response body, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html">Common Data Formats-Inference</a>.</p>
65    pub body: bytes::Bytes,
66    /// <p>The MIME type of the inference returned in the response body.</p>
67    pub content_type: Option<String>,
68    /// <p>Provides additional information in the response about the inference returned by a model hosted at an Amazon SageMaker endpoint. The information is an opaque value that is forwarded verbatim. You could use this value, for example, to return an ID received in the <code>CustomAttributes</code> header of a request or other metadata that a service endpoint was programmed to produce. The value must consist of no more than 1024 visible US-ASCII characters as specified in <a href="https://tools.ietf.org/html/rfc7230#section-3.2.6">Section 3.3.6. Field Value Components</a> of the Hypertext Transfer Protocol (HTTP/1.1). If the customer wants the custom attribute returned, the model must set the custom attribute to be included on the way back. </p> <p>This feature is currently supported in the AWS SDKs but not in the Amazon SageMaker Python SDK.</p>
69    pub custom_attributes: Option<String>,
70    /// <p>Identifies the production variant that was invoked.</p>
71    pub invoked_production_variant: Option<String>,
72}
73
74/// Errors returned by InvokeEndpoint
75#[derive(Debug, PartialEq)]
76pub enum InvokeEndpointError {
77    /// <p> An internal failure occurred. </p>
78    InternalFailure(String),
79    /// <p> Model (owned by the customer in the container) returned 4xx or 5xx error code. </p>
80    ModelError(String),
81    /// <p> The service is unavailable. Try your call again. </p>
82    ServiceUnavailable(String),
83    /// <p> Inspect your request and try again. </p>
84    ValidationError(String),
85}
86
87impl InvokeEndpointError {
88    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<InvokeEndpointError> {
89        if let Some(err) = proto::json::Error::parse_rest(&res) {
90            match err.typ.as_str() {
91                "InternalFailure" => {
92                    return RusotoError::Service(InvokeEndpointError::InternalFailure(err.msg))
93                }
94                "ModelError" => {
95                    return RusotoError::Service(InvokeEndpointError::ModelError(err.msg))
96                }
97                "ServiceUnavailable" => {
98                    return RusotoError::Service(InvokeEndpointError::ServiceUnavailable(err.msg))
99                }
100                "ValidationError" => {
101                    return RusotoError::Service(InvokeEndpointError::ValidationError(err.msg))
102                }
103                "ValidationException" => return RusotoError::Validation(err.msg),
104                _ => {}
105            }
106        }
107        RusotoError::Unknown(res)
108    }
109}
110impl fmt::Display for InvokeEndpointError {
111    #[allow(unused_variables)]
112    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113        match *self {
114            InvokeEndpointError::InternalFailure(ref cause) => write!(f, "{}", cause),
115            InvokeEndpointError::ModelError(ref cause) => write!(f, "{}", cause),
116            InvokeEndpointError::ServiceUnavailable(ref cause) => write!(f, "{}", cause),
117            InvokeEndpointError::ValidationError(ref cause) => write!(f, "{}", cause),
118        }
119    }
120}
121impl Error for InvokeEndpointError {}
122/// Trait representing the capabilities of the Amazon SageMaker Runtime API. Amazon SageMaker Runtime clients implement this trait.
123#[async_trait]
124pub trait SageMakerRuntime {
125    /// <p><p>After you deploy a model into production using Amazon SageMaker hosting services, your client applications use this API to get inferences from the model hosted at the specified endpoint. </p> <p>For an overview of Amazon SageMaker, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works.html">How It Works</a>. </p> <p>Amazon SageMaker strips all POST headers except those supported by the API. Amazon SageMaker might add additional headers. You should not rely on the behavior of headers outside those enumerated in the request syntax. </p> <p>Calls to <code>InvokeEndpoint</code> are authenticated by using AWS Signature Version 4. For information, see <a href="http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html">Authenticating Requests (AWS Signature Version 4)</a> in the <i>Amazon S3 API Reference</i>.</p> <p>A customer&#39;s model containers must respond to requests within 60 seconds. The model itself can have a maximum processing time of 60 seconds before responding to the /invocations. If your model is going to take 50-60 seconds of processing time, the SDK socket timeout should be set to be 70 seconds.</p> <note> <p>Endpoints are scoped to an individual account, and are not public. The URL does not contain the account ID, but Amazon SageMaker determines the account ID from the authentication token that is supplied by the caller.</p> </note></p>
126    async fn invoke_endpoint(
127        &self,
128        input: InvokeEndpointInput,
129    ) -> Result<InvokeEndpointOutput, RusotoError<InvokeEndpointError>>;
130}
131/// A client for the Amazon SageMaker Runtime API.
132#[derive(Clone)]
133pub struct SageMakerRuntimeClient {
134    client: Client,
135    region: region::Region,
136}
137
138impl SageMakerRuntimeClient {
139    /// Creates a client backed by the default tokio event loop.
140    ///
141    /// The client will use the default credentials provider and tls client.
142    pub fn new(region: region::Region) -> SageMakerRuntimeClient {
143        SageMakerRuntimeClient {
144            client: Client::shared(),
145            region,
146        }
147    }
148
149    pub fn new_with<P, D>(
150        request_dispatcher: D,
151        credentials_provider: P,
152        region: region::Region,
153    ) -> SageMakerRuntimeClient
154    where
155        P: ProvideAwsCredentials + Send + Sync + 'static,
156        D: DispatchSignedRequest + Send + Sync + 'static,
157    {
158        SageMakerRuntimeClient {
159            client: Client::new_with(credentials_provider, request_dispatcher),
160            region,
161        }
162    }
163
164    pub fn new_with_client(client: Client, region: region::Region) -> SageMakerRuntimeClient {
165        SageMakerRuntimeClient { client, region }
166    }
167}
168
169#[async_trait]
170impl SageMakerRuntime for SageMakerRuntimeClient {
171    /// <p><p>After you deploy a model into production using Amazon SageMaker hosting services, your client applications use this API to get inferences from the model hosted at the specified endpoint. </p> <p>For an overview of Amazon SageMaker, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works.html">How It Works</a>. </p> <p>Amazon SageMaker strips all POST headers except those supported by the API. Amazon SageMaker might add additional headers. You should not rely on the behavior of headers outside those enumerated in the request syntax. </p> <p>Calls to <code>InvokeEndpoint</code> are authenticated by using AWS Signature Version 4. For information, see <a href="http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html">Authenticating Requests (AWS Signature Version 4)</a> in the <i>Amazon S3 API Reference</i>.</p> <p>A customer&#39;s model containers must respond to requests within 60 seconds. The model itself can have a maximum processing time of 60 seconds before responding to the /invocations. If your model is going to take 50-60 seconds of processing time, the SDK socket timeout should be set to be 70 seconds.</p> <note> <p>Endpoints are scoped to an individual account, and are not public. The URL does not contain the account ID, but Amazon SageMaker determines the account ID from the authentication token that is supplied by the caller.</p> </note></p>
172    #[allow(unused_mut)]
173    async fn invoke_endpoint(
174        &self,
175        input: InvokeEndpointInput,
176    ) -> Result<InvokeEndpointOutput, RusotoError<InvokeEndpointError>> {
177        let request_uri = format!(
178            "/endpoints/{endpoint_name}/invocations",
179            endpoint_name = input.endpoint_name
180        );
181
182        let mut request = SignedRequest::new("POST", "sagemaker", &self.region, &request_uri);
183        if input.content_type.is_none() {
184            request.set_content_type("application/x-amz-json-1.1".to_owned());
185        }
186
187        request.set_endpoint_prefix("runtime.sagemaker".to_string());
188        let encoded = Some(input.body.to_owned());
189        request.set_payload(encoded);
190        request.add_optional_header("Accept", input.accept.as_ref());
191        request.add_optional_header("Content-Type", input.content_type.as_ref());
192        request.add_optional_header(
193            "X-Amzn-SageMaker-Custom-Attributes",
194            input.custom_attributes.as_ref(),
195        );
196        request.add_optional_header("X-Amzn-SageMaker-Target-Model", input.target_model.as_ref());
197        request.add_optional_header(
198            "X-Amzn-SageMaker-Target-Variant",
199            input.target_variant.as_ref(),
200        );
201
202        let mut response = self
203            .client
204            .sign_and_dispatch(request)
205            .await
206            .map_err(RusotoError::from)?;
207        if response.status.is_success() {
208            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
209
210            let mut result = InvokeEndpointOutput::default();
211            result.body = response.body;
212
213            result.content_type = response.headers.remove("Content-Type");
214            result.custom_attributes = response
215                .headers
216                .remove("X-Amzn-SageMaker-Custom-Attributes");
217            result.invoked_production_variant =
218                response.headers.remove("x-Amzn-Invoked-Production-Variant");
219
220            Ok(result)
221        } else {
222            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
223            Err(InvokeEndpointError::from_response(response))
224        }
225    }
226}