1 + | /*
|
2 + | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
3 + | * SPDX-License-Identifier: Apache-2.0
|
4 + | */
|
5 + |
|
6 + | //! HTTP binding protocol for REST-style APIs.
|
7 + |
|
8 + | use crate::codec::{Codec, FinishSerializer};
|
9 + | use crate::protocol::ClientProtocol;
|
10 + | use crate::serde::{SerdeError, SerializableStruct, ShapeDeserializer, ShapeSerializer};
|
11 + | use crate::{Schema, ShapeId};
|
12 + | use aws_smithy_runtime_api::http::{Request, Response};
|
13 + | use aws_smithy_types::body::SdkBody;
|
14 + | use aws_smithy_types::config_bag::ConfigBag;
|
15 + |
|
16 + | /// An HTTP protocol for REST-style APIs that use HTTP bindings.
|
17 + | ///
|
18 + | /// This protocol splits input members between HTTP locations (headers, query
|
19 + | /// strings, URI labels) and the payload based on HTTP binding traits
|
20 + | /// (`@httpHeader`, `@httpQuery`, `@httpLabel`, `@httpPayload`, etc.).
|
21 + | /// Non-bound members are serialized into the body using the provided codec.
|
22 + | ///
|
23 + | /// # Type parameters
|
24 + | ///
|
25 + | /// * `C` — the payload codec (e.g., `JsonCodec`, `XmlCodec`)
|
26 + | #[derive(Debug)]
|
27 + | pub struct HttpBindingProtocol<C> {
|
28 + | protocol_id: ShapeId,
|
29 + | codec: C,
|
30 + | content_type: &'static str,
|
31 + | }
|
32 + |
|
33 + | impl<C: Codec> HttpBindingProtocol<C> {
|
34 + | /// Creates a new HTTP binding protocol.
|
35 + | pub fn new(protocol_id: ShapeId, codec: C, content_type: &'static str) -> Self {
|
36 + | Self {
|
37 + | protocol_id,
|
38 + | codec,
|
39 + | content_type,
|
40 + | }
|
41 + | }
|
42 + | }
|
43 + |
|
44 + | // Note: there is a percent_encoding crate we use some other places for this, but I'm trying to keep
|
45 + | // the dependencies to a minimum.
|
46 + | /// Percent-encode a string per RFC 3986 section 2.3 (unreserved characters only).
|
47 + | pub fn percent_encode(input: &str) -> String {
|
48 + | let mut out = String::with_capacity(input.len());
|
49 + | for byte in input.bytes() {
|
50 + | match byte {
|
51 + | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
|
52 + | out.push(byte as char);
|
53 + | }
|
54 + | _ => {
|
55 + | out.push('%');
|
56 + | out.push(char::from(HEX[(byte >> 4) as usize]));
|
57 + | out.push(char::from(HEX[(byte & 0x0f) as usize]));
|
58 + | }
|
59 + | }
|
60 + | }
|
61 + | out
|
62 + | }
|
63 + |
|
64 + | pub(crate) const HEX: &[u8; 16] = b"0123456789ABCDEF";
|
65 + |
|
66 + | /// A ShapeSerializer that intercepts member writes and routes HTTP-bound
|
67 + | /// members to headers, query params, or URI labels instead of the body.
|
68 + | ///
|
69 + | /// Members without HTTP binding traits are forwarded to the inner body
|
70 + | /// serializer unchanged.
|
71 + | struct HttpBindingSerializer<'a, S> {
|
72 + | body: S,
|
73 + | headers: Vec<(String, String)>,
|
74 + | query_params: Vec<(String, String)>,
|
75 + | labels: Vec<(String, String)>,
|
76 + | /// When set, member schemas are resolved from this schema by name to find
|
77 + | /// HTTP binding traits. This allows the protocol to override bindings
|
78 + | /// (e.g., for presigning where body members become query params).
|
79 + | input_schema: Option<&'a Schema>,
|
80 + | /// True for the top-level input struct in serialize_request.
|
81 + | /// Cleared after the first write_struct so nested structs delegate directly.
|
82 + | is_top_level: bool,
|
83 + | /// Tracks whether any member was written to the body serializer (i.e., a member
|
84 + | /// without an HTTP binding trait). Used by `HttpBindingProtocol` to determine
|
85 + | /// whether to wrap the body in `{}` and set `Content-Type: application/json`.
|
86 + | /// Per the REST-JSON spec, operations with no body members must send an empty
|
87 + | /// body with no Content-Type header.
|
88 + | has_body_content: bool,
|
89 + | /// Raw payload bytes for `@httpPayload` blob/string members. When a member
|
90 + | /// has `@httpPayload` and targets a blob or string, the raw bytes bypass
|
91 + | /// the codec serializer entirely and are used as the HTTP body directly.
|
92 + | /// Safety: the referenced bytes are borrowed from the input struct passed to
|
93 + | /// `serialize_request`, which outlives this serializer.
|
94 + | raw_payload: Option<&'a [u8]>,
|
95 + | }
|
96 + |
|
97 + | impl<'a, S> HttpBindingSerializer<'a, S> {
|
98 + | fn new(body: S, input_schema: Option<&'a Schema>) -> Self {
|
99 + | Self {
|
100 + | body,
|
101 + | headers: Vec::new(),
|
102 + | query_params: Vec::new(),
|
103 + | labels: Vec::new(),
|
104 + | input_schema,
|
105 + | is_top_level: true,
|
106 + | has_body_content: false,
|
107 + | raw_payload: None,
|
108 + | }
|
109 + | }
|
110 + |
|
111 + | /// Finish serialization and return only the body bytes, discarding
|
112 + | /// any collected headers/query/labels.
|
113 + | fn finish_body(self) -> Vec<u8>
|
114 + | where
|
115 + | S: FinishSerializer,
|
116 + | {
|
117 + | if let Some(payload) = self.raw_payload {
|
118 + | payload.to_vec()
|
119 + | } else {
|
120 + | self.body.finish()
|
121 + | }
|
122 + | }
|
123 + |
|
124 + | /// Resolve the effective member schema: if an input_schema override is set,
|
125 + | /// look up the member by name there (to get the correct HTTP bindings).
|
126 + | /// Otherwise use the schema as-is.
|
127 + | fn resolve_member<'s>(&self, schema: &'s Schema) -> &'s Schema
|
128 + | where
|
129 + | 'a: 's,
|
130 + | {
|
131 + | if let (Some(input_schema), Some(name)) = (self.input_schema, schema.member_name()) {
|
132 + | input_schema.member_schema(name).unwrap_or(schema)
|
133 + | } else {
|
134 + | schema
|
135 + | }
|
136 + | }
|
137 + | }
|
138 + |
|
139 + | impl<'a, S: ShapeSerializer> ShapeSerializer for HttpBindingSerializer<'a, S> {
|
140 + | fn write_struct(
|
141 + | &mut self,
|
142 + | schema: &Schema,
|
143 + | value: &dyn SerializableStruct,
|
144 + | ) -> Result<(), SerdeError> {
|
145 + | if self.is_top_level {
|
146 + | // Top-level input struct: route serialize_members through the binder
|
147 + | // so HTTP-bound members are intercepted. The body serializer's
|
148 + | // write_struct is used for framing (e.g., { } for JSON), with a
|
149 + | // proxy whose serialize_members delegates back to the binder.
|
150 + | struct Proxy<'a, 'b, S> {
|
151 + | binder: &'a mut HttpBindingSerializer<'b, S>,
|
152 + | value: &'a dyn SerializableStruct,
|
153 + | }
|
154 + | impl<S: ShapeSerializer> SerializableStruct for Proxy<'_, '_, S> {
|
155 + | fn serialize_members(
|
156 + | &self,
|
157 + | _serializer: &mut dyn ShapeSerializer,
|
158 + | ) -> Result<(), SerdeError> {
|
159 + | let binder = self.binder as *const HttpBindingSerializer<'_, S>
|
160 + | as *mut HttpBindingSerializer<'_, S>;
|
161 + | // SAFETY: The body serializer called serialize_members on
|
162 + | // this proxy, passing &mut self (body). The binder wraps
|
163 + | // that same body serializer. We need mutable access to the
|
164 + | // binder to route writes. This is safe because:
|
165 + | // 1. The body serializer's write_struct only calls
|
166 + | // serialize_members once, synchronously.
|
167 + | // 2. Body member writes from the binder go back to the
|
168 + | // body serializer, which is in a valid state (between
|
169 + | // the { and } it emitted).
|
170 + | self.value.serialize_members(unsafe { &mut *binder })
|
171 + | }
|
172 + | }
|
173 + | // Clear is_top_level so nested write_struct calls (from body members)
|
174 + | // take the else branch and delegate directly to the body serializer.
|
175 + | // input_schema is preserved so resolve_member continues to work.
|
176 + | self.is_top_level = false;
|
177 + | let proxy = Proxy {
|
178 + | binder: self,
|
179 + | value,
|
180 + | };
|
181 + | let binder_ptr = &mut *proxy.binder as *mut HttpBindingSerializer<'_, S>;
|
182 + | // SAFETY: `proxy` holds a shared reference to `binder` (via &mut that
|
183 + | // we reborrow). We need to call `binder.body.write_struct(schema, &proxy)`
|
184 + | // but can't do so through normal references because `proxy` borrows `binder`.
|
185 + | // The raw pointer dereference is safe because:
|
186 + | // 1. `binder_ptr` points to a valid, live `HttpBindingSerializer` (it was
|
187 + | // just derived from `proxy.binder`).
|
188 + | // 2. `body.write_struct` is called synchronously and returns before `proxy`
|
189 + | // is dropped, so the binder is not moved or deallocated.
|
190 + | // 3. The only re-entrant access is through `proxy.serialize_members`, which
|
191 + | // uses the same raw-pointer pattern with its own safety justification above.
|
192 + | unsafe { (*binder_ptr).body.write_struct(schema, &proxy) }
|
193 + | } else {
|
194 + | // Nested struct (a body member targeting a structure): delegate
|
195 + | // entirely to the body serializer.
|
196 + | let schema = self.resolve_member(schema);
|
197 + | if schema.http_payload().is_some() {
|
198 + | // @httpPayload struct/union: write as the body's top-level object
|
199 + | // without a member name prefix. Use a non-member schema for the
|
200 + | // write_struct call so prefix() doesn't emit a field name.
|
201 + | self.has_body_content = true;
|
202 + | self.body.write_struct(&crate::prelude::DOCUMENT, value)?;
|
203 + | return Ok(());
|
204 + | }
|
205 + | self.has_body_content = true;
|
206 + | self.body.write_struct(schema, value)
|
207 + | }
|
208 + | }
|
209 + |
|
210 + | fn write_list(
|
211 + | &mut self,
|
212 + | schema: &Schema,
|
213 + | write_elements: &dyn Fn(&mut dyn ShapeSerializer) -> Result<(), SerdeError>,
|
214 + | ) -> Result<(), SerdeError> {
|
215 + | self.has_body_content = true;
|
216 + | self.body.write_list(schema, write_elements)
|
217 + | }
|
218 + |
|
219 + | fn write_map(
|
220 + | &mut self,
|
221 + | schema: &Schema,
|
222 + | write_entries: &dyn Fn(&mut dyn ShapeSerializer) -> Result<(), SerdeError>,
|
223 + | ) -> Result<(), SerdeError> {
|
224 + | let schema = self.resolve_member(schema);
|
225 + | // @httpPrefixHeaders: serialize map entries as prefixed headers
|
226 + | if let Some(prefix) = schema.http_prefix_headers() {
|
227 + | // Collect entries via a temporary serializer
|
228 + | let mut collector = MapEntryCollector::new(prefix.value().to_string());
|
229 + | write_entries(&mut collector)?;
|
230 + | self.headers.extend(collector.entries);
|
231 + | return Ok(());
|
232 + | }
|
233 + | // @httpQueryParams: serialize map entries as query params
|
234 + | if schema.http_query_params().is_some() {
|
235 + | let mut collector = MapEntryCollector::new(String::new());
|
236 + | write_entries(&mut collector)?;
|
237 + | for (k, v) in collector.entries {
|
238 + | self.query_params.push((k, v));
|
239 + | }
|
240 + | return Ok(());
|
241 + | }
|
242 + | self.has_body_content = true;
|
243 + | self.body.write_map(schema, write_entries)
|
244 + | }
|
245 + |
|
246 + | fn write_boolean(&mut self, schema: &Schema, value: bool) -> Result<(), SerdeError> {
|
247 + | let schema = self.resolve_member(schema);
|
248 + | if let Some(binding) = http_string_binding(schema) {
|
249 + | return self.add_binding(binding, schema, &value.to_string());
|
250 + | }
|
251 + | self.has_body_content = true;
|
252 + | self.body.write_boolean(schema, value)
|
253 + | }
|
254 + |
|
255 + | fn write_byte(&mut self, schema: &Schema, value: i8) -> Result<(), SerdeError> {
|
256 + | let schema = self.resolve_member(schema);
|
257 + | if let Some(binding) = http_string_binding(schema) {
|
258 + | return self.add_binding(binding, schema, &value.to_string());
|
259 + | }
|
260 + | self.has_body_content = true;
|
261 + | self.body.write_byte(schema, value)
|
262 + | }
|
263 + |
|
264 + | fn write_short(&mut self, schema: &Schema, value: i16) -> Result<(), SerdeError> {
|
265 + | let schema = self.resolve_member(schema);
|
266 + | if let Some(binding) = http_string_binding(schema) {
|
267 + | return self.add_binding(binding, schema, &value.to_string());
|
268 + | }
|
269 + | self.has_body_content = true;
|
270 + | self.body.write_short(schema, value)
|
271 + | }
|
272 + |
|
273 + | fn write_integer(&mut self, schema: &Schema, value: i32) -> Result<(), SerdeError> {
|
274 + | let schema = self.resolve_member(schema);
|
275 + | if let Some(binding) = http_string_binding(schema) {
|
276 + | return self.add_binding(binding, schema, &value.to_string());
|
277 + | }
|
278 + | self.has_body_content = true;
|
279 + | self.body.write_integer(schema, value)
|
280 + | }
|
281 + |
|
282 + | fn write_long(&mut self, schema: &Schema, value: i64) -> Result<(), SerdeError> {
|
283 + | let schema = self.resolve_member(schema);
|
284 + | if let Some(binding) = http_string_binding(schema) {
|
285 + | return self.add_binding(binding, schema, &value.to_string());
|
286 + | }
|
287 + | self.has_body_content = true;
|
288 + | self.body.write_long(schema, value)
|
289 + | }
|
290 + |
|
291 + | fn write_float(&mut self, schema: &Schema, value: f32) -> Result<(), SerdeError> {
|
292 + | let schema = self.resolve_member(schema);
|
293 + | if let Some(binding) = http_string_binding(schema) {
|
294 + | return self.add_binding(binding, schema, &value.to_string());
|
295 + | }
|
296 + | self.has_body_content = true;
|
297 + | self.body.write_float(schema, value)
|
298 + | }
|
299 + |
|
300 + | fn write_double(&mut self, schema: &Schema, value: f64) -> Result<(), SerdeError> {
|
301 + | let schema = self.resolve_member(schema);
|
302 + | if let Some(binding) = http_string_binding(schema) {
|
303 + | return self.add_binding(binding, schema, &value.to_string());
|
304 + | }
|
305 + | self.has_body_content = true;
|
306 + | self.body.write_double(schema, value)
|
307 + | }
|
308 + |
|
309 + | fn write_big_integer(
|
310 + | &mut self,
|
311 + | schema: &Schema,
|
312 + | value: &aws_smithy_types::BigInteger,
|
313 + | ) -> Result<(), SerdeError> {
|
314 + | let schema = self.resolve_member(schema);
|
315 + | if let Some(binding) = http_string_binding(schema) {
|
316 + | return self.add_binding(binding, schema, value.as_ref());
|
317 + | }
|
318 + | self.has_body_content = true;
|
319 + | self.body.write_big_integer(schema, value)
|
320 + | }
|
321 + |
|
322 + | fn write_big_decimal(
|
323 + | &mut self,
|
324 + | schema: &Schema,
|
325 + | value: &aws_smithy_types::BigDecimal,
|
326 + | ) -> Result<(), SerdeError> {
|
327 + | let schema = self.resolve_member(schema);
|
328 + | if let Some(binding) = http_string_binding(schema) {
|
329 + | return self.add_binding(binding, schema, value.as_ref());
|
330 + | }
|
331 + | self.has_body_content = true;
|
332 + | self.body.write_big_decimal(schema, value)
|
333 + | }
|
334 + |
|
335 + | fn write_string(&mut self, schema: &Schema, value: &str) -> Result<(), SerdeError> {
|
336 + | let schema = self.resolve_member(schema);
|
337 + | if let Some(binding) = http_string_binding(schema) {
|
338 + | return self.add_binding(binding, schema, value);
|
339 + | }
|
340 + | if schema.http_payload().is_some() {
|
341 + | // SAFETY: We extend the lifetime of `value.as_bytes()` from its anonymous
|
342 + | // lifetime to `'a`. This is sound because:
|
343 + | // 1. `value` is borrowed from the input struct passed to `serialize_request`.
|
344 + | // 2. `HttpBindingSerializer` is a local variable within `serialize_request`
|
345 + | // and is dropped before `serialize_request` returns.
|
346 + | // 3. The input struct (and thus `value`) outlives the serializer.
|
347 + | // 4. `raw_payload` is read in `serialize_request` immediately after
|
348 + | // `serialize_members` returns, before the input is dropped.
|
349 + | // We use transmute rather than copying to avoid allocating for potentially
|
350 + | // multi-GB string payloads.
|
351 + | self.raw_payload =
|
352 + | Some(unsafe { std::mem::transmute::<&[u8], &'a [u8]>(value.as_bytes()) });
|
353 + | return Ok(());
|
354 + | }
|
355 + | self.has_body_content = true;
|
356 + | self.body.write_string(schema, value)
|
357 + | }
|
358 + |
|
359 + | fn write_blob(
|
360 + | &mut self,
|
361 + | schema: &Schema,
|
362 + | value: &aws_smithy_types::Blob,
|
363 + | ) -> Result<(), SerdeError> {
|
364 + | let schema = self.resolve_member(schema);
|
365 + | if schema.http_header().is_some() {
|
366 + | let encoded = aws_smithy_types::base64::encode(value.as_ref());
|
367 + | self.headers
|
368 + | .push((schema.http_header().unwrap().value().to_string(), encoded));
|
369 + | return Ok(());
|
370 + | }
|
371 + | if schema.http_payload().is_some() {
|
372 + | // SAFETY: We extend the lifetime of `value.as_ref()` (a `&[u8]`) from its
|
373 + | // anonymous lifetime to `'a`. This is sound because:
|
374 + | // 1. `value` is borrowed from the input struct passed to `serialize_request`.
|
375 + | // 2. `HttpBindingSerializer` is a local variable within `serialize_request`
|
376 + | // and is dropped before `serialize_request` returns.
|
377 + | // 3. The input struct (and thus `value`) outlives the serializer.
|
378 + | // 4. `raw_payload` is read in `serialize_request` immediately after
|
379 + | // `serialize_members` returns, before the input is dropped.
|
380 + | // We use transmute rather than copying to avoid allocating for potentially
|
381 + | // multi-GB blob payloads.
|
382 + | self.raw_payload =
|
383 + | Some(unsafe { std::mem::transmute::<&[u8], &'a [u8]>(value.as_ref()) });
|
384 + | return Ok(());
|
385 + | }
|
386 + | self.has_body_content = true;
|
387 + | self.body.write_blob(schema, value)
|
388 + | }
|
389 + |
|
390 + | fn write_timestamp(
|
391 + | &mut self,
|
392 + | schema: &Schema,
|
393 + | value: &aws_smithy_types::DateTime,
|
394 + | ) -> Result<(), SerdeError> {
|
395 + | let schema = self.resolve_member(schema);
|
396 + | if let Some(binding) = http_string_binding(schema) {
|
397 + | // Headers default to http-date, query/label default to date-time
|
398 + | let format = if let Some(ts_trait) = schema.timestamp_format() {
|
399 + | match ts_trait.format() {
|
400 + | crate::traits::TimestampFormat::EpochSeconds => {
|
401 + | aws_smithy_types::date_time::Format::EpochSeconds
|
402 + | }
|
403 + | crate::traits::TimestampFormat::HttpDate => {
|
404 + | aws_smithy_types::date_time::Format::HttpDate
|
405 + | }
|
406 + | crate::traits::TimestampFormat::DateTime => {
|
407 + | aws_smithy_types::date_time::Format::DateTime
|
408 + | }
|
409 + | }
|
410 + | } else {
|
411 + | match binding {
|
412 + | HttpBinding::Header(_) => aws_smithy_types::date_time::Format::HttpDate,
|
413 + | _ => aws_smithy_types::date_time::Format::DateTime,
|
414 + | }
|
415 + | };
|
416 + | let formatted = value
|
417 + | .fmt(format)
|
418 + | .map_err(|e| SerdeError::custom(format!("failed to format timestamp: {e}")))?;
|
419 + | return self.add_binding(binding, schema, &formatted);
|
420 + | }
|
421 + | self.has_body_content = true;
|
422 + | self.body.write_timestamp(schema, value)
|
423 + | }
|
424 + |
|
425 + | fn write_document(
|
426 + | &mut self,
|
427 + | schema: &Schema,
|
428 + | value: &aws_smithy_types::Document,
|
429 + | ) -> Result<(), SerdeError> {
|
430 + | self.has_body_content = true;
|
431 + | self.body.write_document(schema, value)
|
432 + | }
|
433 + |
|
434 + | fn write_null(&mut self, schema: &Schema) -> Result<(), SerdeError> {
|
435 + | self.has_body_content = true;
|
436 + | self.body.write_null(schema)
|
437 + | }
|
438 + | }
|
439 + |
|
440 + | /// Which HTTP location a member is bound to.
|
441 + | enum HttpBinding<'a> {
|
442 + | Header(&'a str),
|
443 + | Query(&'a str),
|
444 + | Label,
|
445 + | }
|
446 + |
|
447 + | /// Determine the HTTP binding for a member schema, if any.
|
448 + | fn http_string_binding(schema: &Schema) -> Option<HttpBinding<'_>> {
|
449 + | if let Some(h) = schema.http_header() {
|
450 + | return Some(HttpBinding::Header(h.value()));
|
451 + | }
|
452 + | if let Some(q) = schema.http_query() {
|
453 + | return Some(HttpBinding::Query(q.value()));
|
454 + | }
|
455 + | if schema.http_label().is_some() {
|
456 + | return Some(HttpBinding::Label);
|
457 + | }
|
458 + | None
|
459 + | }
|
460 + |
|
461 + | impl<'a, S> HttpBindingSerializer<'a, S> {
|
462 + | fn add_binding(
|
463 + | &mut self,
|
464 + | binding: HttpBinding<'_>,
|
465 + | schema: &Schema,
|
466 + | value: &str,
|
467 + | ) -> Result<(), SerdeError> {
|
468 + | match binding {
|
469 + | HttpBinding::Header(name) => {
|
470 + | self.headers.push((name.to_string(), value.to_string()));
|
471 + | }
|
472 + | HttpBinding::Query(name) => {
|
473 + | self.query_params
|
474 + | .push((name.to_string(), value.to_string()));
|
475 + | }
|
476 + | HttpBinding::Label => {
|
477 + | let name = schema
|
478 + | .member_name()
|
479 + | .ok_or_else(|| SerdeError::custom("httpLabel on non-member schema"))?;
|
480 + | self.labels.push((name.to_string(), value.to_string()));
|
481 + | }
|
482 + | }
|
483 + | Ok(())
|
484 + | }
|
485 + | }
|
486 + |
|
487 + | /// Collects map key-value pairs written via ShapeSerializer for
|
488 + | /// @httpPrefixHeaders and @httpQueryParams.
|
489 + | struct MapEntryCollector {
|
490 + | prefix: String,
|
491 + | entries: Vec<(String, String)>,
|
492 + | pending_key: Option<String>,
|
493 + | }
|
494 + |
|
495 + | impl MapEntryCollector {
|
496 + | fn new(prefix: String) -> Self {
|
497 + | Self {
|
498 + | prefix,
|
499 + | entries: Vec::new(),
|
500 + | pending_key: None,
|
501 + | }
|
502 + | }
|
503 + | }
|
504 + |
|
505 + | impl ShapeSerializer for MapEntryCollector {
|
506 + | fn write_string(&mut self, _schema: &Schema, value: &str) -> Result<(), SerdeError> {
|
507 + | if let Some(key) = self.pending_key.take() {
|
508 + | self.entries
|
509 + | .push((format!("{}{}", self.prefix, key), value.to_string()));
|
510 + | } else {
|
511 + | self.pending_key = Some(value.to_string());
|
512 + | }
|
513 + | Ok(())
|
514 + | }
|
515 + |
|
516 + | // All other methods are no-ops — maps in HTTP bindings only have string keys/values.
|
517 + | fn write_struct(&mut self, _: &Schema, _: &dyn SerializableStruct) -> Result<(), SerdeError> {
|
518 + | Ok(())
|
519 + | }
|
520 + | fn write_list(
|
521 + | &mut self,
|
522 + | _: &Schema,
|
523 + | _: &dyn Fn(&mut dyn ShapeSerializer) -> Result<(), SerdeError>,
|
524 + | ) -> Result<(), SerdeError> {
|
525 + | Ok(())
|
526 + | }
|
527 + | fn write_map(
|
528 + | &mut self,
|
529 + | _: &Schema,
|
530 + | _: &dyn Fn(&mut dyn ShapeSerializer) -> Result<(), SerdeError>,
|
531 + | ) -> Result<(), SerdeError> {
|
532 + | Ok(())
|
533 + | }
|
534 + | fn write_boolean(&mut self, _: &Schema, _: bool) -> Result<(), SerdeError> {
|
535 + | Ok(())
|
536 + | }
|
537 + | fn write_byte(&mut self, _: &Schema, _: i8) -> Result<(), SerdeError> {
|
538 + | Ok(())
|
539 + | }
|
540 + | fn write_short(&mut self, _: &Schema, _: i16) -> Result<(), SerdeError> {
|
541 + | Ok(())
|
542 + | }
|
543 + | fn write_integer(&mut self, _: &Schema, _: i32) -> Result<(), SerdeError> {
|
544 + | Ok(())
|
545 + | }
|
546 + | fn write_long(&mut self, _: &Schema, _: i64) -> Result<(), SerdeError> {
|
547 + | Ok(())
|
548 + | }
|
549 + | fn write_float(&mut self, _: &Schema, _: f32) -> Result<(), SerdeError> {
|
550 + | Ok(())
|
551 + | }
|
552 + | fn write_double(&mut self, _: &Schema, _: f64) -> Result<(), SerdeError> {
|
553 + | Ok(())
|
554 + | }
|
555 + | fn write_big_integer(
|
556 + | &mut self,
|
557 + | _: &Schema,
|
558 + | _: &aws_smithy_types::BigInteger,
|
559 + | ) -> Result<(), SerdeError> {
|
560 + | Ok(())
|
561 + | }
|
562 + | fn write_big_decimal(
|
563 + | &mut self,
|
564 + | _: &Schema,
|
565 + | _: &aws_smithy_types::BigDecimal,
|
566 + | ) -> Result<(), SerdeError> {
|
567 + | Ok(())
|
568 + | }
|
569 + | fn write_blob(&mut self, _: &Schema, _: &aws_smithy_types::Blob) -> Result<(), SerdeError> {
|
570 + | Ok(())
|
571 + | }
|
572 + | fn write_timestamp(
|
573 + | &mut self,
|
574 + | _: &Schema,
|
575 + | _: &aws_smithy_types::DateTime,
|
576 + | ) -> Result<(), SerdeError> {
|
577 + | Ok(())
|
578 + | }
|
579 + | fn write_document(
|
580 + | &mut self,
|
581 + | _: &Schema,
|
582 + | _: &aws_smithy_types::Document,
|
583 + | ) -> Result<(), SerdeError> {
|
584 + | Ok(())
|
585 + | }
|
586 + | fn write_null(&mut self, _: &Schema) -> Result<(), SerdeError> {
|
587 + | Ok(())
|
588 + | }
|
589 + | }
|
590 + |
|
591 + | impl<C> ClientProtocol for HttpBindingProtocol<C>
|
592 + | where
|
593 + | C: Codec + Send + Sync + std::fmt::Debug + 'static,
|
594 + | for<'a> C::Deserializer<'a>: ShapeDeserializer,
|
595 + | {
|
596 + | fn protocol_id(&self) -> &ShapeId {
|
597 + | &self.protocol_id
|
598 + | }
|
599 + |
|
600 + | fn supports_http_bindings(&self) -> bool {
|
601 + | true
|
602 + | }
|
603 + |
|
604 + | fn serialize_request(
|
605 + | &self,
|
606 + | input: &dyn SerializableStruct,
|
607 + | input_schema: &Schema,
|
608 + | endpoint: &str,
|
609 + | _cfg: &ConfigBag,
|
610 + | ) -> Result<Request, SerdeError> {
|
611 + | let mut binder =
|
612 + | HttpBindingSerializer::new(self.codec.create_serializer(), Some(input_schema));
|
613 + |
|
614 + | // Check if there's an @httpPayload member targeting a structure/union.
|
615 + | // In that case, the payload member's own write_struct provides the body
|
616 + | // framing, so we must not add top-level struct framing.
|
617 + | let has_struct_payload = input_schema.members().iter().any(|m| {
|
618 + | m.http_payload().is_some()
|
619 + | && matches!(
|
620 + | m.shape_type(),
|
621 + | crate::ShapeType::Structure | crate::ShapeType::Union
|
622 + | )
|
623 + | });
|
624 + | if has_struct_payload {
|
625 + | binder.is_top_level = false;
|
626 + | input.serialize_members(&mut binder)?;
|
627 + | } else {
|
628 + | binder.write_struct(input_schema, input)?;
|
629 + | }
|
630 + | let raw_payload = binder.raw_payload;
|
631 + | let mut body = if raw_payload.is_some() {
|
632 + | // @httpPayload blob/string — don't use the codec output
|
633 + | Vec::new()
|
634 + | } else {
|
635 + | binder.body.finish()
|
636 + | };
|
637 + |
|
638 + | // Per the REST-JSON content-type handling spec:
|
639 + | // - If @httpPayload targets a blob/string: send raw bytes, no Content-Type when empty
|
640 + | // - If body members exist (even if all optional and unset): send `{}` with Content-Type
|
641 + | // - If no body members at all (everything is in headers/query/labels): empty body, no Content-Type
|
642 + | let has_blob_or_string_payload = raw_payload.is_some();
|
643 + | let has_body_members = input_schema.members().iter().any(|m| {
|
644 + | m.http_header().is_none()
|
645 + | && m.http_query().is_none()
|
646 + | && m.http_label().is_none()
|
647 + | && m.http_prefix_headers().is_none()
|
648 + | && m.http_query_params().is_none()
|
649 + | });
|
650 + |
|
651 + | let set_content_type = if has_blob_or_string_payload {
|
652 + | // Blob/string payload: only set Content-Type if there's actual content
|
653 + | raw_payload.is_some_and(|p| !p.is_empty())
|
654 + | } else if has_body_members {
|
655 + | // Operation has body members — body includes framing (e.g., `{}`).
|
656 + | // Per the REST-JSON spec, even if all members are optional and unset, send `{}`.
|
657 + | true
|
658 + | } else {
|
659 + | // No body members at all — empty body, no Content-Type.
|
660 + | body = Vec::new();
|
661 + | false
|
662 + | };
|
663 + |
|
664 + | // Build URI: use @http trait if available (with label substitution from binder),
|
665 + | // otherwise fall back to endpoint with manual label substitution.
|
666 + | let mut uri = match input_schema.http() {
|
667 + | Some(h) => {
|
668 + | let mut path = h.uri().to_string();
|
669 + | for (name, value) in &binder.labels {
|
670 + | let placeholder = format!("{{{name}}}");
|
671 + | path = path.replace(&placeholder, &percent_encode(value));
|
672 + | }
|
673 + | if endpoint.is_empty() {
|
674 + | path
|
675 + | } else {
|
676 + | format!("{}{}", endpoint, path)
|
677 + | }
|
678 + | }
|
679 + | None => {
|
680 + | let mut u = if endpoint.is_empty() {
|
681 + | "/".to_string()
|
682 + | } else {
|
683 + | endpoint.to_string()
|
684 + | };
|
685 + | for (name, value) in &binder.labels {
|
686 + | let placeholder = format!("{{{name}}}");
|
687 + | u = u.replace(&placeholder, &percent_encode(value));
|
688 + | }
|
689 + | u
|
690 + | }
|
691 + | };
|
692 + | if !binder.query_params.is_empty() {
|
693 + | uri.push(if uri.contains('?') { '&' } else { '?' });
|
694 + | let pairs: Vec<String> = binder
|
695 + | .query_params
|
696 + | .iter()
|
697 + | .map(|(k, v)| format!("{}={}", percent_encode(k), percent_encode(v)))
|
698 + | .collect();
|
699 + | uri.push_str(&pairs.join("&"));
|
700 + | }
|
701 + |
|
702 + | let mut request = if let Some(payload) = raw_payload {
|
703 + | Request::new(SdkBody::from(payload))
|
704 + | } else {
|
705 + | Request::new(SdkBody::from(body))
|
706 + | };
|
707 + | // Set HTTP method from @http trait
|
708 + | if let Some(http) = input_schema.http() {
|
709 + | request
|
710 + | .set_method(http.method())
|
711 + | .map_err(|e| SerdeError::custom(format!("invalid HTTP method: {e}")))?;
|
712 + | }
|
713 + | request
|
714 + | .set_uri(uri.as_str())
|
715 + | .map_err(|e| SerdeError::custom(format!("invalid endpoint URI: {e}")))?;
|
716 + | if set_content_type {
|
717 + | request
|
718 + | .headers_mut()
|
719 + | .insert("Content-Type", self.content_type);
|
720 + | }
|
721 + | if let Some(len) = request.body().content_length() {
|
722 + | if len > 0 || set_content_type {
|
723 + | request
|
724 + | .headers_mut()
|
725 + | .insert("Content-Length", len.to_string());
|
726 + | }
|
727 + | }
|
728 + | for (name, value) in &binder.headers {
|
729 + | request.headers_mut().insert(name.clone(), value.clone());
|
730 + | }
|
731 + | Ok(request)
|
732 + | }
|
733 + |
|
734 + | fn deserialize_response<'a>(
|
735 + | &self,
|
736 + | response: &'a Response,
|
737 + | _output_schema: &Schema,
|
738 + | _cfg: &ConfigBag,
|
739 + | ) -> Result<Box<dyn ShapeDeserializer + 'a>, SerdeError> {
|
740 + | let body = response
|
741 + | .body()
|
742 + | .bytes()
|
743 + | .ok_or_else(|| SerdeError::custom("response body is not available as bytes"))?;
|
744 + | Ok(Box::new(self.codec.create_deserializer(body)))
|
745 + | }
|
746 + |
|
747 + | fn serialize_body(
|
748 + | &self,
|
749 + | input: &dyn SerializableStruct,
|
750 + | input_schema: &Schema,
|
751 + | _endpoint: &str,
|
752 + | _cfg: &ConfigBag,
|
753 + | ) -> Result<Request, SerdeError> {
|
754 + | // Check if there are body members (non-HTTP-bound) to determine Content-Type and body behavior.
|
755 + | let has_body_members = input_schema.members().iter().any(|m| {
|
756 + | m.http_header().is_none()
|
757 + | && m.http_query().is_none()
|
758 + | && m.http_label().is_none()
|
759 + | && m.http_prefix_headers().is_none()
|
760 + | && m.http_query_params().is_none()
|
761 + | && m.http_payload().is_none()
|
762 + | });
|
763 + |
|
764 + | // Use HttpBindingSerializer to filter out HTTP-bound members, keeping only body members.
|
765 + | // The collected headers/query/labels are discarded — the caller writes those directly.
|
766 + | let mut request = if has_body_members {
|
767 + | let serializer = self.codec.create_serializer();
|
768 + | let mut binding_ser = HttpBindingSerializer::new(serializer, None);
|
769 + | binding_ser.write_struct(input_schema, input)?;
|
770 + | let body = binding_ser.finish_body();
|
771 + | let mut r = Request::new(SdkBody::from(body));
|
772 + | r.headers_mut().insert("Content-Type", self.content_type);
|
773 + | if let Some(len) = r.body().content_length() {
|
774 + | r.headers_mut().insert("Content-Length", len.to_string());
|
775 + | }
|
776 + | r
|
777 + | } else {
|
778 + | Request::new(SdkBody::empty())
|
779 + | };
|
780 + |
|
781 + | // Set HTTP method from @http trait.
|
782 + | if let Some(http) = input_schema.http() {
|
783 + | request
|
784 + | .set_method(http.method())
|
785 + | .map_err(|e| SerdeError::custom(format!("invalid HTTP method: {e}")))?;
|
786 + | }
|
787 + | Ok(request)
|
788 + | }
|
789 + | }
|
790 + |
|
791 + | #[cfg(test)]
|
792 + | mod tests {
|
793 + | use super::*;
|
794 + | use crate::serde::SerializableStruct;
|
795 + | use crate::{prelude::*, ShapeType};
|
796 + |
|
797 + | struct TestSerializer {
|
798 + | output: Vec<u8>,
|
799 + | }
|
800 + |
|
801 + | impl FinishSerializer for TestSerializer {
|
802 + | fn finish(self) -> Vec<u8> {
|
803 + | self.output
|
804 + | }
|
805 + | }
|
806 + |
|
807 + | impl ShapeSerializer for TestSerializer {
|
808 + | fn write_struct(
|
809 + | &mut self,
|
810 + | _: &Schema,
|
811 + | value: &dyn SerializableStruct,
|
812 + | ) -> Result<(), SerdeError> {
|
813 + | self.output.push(b'{');
|
814 + | value.serialize_members(self)?;
|
815 + | self.output.push(b'}');
|
816 + | Ok(())
|
817 + | }
|
818 + | fn write_list(
|
819 + | &mut self,
|
820 + | _: &Schema,
|
821 + | _: &dyn Fn(&mut dyn ShapeSerializer) -> Result<(), SerdeError>,
|
822 + | ) -> Result<(), SerdeError> {
|
823 + | Ok(())
|
824 + | }
|
825 + | fn write_map(
|
826 + | &mut self,
|
827 + | _: &Schema,
|
828 + | _: &dyn Fn(&mut dyn ShapeSerializer) -> Result<(), SerdeError>,
|
829 + | ) -> Result<(), SerdeError> {
|
830 + | Ok(())
|
831 + | }
|
832 + | fn write_boolean(&mut self, _: &Schema, _: bool) -> Result<(), SerdeError> {
|
833 + | Ok(())
|
834 + | }
|
835 + | fn write_byte(&mut self, _: &Schema, _: i8) -> Result<(), SerdeError> {
|
836 + | Ok(())
|
837 + | }
|
838 + | fn write_short(&mut self, _: &Schema, _: i16) -> Result<(), SerdeError> {
|
839 + | Ok(())
|
840 + | }
|
841 + | fn write_integer(&mut self, _: &Schema, _: i32) -> Result<(), SerdeError> {
|
842 + | Ok(())
|
843 + | }
|
844 + | fn write_long(&mut self, _: &Schema, _: i64) -> Result<(), SerdeError> {
|
845 + | Ok(())
|
846 + | }
|
847 + | fn write_float(&mut self, _: &Schema, _: f32) -> Result<(), SerdeError> {
|
848 + | Ok(())
|
849 + | }
|
850 + | fn write_double(&mut self, _: &Schema, _: f64) -> Result<(), SerdeError> {
|
851 + | Ok(())
|
852 + | }
|
853 + | fn write_big_integer(
|
854 + | &mut self,
|
855 + | _: &Schema,
|
856 + | _: &aws_smithy_types::BigInteger,
|
857 + | ) -> Result<(), SerdeError> {
|
858 + | Ok(())
|
859 + | }
|
860 + | fn write_big_decimal(
|
861 + | &mut self,
|
862 + | _: &Schema,
|
863 + | _: &aws_smithy_types::BigDecimal,
|
864 + | ) -> Result<(), SerdeError> {
|
865 + | Ok(())
|
866 + | }
|
867 + | fn write_string(&mut self, _: &Schema, v: &str) -> Result<(), SerdeError> {
|
868 + | self.output.extend_from_slice(v.as_bytes());
|
869 + | Ok(())
|
870 + | }
|
871 + | fn write_blob(&mut self, _: &Schema, _: &aws_smithy_types::Blob) -> Result<(), SerdeError> {
|
872 + | Ok(())
|
873 + | }
|
874 + | fn write_timestamp(
|
875 + | &mut self,
|
876 + | _: &Schema,
|
877 + | _: &aws_smithy_types::DateTime,
|
878 + | ) -> Result<(), SerdeError> {
|
879 + | Ok(())
|
880 + | }
|
881 + | fn write_document(
|
882 + | &mut self,
|
883 + | _: &Schema,
|
884 + | _: &aws_smithy_types::Document,
|
885 + | ) -> Result<(), SerdeError> {
|
886 + | Ok(())
|
887 + | }
|
888 + | fn write_null(&mut self, _: &Schema) -> Result<(), SerdeError> {
|
889 + | Ok(())
|
890 + | }
|
891 + | }
|
892 + |
|
893 + | struct TestDeserializer<'a> {
|
894 + | input: &'a [u8],
|
895 + | }
|
896 + |
|
897 + | impl ShapeDeserializer for TestDeserializer<'_> {
|
898 + | fn read_struct(
|
899 + | &mut self,
|
900 + | _: &Schema,
|
901 + | _: &mut dyn FnMut(&Schema, &mut dyn ShapeDeserializer) -> Result<(), SerdeError>,
|
902 + | ) -> Result<(), SerdeError> {
|
903 + | Ok(())
|
904 + | }
|
905 + | fn read_list(
|
906 + | &mut self,
|
907 + | _: &Schema,
|
908 + | _: &mut dyn FnMut(&mut dyn ShapeDeserializer) -> Result<(), SerdeError>,
|
909 + | ) -> Result<(), SerdeError> {
|
910 + | Ok(())
|
911 + | }
|
912 + | fn read_map(
|
913 + | &mut self,
|
914 + | _: &Schema,
|
915 + | _: &mut dyn FnMut(String, &mut dyn ShapeDeserializer) -> Result<(), SerdeError>,
|
916 + | ) -> Result<(), SerdeError> {
|
917 + | Ok(())
|
918 + | }
|
919 + | fn read_boolean(&mut self, _: &Schema) -> Result<bool, SerdeError> {
|
920 + | Ok(false)
|
921 + | }
|
922 + | fn read_byte(&mut self, _: &Schema) -> Result<i8, SerdeError> {
|
923 + | Ok(0)
|
924 + | }
|
925 + | fn read_short(&mut self, _: &Schema) -> Result<i16, SerdeError> {
|
926 + | Ok(0)
|
927 + | }
|
928 + | fn read_integer(&mut self, _: &Schema) -> Result<i32, SerdeError> {
|
929 + | Ok(0)
|
930 + | }
|
931 + | fn read_long(&mut self, _: &Schema) -> Result<i64, SerdeError> {
|
932 + | Ok(0)
|
933 + | }
|
934 + | fn read_float(&mut self, _: &Schema) -> Result<f32, SerdeError> {
|
935 + | Ok(0.0)
|
936 + | }
|
937 + | fn read_double(&mut self, _: &Schema) -> Result<f64, SerdeError> {
|
938 + | Ok(0.0)
|
939 + | }
|
940 + | fn read_big_integer(
|
941 + | &mut self,
|
942 + | _: &Schema,
|
943 + | ) -> Result<aws_smithy_types::BigInteger, SerdeError> {
|
944 + | use std::str::FromStr;
|
945 + | Ok(aws_smithy_types::BigInteger::from_str("0").unwrap())
|
946 + | }
|
947 + | fn read_big_decimal(
|
948 + | &mut self,
|
949 + | _: &Schema,
|
950 + | ) -> Result<aws_smithy_types::BigDecimal, SerdeError> {
|
951 + | use std::str::FromStr;
|
952 + | Ok(aws_smithy_types::BigDecimal::from_str("0").unwrap())
|
953 + | }
|
954 + | fn read_string(&mut self, _: &Schema) -> Result<String, SerdeError> {
|
955 + | Ok(String::from_utf8_lossy(self.input).into_owned())
|
956 + | }
|
957 + | fn read_blob(&mut self, _: &Schema) -> Result<aws_smithy_types::Blob, SerdeError> {
|
958 + | Ok(aws_smithy_types::Blob::new(vec![]))
|
959 + | }
|
960 + | fn read_timestamp(&mut self, _: &Schema) -> Result<aws_smithy_types::DateTime, SerdeError> {
|
961 + | Ok(aws_smithy_types::DateTime::from_secs(0))
|
962 + | }
|
963 + | fn read_document(&mut self, _: &Schema) -> Result<aws_smithy_types::Document, SerdeError> {
|
964 + | Ok(aws_smithy_types::Document::Null)
|
965 + | }
|
966 + | fn is_null(&self) -> bool {
|
967 + | false
|
968 + | }
|
969 + | fn container_size(&self) -> Option<usize> {
|
970 + | None
|
971 + | }
|
972 + | }
|
973 + |
|
974 + | #[derive(Debug)]
|
975 + | struct TestCodec;
|
976 + |
|
977 + | impl Codec for TestCodec {
|
978 + | type Serializer = TestSerializer;
|
979 + | type Deserializer<'a> = TestDeserializer<'a>;
|
980 + | fn create_serializer(&self) -> Self::Serializer {
|
981 + | TestSerializer { output: Vec::new() }
|
982 + | }
|
983 + | fn create_deserializer<'a>(&self, input: &'a [u8]) -> Self::Deserializer<'a> {
|
984 + | TestDeserializer { input }
|
985 + | }
|
986 + | }
|
987 + |
|
988 + | static TEST_SCHEMA: Schema =
|
989 + | Schema::new(crate::shape_id!("test", "TestStruct"), ShapeType::Structure);
|
990 + |
|
991 + | struct EmptyStruct;
|
992 + | impl SerializableStruct for EmptyStruct {
|
993 + | fn serialize_members(&self, _: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
994 + | Ok(())
|
995 + | }
|
996 + | }
|
997 + |
|
998 + | static NAME_MEMBER: Schema = Schema::new_member(
|
999 + | crate::shape_id!("test", "TestStruct"),
|
1000 + | ShapeType::String,
|
1001 + | "name",
|
1002 + | 0,
|
1003 + | );
|
1004 + | static MEMBERS: &[&Schema] = &[&NAME_MEMBER];
|
1005 + | static STRUCT_WITH_MEMBER: Schema = Schema::new_struct(
|
1006 + | crate::shape_id!("test", "TestStruct"),
|
1007 + | ShapeType::Structure,
|
1008 + | MEMBERS,
|
1009 + | );
|
1010 + |
|
1011 + | struct NameStruct;
|
1012 + | impl SerializableStruct for NameStruct {
|
1013 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1014 + | s.write_string(&NAME_MEMBER, "Alice")
|
1015 + | }
|
1016 + | }
|
1017 + |
|
1018 + | fn make_protocol() -> HttpBindingProtocol<TestCodec> {
|
1019 + | HttpBindingProtocol::new(
|
1020 + | crate::shape_id!("test", "proto"),
|
1021 + | TestCodec,
|
1022 + | "application/test",
|
1023 + | )
|
1024 + | }
|
1025 + |
|
1026 + | #[test]
|
1027 + | fn serialize_sets_content_type() {
|
1028 + | // A struct with body members gets Content-Type
|
1029 + | let request = make_protocol()
|
1030 + | .serialize_request(
|
1031 + | &EmptyStruct,
|
1032 + | &STRUCT_WITH_MEMBER,
|
1033 + | "https://example.com",
|
1034 + | &ConfigBag::base(),
|
1035 + | )
|
1036 + | .unwrap();
|
1037 + | assert_eq!(
|
1038 + | request.headers().get("Content-Type").unwrap(),
|
1039 + | "application/test"
|
1040 + | );
|
1041 + | }
|
1042 + |
|
1043 + | #[test]
|
1044 + | fn serialize_no_body_members_omits_content_type() {
|
1045 + | // A struct with no members gets no Content-Type per REST-JSON spec
|
1046 + | let request = make_protocol()
|
1047 + | .serialize_request(
|
1048 + | &EmptyStruct,
|
1049 + | &TEST_SCHEMA,
|
1050 + | "https://example.com",
|
1051 + | &ConfigBag::base(),
|
1052 + | )
|
1053 + | .unwrap();
|
1054 + | assert!(request.headers().get("Content-Type").is_none());
|
1055 + | }
|
1056 + |
|
1057 + | #[test]
|
1058 + | fn serialize_sets_uri() {
|
1059 + | let request = make_protocol()
|
1060 + | .serialize_request(
|
1061 + | &EmptyStruct,
|
1062 + | &TEST_SCHEMA,
|
1063 + | "https://example.com/path",
|
1064 + | &ConfigBag::base(),
|
1065 + | )
|
1066 + | .unwrap();
|
1067 + | assert_eq!(request.uri(), "https://example.com/path");
|
1068 + | }
|
1069 + |
|
1070 + | #[test]
|
1071 + | fn serialize_body() {
|
1072 + | let request = make_protocol()
|
1073 + | .serialize_request(
|
1074 + | &NameStruct,
|
1075 + | &STRUCT_WITH_MEMBER,
|
1076 + | "https://example.com",
|
1077 + | &ConfigBag::base(),
|
1078 + | )
|
1079 + | .unwrap();
|
1080 + | assert_eq!(request.body().bytes().unwrap(), b"{Alice}");
|
1081 + | }
|
1082 + |
|
1083 + | #[test]
|
1084 + | fn deserialize_response() {
|
1085 + | let response = Response::new(
|
1086 + | 200u16.try_into().unwrap(),
|
1087 + | SdkBody::from(r#"{"name":"Bob"}"#),
|
1088 + | );
|
1089 + | let mut deser = make_protocol()
|
1090 + | .deserialize_response(&response, &TEST_SCHEMA, &ConfigBag::base())
|
1091 + | .unwrap();
|
1092 + | assert_eq!(deser.read_string(&STRING).unwrap(), r#"{"name":"Bob"}"#);
|
1093 + | }
|
1094 + |
|
1095 + | #[test]
|
1096 + | fn update_endpoint() {
|
1097 + | let mut request = make_protocol()
|
1098 + | .serialize_request(
|
1099 + | &EmptyStruct,
|
1100 + | &TEST_SCHEMA,
|
1101 + | "https://old.example.com",
|
1102 + | &ConfigBag::base(),
|
1103 + | )
|
1104 + | .unwrap();
|
1105 + | let endpoint = aws_smithy_types::endpoint::Endpoint::builder()
|
1106 + | .url("https://new.example.com")
|
1107 + | .build();
|
1108 + | make_protocol()
|
1109 + | .update_endpoint(&mut request, &endpoint, &ConfigBag::base())
|
1110 + | .unwrap();
|
1111 + | assert_eq!(request.uri(), "https://new.example.com/");
|
1112 + | }
|
1113 + |
|
1114 + | #[test]
|
1115 + | fn protocol_id() {
|
1116 + | let protocol = HttpBindingProtocol::new(
|
1117 + | crate::shape_id!("aws.protocols", "restJson1"),
|
1118 + | TestCodec,
|
1119 + | "application/json",
|
1120 + | );
|
1121 + | assert_eq!(protocol.protocol_id().as_str(), "aws.protocols#restJson1");
|
1122 + | }
|
1123 + |
|
1124 + | #[test]
|
1125 + | fn invalid_uri_returns_error() {
|
1126 + | assert!(make_protocol()
|
1127 + | .serialize_request(
|
1128 + | &EmptyStruct,
|
1129 + | &TEST_SCHEMA,
|
1130 + | "not a valid uri\n\n",
|
1131 + | &ConfigBag::base()
|
1132 + | )
|
1133 + | .is_err());
|
1134 + | }
|
1135 + |
|
1136 + | // -- @httpHeader tests --
|
1137 + |
|
1138 + | static HEADER_MEMBER: Schema = Schema::new_member(
|
1139 + | crate::shape_id!("test", "S"),
|
1140 + | ShapeType::String,
|
1141 + | "xToken",
|
1142 + | 0,
|
1143 + | )
|
1144 + | .with_http_header("X-Token");
|
1145 + |
|
1146 + | static HEADER_SCHEMA: Schema = Schema::new_struct(
|
1147 + | crate::shape_id!("test", "S"),
|
1148 + | ShapeType::Structure,
|
1149 + | &[&HEADER_MEMBER],
|
1150 + | );
|
1151 + |
|
1152 + | struct HeaderStruct;
|
1153 + | impl SerializableStruct for HeaderStruct {
|
1154 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1155 + | s.write_string(&HEADER_MEMBER, "my-token-value")
|
1156 + | }
|
1157 + | }
|
1158 + |
|
1159 + | #[test]
|
1160 + | fn http_header_string() {
|
1161 + | let request = make_protocol()
|
1162 + | .serialize_request(
|
1163 + | &HeaderStruct,
|
1164 + | &HEADER_SCHEMA,
|
1165 + | "https://example.com",
|
1166 + | &ConfigBag::base(),
|
1167 + | )
|
1168 + | .unwrap();
|
1169 + | assert_eq!(request.headers().get("X-Token").unwrap(), "my-token-value");
|
1170 + | }
|
1171 + |
|
1172 + | static INT_HEADER_MEMBER: Schema = Schema::new_member(
|
1173 + | crate::shape_id!("test", "S"),
|
1174 + | ShapeType::Integer,
|
1175 + | "retryCount",
|
1176 + | 0,
|
1177 + | )
|
1178 + | .with_http_header("X-Retry-Count");
|
1179 + |
|
1180 + | static INT_HEADER_SCHEMA: Schema = Schema::new_struct(
|
1181 + | crate::shape_id!("test", "S"),
|
1182 + | ShapeType::Structure,
|
1183 + | &[&INT_HEADER_MEMBER],
|
1184 + | );
|
1185 + |
|
1186 + | struct IntHeaderStruct;
|
1187 + | impl SerializableStruct for IntHeaderStruct {
|
1188 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1189 + | s.write_integer(&INT_HEADER_MEMBER, 3)
|
1190 + | }
|
1191 + | }
|
1192 + |
|
1193 + | #[test]
|
1194 + | fn http_header_integer() {
|
1195 + | let request = make_protocol()
|
1196 + | .serialize_request(
|
1197 + | &IntHeaderStruct,
|
1198 + | &INT_HEADER_SCHEMA,
|
1199 + | "https://example.com",
|
1200 + | &ConfigBag::base(),
|
1201 + | )
|
1202 + | .unwrap();
|
1203 + | assert_eq!(request.headers().get("X-Retry-Count").unwrap(), "3");
|
1204 + | }
|
1205 + |
|
1206 + | static BOOL_HEADER_MEMBER: Schema = Schema::new_member(
|
1207 + | crate::shape_id!("test", "S"),
|
1208 + | ShapeType::Boolean,
|
1209 + | "verbose",
|
1210 + | 0,
|
1211 + | )
|
1212 + | .with_http_header("X-Verbose");
|
1213 + |
|
1214 + | static BOOL_HEADER_SCHEMA: Schema = Schema::new_struct(
|
1215 + | crate::shape_id!("test", "S"),
|
1216 + | ShapeType::Structure,
|
1217 + | &[&BOOL_HEADER_MEMBER],
|
1218 + | );
|
1219 + |
|
1220 + | struct BoolHeaderStruct;
|
1221 + | impl SerializableStruct for BoolHeaderStruct {
|
1222 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1223 + | s.write_boolean(&BOOL_HEADER_MEMBER, true)
|
1224 + | }
|
1225 + | }
|
1226 + |
|
1227 + | #[test]
|
1228 + | fn http_header_boolean() {
|
1229 + | let request = make_protocol()
|
1230 + | .serialize_request(
|
1231 + | &BoolHeaderStruct,
|
1232 + | &BOOL_HEADER_SCHEMA,
|
1233 + | "https://example.com",
|
1234 + | &ConfigBag::base(),
|
1235 + | )
|
1236 + | .unwrap();
|
1237 + | assert_eq!(request.headers().get("X-Verbose").unwrap(), "true");
|
1238 + | }
|
1239 + |
|
1240 + | // -- @httpQuery tests --
|
1241 + |
|
1242 + | static QUERY_MEMBER: Schema =
|
1243 + | Schema::new_member(crate::shape_id!("test", "S"), ShapeType::String, "color", 0)
|
1244 + | .with_http_query("color");
|
1245 + |
|
1246 + | static QUERY_SCHEMA: Schema = Schema::new_struct(
|
1247 + | crate::shape_id!("test", "S"),
|
1248 + | ShapeType::Structure,
|
1249 + | &[&QUERY_MEMBER],
|
1250 + | );
|
1251 + |
|
1252 + | struct QueryStruct;
|
1253 + | impl SerializableStruct for QueryStruct {
|
1254 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1255 + | s.write_string(&QUERY_MEMBER, "blue")
|
1256 + | }
|
1257 + | }
|
1258 + |
|
1259 + | #[test]
|
1260 + | fn http_query_string() {
|
1261 + | let request = make_protocol()
|
1262 + | .serialize_request(
|
1263 + | &QueryStruct,
|
1264 + | &QUERY_SCHEMA,
|
1265 + | "https://example.com/things",
|
1266 + | &ConfigBag::base(),
|
1267 + | )
|
1268 + | .unwrap();
|
1269 + | assert_eq!(request.uri(), "https://example.com/things?color=blue");
|
1270 + | }
|
1271 + |
|
1272 + | static INT_QUERY_MEMBER: Schema =
|
1273 + | Schema::new_member(crate::shape_id!("test", "S"), ShapeType::Integer, "size", 0)
|
1274 + | .with_http_query("size");
|
1275 + |
|
1276 + | static INT_QUERY_SCHEMA: Schema = Schema::new_struct(
|
1277 + | crate::shape_id!("test", "S"),
|
1278 + | ShapeType::Structure,
|
1279 + | &[&INT_QUERY_MEMBER],
|
1280 + | );
|
1281 + |
|
1282 + | struct IntQueryStruct;
|
1283 + | impl SerializableStruct for IntQueryStruct {
|
1284 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1285 + | s.write_integer(&INT_QUERY_MEMBER, 42)
|
1286 + | }
|
1287 + | }
|
1288 + |
|
1289 + | #[test]
|
1290 + | fn http_query_integer() {
|
1291 + | let request = make_protocol()
|
1292 + | .serialize_request(
|
1293 + | &IntQueryStruct,
|
1294 + | &INT_QUERY_SCHEMA,
|
1295 + | "https://example.com/things",
|
1296 + | &ConfigBag::base(),
|
1297 + | )
|
1298 + | .unwrap();
|
1299 + | assert_eq!(request.uri(), "https://example.com/things?size=42");
|
1300 + | }
|
1301 + |
|
1302 + | // -- Multiple @httpQuery params --
|
1303 + |
|
1304 + | static Q1: Schema =
|
1305 + | Schema::new_member(crate::shape_id!("test", "S"), ShapeType::String, "a", 0)
|
1306 + | .with_http_query("a");
|
1307 + | static Q2: Schema =
|
1308 + | Schema::new_member(crate::shape_id!("test", "S"), ShapeType::String, "b", 1)
|
1309 + | .with_http_query("b");
|
1310 + | static MULTI_QUERY_SCHEMA: Schema = Schema::new_struct(
|
1311 + | crate::shape_id!("test", "S"),
|
1312 + | ShapeType::Structure,
|
1313 + | &[&Q1, &Q2],
|
1314 + | );
|
1315 + |
|
1316 + | struct MultiQueryStruct;
|
1317 + | impl SerializableStruct for MultiQueryStruct {
|
1318 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1319 + | s.write_string(&Q1, "x")?;
|
1320 + | s.write_string(&Q2, "y")
|
1321 + | }
|
1322 + | }
|
1323 + |
|
1324 + | #[test]
|
1325 + | fn http_query_multiple_params() {
|
1326 + | let request = make_protocol()
|
1327 + | .serialize_request(
|
1328 + | &MultiQueryStruct,
|
1329 + | &MULTI_QUERY_SCHEMA,
|
1330 + | "https://example.com",
|
1331 + | &ConfigBag::base(),
|
1332 + | )
|
1333 + | .unwrap();
|
1334 + | assert_eq!(request.uri(), "https://example.com?a=x&b=y");
|
1335 + | }
|
1336 + |
|
1337 + | // -- @httpQuery with percent-encoding --
|
1338 + |
|
1339 + | #[test]
|
1340 + | fn http_query_percent_encodes_values() {
|
1341 + | struct SpaceQueryStruct;
|
1342 + | impl SerializableStruct for SpaceQueryStruct {
|
1343 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1344 + | s.write_string(&QUERY_MEMBER, "hello world")
|
1345 + | }
|
1346 + | }
|
1347 + | let request = make_protocol()
|
1348 + | .serialize_request(
|
1349 + | &SpaceQueryStruct,
|
1350 + | &QUERY_SCHEMA,
|
1351 + | "https://example.com",
|
1352 + | &ConfigBag::base(),
|
1353 + | )
|
1354 + | .unwrap();
|
1355 + | assert_eq!(request.uri(), "https://example.com?color=hello%20world");
|
1356 + | }
|
1357 + |
|
1358 + | // -- @httpLabel tests --
|
1359 + |
|
1360 + | static LABEL_MEMBER: Schema = Schema::new_member(
|
1361 + | crate::shape_id!("test", "S"),
|
1362 + | ShapeType::String,
|
1363 + | "bucketName",
|
1364 + | 0,
|
1365 + | )
|
1366 + | .with_http_label();
|
1367 + |
|
1368 + | static LABEL_SCHEMA: Schema = Schema::new_struct(
|
1369 + | crate::shape_id!("test", "S"),
|
1370 + | ShapeType::Structure,
|
1371 + | &[&LABEL_MEMBER],
|
1372 + | );
|
1373 + |
|
1374 + | struct LabelStruct;
|
1375 + | impl SerializableStruct for LabelStruct {
|
1376 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1377 + | s.write_string(&LABEL_MEMBER, "my-bucket")
|
1378 + | }
|
1379 + | }
|
1380 + |
|
1381 + | #[test]
|
1382 + | fn http_label_substitution() {
|
1383 + | let request = make_protocol()
|
1384 + | .serialize_request(
|
1385 + | &LabelStruct,
|
1386 + | &LABEL_SCHEMA,
|
1387 + | "https://example.com/{bucketName}/objects",
|
1388 + | &ConfigBag::base(),
|
1389 + | )
|
1390 + | .unwrap();
|
1391 + | assert_eq!(request.uri(), "https://example.com/my-bucket/objects");
|
1392 + | }
|
1393 + |
|
1394 + | #[test]
|
1395 + | fn http_label_percent_encodes() {
|
1396 + | struct SpecialLabelStruct;
|
1397 + | impl SerializableStruct for SpecialLabelStruct {
|
1398 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1399 + | s.write_string(&LABEL_MEMBER, "my bucket/name")
|
1400 + | }
|
1401 + | }
|
1402 + | let request = make_protocol()
|
1403 + | .serialize_request(
|
1404 + | &SpecialLabelStruct,
|
1405 + | &LABEL_SCHEMA,
|
1406 + | "https://example.com/{bucketName}",
|
1407 + | &ConfigBag::base(),
|
1408 + | )
|
1409 + | .unwrap();
|
1410 + | assert!(request.uri().contains("my%20bucket%2Fname"));
|
1411 + | }
|
1412 + |
|
1413 + | static INT_LABEL_MEMBER: Schema = Schema::new_member(
|
1414 + | crate::shape_id!("test", "S"),
|
1415 + | ShapeType::Integer,
|
1416 + | "itemId",
|
1417 + | 0,
|
1418 + | )
|
1419 + | .with_http_label();
|
1420 + |
|
1421 + | static INT_LABEL_SCHEMA: Schema = Schema::new_struct(
|
1422 + | crate::shape_id!("test", "S"),
|
1423 + | ShapeType::Structure,
|
1424 + | &[&INT_LABEL_MEMBER],
|
1425 + | );
|
1426 + |
|
1427 + | struct IntLabelStruct;
|
1428 + | impl SerializableStruct for IntLabelStruct {
|
1429 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1430 + | s.write_integer(&INT_LABEL_MEMBER, 123)
|
1431 + | }
|
1432 + | }
|
1433 + |
|
1434 + | #[test]
|
1435 + | fn http_label_integer() {
|
1436 + | let request = make_protocol()
|
1437 + | .serialize_request(
|
1438 + | &IntLabelStruct,
|
1439 + | &INT_LABEL_SCHEMA,
|
1440 + | "https://example.com/items/{itemId}",
|
1441 + | &ConfigBag::base(),
|
1442 + | )
|
1443 + | .unwrap();
|
1444 + | assert_eq!(request.uri(), "https://example.com/items/123");
|
1445 + | }
|
1446 + |
|
1447 + | // -- Combined: @httpHeader + @httpQuery + @httpLabel + body --
|
1448 + |
|
1449 + | static COMBINED_LABEL: Schema =
|
1450 + | Schema::new_member(crate::shape_id!("test", "S"), ShapeType::String, "id", 0)
|
1451 + | .with_http_label();
|
1452 + | static COMBINED_HEADER: Schema =
|
1453 + | Schema::new_member(crate::shape_id!("test", "S"), ShapeType::String, "token", 1)
|
1454 + | .with_http_header("X-Token");
|
1455 + | static COMBINED_QUERY: Schema = Schema::new_member(
|
1456 + | crate::shape_id!("test", "S"),
|
1457 + | ShapeType::String,
|
1458 + | "filter",
|
1459 + | 2,
|
1460 + | )
|
1461 + | .with_http_query("filter");
|
1462 + | static COMBINED_BODY: Schema =
|
1463 + | Schema::new_member(crate::shape_id!("test", "S"), ShapeType::String, "data", 3);
|
1464 + | static COMBINED_SCHEMA: Schema = Schema::new_struct(
|
1465 + | crate::shape_id!("test", "S"),
|
1466 + | ShapeType::Structure,
|
1467 + | &[
|
1468 + | &COMBINED_LABEL,
|
1469 + | &COMBINED_HEADER,
|
1470 + | &COMBINED_QUERY,
|
1471 + | &COMBINED_BODY,
|
1472 + | ],
|
1473 + | );
|
1474 + |
|
1475 + | struct CombinedStruct;
|
1476 + | impl SerializableStruct for CombinedStruct {
|
1477 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1478 + | s.write_string(&COMBINED_LABEL, "item-42")?;
|
1479 + | s.write_string(&COMBINED_HEADER, "secret")?;
|
1480 + | s.write_string(&COMBINED_QUERY, "active")?;
|
1481 + | s.write_string(&COMBINED_BODY, "payload-data")
|
1482 + | }
|
1483 + | }
|
1484 + |
|
1485 + | #[test]
|
1486 + | fn combined_bindings() {
|
1487 + | let request = make_protocol()
|
1488 + | .serialize_request(
|
1489 + | &CombinedStruct,
|
1490 + | &COMBINED_SCHEMA,
|
1491 + | "https://example.com/{id}/details",
|
1492 + | &ConfigBag::base(),
|
1493 + | )
|
1494 + | .unwrap();
|
1495 + | assert_eq!(
|
1496 + | request.uri(),
|
1497 + | "https://example.com/item-42/details?filter=active"
|
1498 + | );
|
1499 + | // Header
|
1500 + | assert_eq!(request.headers().get("X-Token").unwrap(), "secret");
|
1501 + | // Body contains only the unbound member
|
1502 + | let body = request.body().bytes().unwrap();
|
1503 + | assert!(body
|
1504 + | .windows(b"payload-data".len())
|
1505 + | .any(|w| w == b"payload-data"));
|
1506 + | }
|
1507 + |
|
1508 + | // -- @httpPrefixHeaders tests --
|
1509 + |
|
1510 + | static PREFIX_MEMBER: Schema =
|
1511 + | Schema::new_member(crate::shape_id!("test", "S"), ShapeType::Map, "metadata", 0)
|
1512 + | .with_http_prefix_headers("X-Meta-");
|
1513 + |
|
1514 + | static PREFIX_SCHEMA: Schema = Schema::new_struct(
|
1515 + | crate::shape_id!("test", "S"),
|
1516 + | ShapeType::Structure,
|
1517 + | &[&PREFIX_MEMBER],
|
1518 + | );
|
1519 + |
|
1520 + | struct PrefixHeaderStruct;
|
1521 + | impl SerializableStruct for PrefixHeaderStruct {
|
1522 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1523 + | s.write_map(&PREFIX_MEMBER, &|s| {
|
1524 + | s.write_string(&STRING, "Color")?;
|
1525 + | s.write_string(&STRING, "red")?;
|
1526 + | s.write_string(&STRING, "Size")?;
|
1527 + | s.write_string(&STRING, "large")?;
|
1528 + | Ok(())
|
1529 + | })
|
1530 + | }
|
1531 + | }
|
1532 + |
|
1533 + | #[test]
|
1534 + | fn http_prefix_headers() {
|
1535 + | let request = make_protocol()
|
1536 + | .serialize_request(
|
1537 + | &PrefixHeaderStruct,
|
1538 + | &PREFIX_SCHEMA,
|
1539 + | "https://example.com",
|
1540 + | &ConfigBag::base(),
|
1541 + | )
|
1542 + | .unwrap();
|
1543 + | assert_eq!(request.headers().get("X-Meta-Color").unwrap(), "red");
|
1544 + | assert_eq!(request.headers().get("X-Meta-Size").unwrap(), "large");
|
1545 + | }
|
1546 + |
|
1547 + | // -- @httpQueryParams tests --
|
1548 + |
|
1549 + | static QUERY_PARAMS_MEMBER: Schema =
|
1550 + | Schema::new_member(crate::shape_id!("test", "S"), ShapeType::Map, "params", 0)
|
1551 + | .with_http_query_params();
|
1552 + |
|
1553 + | static QUERY_PARAMS_SCHEMA: Schema = Schema::new_struct(
|
1554 + | crate::shape_id!("test", "S"),
|
1555 + | ShapeType::Structure,
|
1556 + | &[&QUERY_PARAMS_MEMBER],
|
1557 + | );
|
1558 + |
|
1559 + | struct QueryParamsStruct;
|
1560 + | impl SerializableStruct for QueryParamsStruct {
|
1561 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1562 + | s.write_map(&QUERY_PARAMS_MEMBER, &|s| {
|
1563 + | s.write_string(&STRING, "page")?;
|
1564 + | s.write_string(&STRING, "2")?;
|
1565 + | s.write_string(&STRING, "limit")?;
|
1566 + | s.write_string(&STRING, "50")?;
|
1567 + | Ok(())
|
1568 + | })
|
1569 + | }
|
1570 + | }
|
1571 + |
|
1572 + | #[test]
|
1573 + | fn http_query_params() {
|
1574 + | let request = make_protocol()
|
1575 + | .serialize_request(
|
1576 + | &QueryParamsStruct,
|
1577 + | &QUERY_PARAMS_SCHEMA,
|
1578 + | "https://example.com",
|
1579 + | &ConfigBag::base(),
|
1580 + | )
|
1581 + | .unwrap();
|
1582 + | assert_eq!(request.uri(), "https://example.com?page=2&limit=50");
|
1583 + | }
|
1584 + |
|
1585 + | // -- Timestamp in header defaults to http-date --
|
1586 + |
|
1587 + | static TS_HEADER_MEMBER: Schema = Schema::new_member(
|
1588 + | crate::shape_id!("test", "S"),
|
1589 + | ShapeType::Timestamp,
|
1590 + | "ifModified",
|
1591 + | 0,
|
1592 + | )
|
1593 + | .with_http_header("If-Modified-Since");
|
1594 + |
|
1595 + | static TS_HEADER_SCHEMA: Schema = Schema::new_struct(
|
1596 + | crate::shape_id!("test", "S"),
|
1597 + | ShapeType::Structure,
|
1598 + | &[&TS_HEADER_MEMBER],
|
1599 + | );
|
1600 + |
|
1601 + | struct TimestampHeaderStruct;
|
1602 + | impl SerializableStruct for TimestampHeaderStruct {
|
1603 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1604 + | s.write_timestamp(&TS_HEADER_MEMBER, &aws_smithy_types::DateTime::from_secs(0))
|
1605 + | }
|
1606 + | }
|
1607 + |
|
1608 + | #[test]
|
1609 + | fn timestamp_header_uses_http_date() {
|
1610 + | let request = make_protocol()
|
1611 + | .serialize_request(
|
1612 + | &TimestampHeaderStruct,
|
1613 + | &TS_HEADER_SCHEMA,
|
1614 + | "https://example.com",
|
1615 + | &ConfigBag::base(),
|
1616 + | )
|
1617 + | .unwrap();
|
1618 + | let value = request.headers().get("If-Modified-Since").unwrap();
|
1619 + | // http-date format: "Thu, 01 Jan 1970 00:00:00 GMT"
|
1620 + | assert!(value.contains("1970"), "expected http-date, got: {value}");
|
1621 + | }
|
1622 + |
|
1623 + | // -- Timestamp in query defaults to date-time --
|
1624 + |
|
1625 + | static TS_QUERY_MEMBER: Schema = Schema::new_member(
|
1626 + | crate::shape_id!("test", "S"),
|
1627 + | ShapeType::Timestamp,
|
1628 + | "since",
|
1629 + | 0,
|
1630 + | )
|
1631 + | .with_http_query("since");
|
1632 + |
|
1633 + | static TS_QUERY_SCHEMA: Schema = Schema::new_struct(
|
1634 + | crate::shape_id!("test", "S"),
|
1635 + | ShapeType::Structure,
|
1636 + | &[&TS_QUERY_MEMBER],
|
1637 + | );
|
1638 + |
|
1639 + | struct TimestampQueryStruct;
|
1640 + | impl SerializableStruct for TimestampQueryStruct {
|
1641 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1642 + | s.write_timestamp(&TS_QUERY_MEMBER, &aws_smithy_types::DateTime::from_secs(0))
|
1643 + | }
|
1644 + | }
|
1645 + |
|
1646 + | #[test]
|
1647 + | fn timestamp_query_uses_date_time() {
|
1648 + | let request = make_protocol()
|
1649 + | .serialize_request(
|
1650 + | &TimestampQueryStruct,
|
1651 + | &TS_QUERY_SCHEMA,
|
1652 + | "https://example.com",
|
1653 + | &ConfigBag::base(),
|
1654 + | )
|
1655 + | .unwrap();
|
1656 + | assert_eq!(
|
1657 + | request.uri(),
|
1658 + | "https://example.com?since=1970-01-01T00%3A00%3A00Z"
|
1659 + | );
|
1660 + | }
|
1661 + |
|
1662 + | // -- Unbound members go to body, bound members do not --
|
1663 + |
|
1664 + | static BOUND_MEMBER: Schema = Schema::new_member(
|
1665 + | crate::shape_id!("test", "S"),
|
1666 + | ShapeType::String,
|
1667 + | "headerVal",
|
1668 + | 0,
|
1669 + | )
|
1670 + | .with_http_header("X-Val");
|
1671 + | static UNBOUND_MEMBER: Schema = Schema::new_member(
|
1672 + | crate::shape_id!("test", "S"),
|
1673 + | ShapeType::String,
|
1674 + | "bodyVal",
|
1675 + | 1,
|
1676 + | );
|
1677 + | static MIXED_SCHEMA: Schema = Schema::new_struct(
|
1678 + | crate::shape_id!("test", "S"),
|
1679 + | ShapeType::Structure,
|
1680 + | &[&BOUND_MEMBER, &UNBOUND_MEMBER],
|
1681 + | );
|
1682 + |
|
1683 + | struct MixedStruct;
|
1684 + | impl SerializableStruct for MixedStruct {
|
1685 + | fn serialize_members(&self, s: &mut dyn ShapeSerializer) -> Result<(), SerdeError> {
|
1686 + | s.write_string(&BOUND_MEMBER, "in-header")?;
|
1687 + | s.write_string(&UNBOUND_MEMBER, "in-body")
|
1688 + | }
|
1689 + | }
|
1690 + |
|
1691 + | #[test]
|
1692 + | fn bound_members_not_in_body() {
|
1693 + | let request = make_protocol()
|
1694 + | .serialize_request(
|
1695 + | &MixedStruct,
|
1696 + | &MIXED_SCHEMA,
|
1697 + | "https://example.com",
|
1698 + | &ConfigBag::base(),
|
1699 + | )
|
1700 + | .unwrap();
|
1701 + | let body = std::str::from_utf8(request.body().bytes().unwrap()).unwrap();
|
1702 + | assert!(
|
1703 + | body.contains("in-body"),
|
1704 + | "body should contain unbound member"
|
1705 + | );
|
1706 + | assert!(
|
1707 + | !body.contains("in-header"),
|
1708 + | "body should NOT contain header-bound member"
|
1709 + | );
|
1710 + | assert_eq!(request.headers().get("X-Val").unwrap(), "in-header");
|
1711 + | }
|
1712 + | }
|