Skip to main content

aws_smithy_schema/schema/
operation_schema.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6use crate::{prelude, Schema, ShapeId};
7use std::fmt;
8
9/// The identity and schemas of one Smithy operation.
10///
11/// An operation is not itself serialized, so it has no [`Schema`]; this descriptor relates the
12/// operation's shape ID to the schemas a protocol needs to call it: the input, the output, and
13/// the errors it can return.
14///
15/// The descriptor borrows everything, so it is cheap to construct and to clone. It is built
16/// with [`OperationSchema::builder`], whose methods are `const`, so it can be declared as a
17/// `static` alongside generated schemas:
18///
19/// ```
20/// use aws_smithy_schema::{shape_id, OperationSchema, Schema, ShapeType};
21///
22/// static INPUT: Schema<'static> =
23///     Schema::new_struct(shape_id!("com.example", "GetThingInput"), ShapeType::Structure, &[]);
24/// static OUTPUT: Schema<'static> =
25///     Schema::new_struct(shape_id!("com.example", "GetThingOutput"), ShapeType::Structure, &[]);
26/// static NOT_FOUND: Schema<'static> =
27///     Schema::new_struct(shape_id!("com.example", "NotFound"), ShapeType::Structure, &[]);
28///
29/// static GET_THING: OperationSchema<'static> =
30///     OperationSchema::builder(shape_id!("com.example", "GetThing"))
31///         .input(&INPUT)
32///         .output(&OUTPUT)
33///         .errors(&[&NOT_FOUND])
34///         .build();
35///
36/// assert_eq!(GET_THING.id().as_str(), "com.example#GetThing");
37/// assert_eq!(GET_THING.input().shape_id().as_str(), "com.example#GetThingInput");
38/// assert_eq!(GET_THING.errors().len(), 1);
39/// ```
40///
41/// # Input and output schemas
42///
43/// Protocols read operation-level behavior, such as the `@http` trait and body hints, from the
44/// input schema, and S3's unwrapped XML output from the output schema. The input and output
45/// schemas of a descriptor are therefore specific to the operation: when two operations share
46/// an input structure, each has its own input schema with that structure's ID, members, and
47/// traits plus its own operation-level behavior.
48///
49/// # Errors
50///
51/// [`errors`](Self::errors) are the operation's errors in the context the descriptor was built
52/// for. For an operation of a service, that is the service's common errors followed by the
53/// operation's own, without duplicates. Without a service, it is the operation's own errors.
54///
55/// # Lifetimes
56///
57/// A descriptor cannot outlive the schemas it references:
58///
59/// ```compile_fail,E0597
60/// use aws_smithy_schema::{shape_id, OperationSchema, Schema, ShapeType};
61///
62/// let operation = {
63///     let unit = Schema::new(shape_id!("smithy.api", "Unit"), ShapeType::Structure);
64///     OperationSchema::builder(shape_id!("com.example", "Op"))
65///         .input(&unit)
66///         .build()
67/// };
68/// # let _ = operation;
69/// ```
70#[derive(Clone)]
71pub struct OperationSchema<'a> {
72    id: ShapeId<'a>,
73    input: &'a Schema<'a>,
74    output: &'a Schema<'a>,
75    errors: &'a [&'a Schema<'a>],
76}
77
78impl<'a> OperationSchema<'a> {
79    /// A builder for the descriptor of the operation `id`.
80    ///
81    /// The input and output default to [`prelude::UNIT`], as in a Smithy model that omits
82    /// them, and the errors default to none.
83    pub const fn builder(id: ShapeId<'a>) -> OperationSchemaBuilder<'a> {
84        OperationSchemaBuilder {
85            id,
86            input: &prelude::UNIT,
87            output: &prelude::UNIT,
88            errors: &[],
89        }
90    }
91
92    /// The operation's shape ID.
93    ///
94    /// Returned by value: a [`ShapeId`] only borrows its strings, so this does not allocate,
95    /// and the result is not tied to the lifetime of the descriptor value itself.
96    pub fn id(&self) -> ShapeId<'a> {
97        self.id.clone()
98    }
99
100    /// The input schema for this operation, to pass to a protocol's `serialize_request`.
101    pub fn input(&self) -> &'a Schema<'a> {
102        self.input
103    }
104
105    /// The output schema for this operation, to pass to a protocol's `deserialize_response`.
106    pub fn output(&self) -> &'a Schema<'a> {
107        self.output
108    }
109
110    /// The error structures the operation can return.
111    pub fn errors(&self) -> &'a [&'a Schema<'a>] {
112        self.errors
113    }
114}
115
116impl fmt::Debug for OperationSchema<'_> {
117    /// Shows shape IDs only, not the complete schemas.
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        debug_ids(
120            f,
121            "OperationSchema",
122            &self.id,
123            self.input,
124            self.output,
125            self.errors,
126        )
127    }
128}
129
130/// Builds an [`OperationSchema`]. Created by [`OperationSchema::builder`].
131///
132/// Every method is `const`, so a descriptor can be built in a `static` initializer. Settings
133/// added in the future will have defaults, so existing builders keep compiling.
134#[derive(Clone)]
135#[must_use]
136pub struct OperationSchemaBuilder<'a> {
137    id: ShapeId<'a>,
138    input: &'a Schema<'a>,
139    output: &'a Schema<'a>,
140    errors: &'a [&'a Schema<'a>],
141}
142
143impl<'a> OperationSchemaBuilder<'a> {
144    /// Sets the input schema, to pass to a protocol's `serialize_request`. Defaults to
145    /// [`prelude::UNIT`].
146    pub const fn input(mut self, input: &'a Schema<'a>) -> Self {
147        self.input = input;
148        self
149    }
150
151    /// Sets the output schema, to pass to a protocol's `deserialize_response`. Defaults to
152    /// [`prelude::UNIT`].
153    pub const fn output(mut self, output: &'a Schema<'a>) -> Self {
154        self.output = output;
155        self
156    }
157
158    /// Sets the error structures the operation can return, in the context the descriptor is
159    /// built for (see [`OperationSchema::errors`]). Defaults to none.
160    pub const fn errors(mut self, errors: &'a [&'a Schema<'a>]) -> Self {
161        self.errors = errors;
162        self
163    }
164
165    /// Builds the descriptor.
166    pub const fn build(self) -> OperationSchema<'a> {
167        OperationSchema {
168            id: self.id,
169            input: self.input,
170            output: self.output,
171            errors: self.errors,
172        }
173    }
174}
175
176impl fmt::Debug for OperationSchemaBuilder<'_> {
177    /// Shows shape IDs only, not the complete schemas.
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        debug_ids(
180            f,
181            "OperationSchemaBuilder",
182            &self.id,
183            self.input,
184            self.output,
185            self.errors,
186        )
187    }
188}
189
190fn debug_ids(
191    f: &mut fmt::Formatter<'_>,
192    name: &str,
193    id: &ShapeId<'_>,
194    input: &Schema<'_>,
195    output: &Schema<'_>,
196    errors: &[&Schema<'_>],
197) -> fmt::Result {
198    struct Ids<'s, 'a>(&'s [&'a Schema<'a>]);
199    impl fmt::Debug for Ids<'_, '_> {
200        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201            f.debug_list()
202                .entries(self.0.iter().map(|schema| schema.shape_id().as_str()))
203                .finish()
204        }
205    }
206    f.debug_struct(name)
207        .field("id", &id.as_str())
208        .field("input", &input.shape_id().as_str())
209        .field("output", &output.shape_id().as_str())
210        .field("errors", &Ids(errors))
211        .finish()
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use crate::{shape_id, ShapeType};
218
219    static INPUT: Schema<'static> =
220        Schema::new_struct(shape_id!("com.example", "Input"), ShapeType::Structure, &[]);
221    static OUTPUT: Schema<'static> = Schema::new_struct(
222        shape_id!("com.example", "Output"),
223        ShapeType::Structure,
224        &[],
225    );
226    static ERROR_A: Schema<'static> = Schema::new_struct(
227        shape_id!("com.example", "ErrorA"),
228        ShapeType::Structure,
229        &[],
230    );
231    static ERROR_B: Schema<'static> = Schema::new_struct(
232        shape_id!("com.example", "ErrorB"),
233        ShapeType::Structure,
234        &[],
235    );
236
237    static OPERATION: OperationSchema<'static> =
238        OperationSchema::builder(shape_id!("com.example", "Operation"))
239            .input(&INPUT)
240            .output(&OUTPUT)
241            .errors(&[&ERROR_B, &ERROR_A])
242            .build();
243
244    #[test]
245    fn static_descriptor() {
246        let id = OPERATION.id();
247        assert_eq!(id.as_str(), "com.example#Operation");
248        assert_eq!(id.namespace(), "com.example");
249        assert_eq!(id.shape_name(), "Operation");
250        assert_eq!(id.member_name(), None);
251        assert!(std::ptr::eq(OPERATION.input(), &INPUT));
252        assert!(std::ptr::eq(OPERATION.output(), &OUTPUT));
253        let errors: Vec<_> = OPERATION
254            .errors()
255            .iter()
256            .map(|error| error.shape_id().as_str())
257            .collect();
258        // Order is preserved.
259        assert_eq!(errors, ["com.example#ErrorB", "com.example#ErrorA"]);
260    }
261
262    #[test]
263    fn borrowed_descriptor() {
264        let fqn = String::from("com.example#Borrowed");
265        let id = ShapeId::from_parts(&fqn, &fqn[..11], &fqn[12..]);
266        let input = Schema::new_struct(id.clone(), ShapeType::Structure, &[]);
267        let errors = [&ERROR_A];
268        let operation = OperationSchema::builder(id)
269            .input(&input)
270            .output(&OUTPUT)
271            .errors(&errors)
272            .build();
273        // The ID outlives the descriptor value it came from.
274        let id = operation.clone().id();
275        assert_eq!(id.as_str(), "com.example#Borrowed");
276        assert_eq!(id.namespace(), "com.example");
277        assert_eq!(id.shape_name(), "Borrowed");
278        assert!(std::ptr::eq(id.as_str(), fqn.as_str()));
279        assert!(std::ptr::eq(operation.input(), &input));
280    }
281
282    #[test]
283    fn builder_defaults_match_an_omitted_input_and_output() {
284        static DEFAULTS: OperationSchema<'static> =
285            OperationSchema::builder(shape_id!("com.example", "Ping")).build();
286        assert!(std::ptr::eq(DEFAULTS.input(), &prelude::UNIT));
287        assert!(std::ptr::eq(DEFAULTS.output(), &prelude::UNIT));
288        assert!(DEFAULTS.errors().is_empty());
289        // A later setter replaces an earlier one.
290        let operation = OperationSchema::builder(shape_id!("com.example", "Ping"))
291            .input(&INPUT)
292            .input(&OUTPUT)
293            .build();
294        assert!(std::ptr::eq(operation.input(), &OUTPUT));
295    }
296
297    #[test]
298    fn debug_shows_ids_only() {
299        assert_eq!(
300            format!("{OPERATION:?}"),
301            r#"OperationSchema { id: "com.example#Operation", input: "com.example#Input", output: "com.example#Output", errors: ["com.example#ErrorB", "com.example#ErrorA"] }"#
302        );
303        assert_eq!(
304            format!(
305                "{:?}",
306                OperationSchema::builder(shape_id!("com.example", "Ping"))
307            ),
308            r#"OperationSchemaBuilder { id: "com.example#Ping", input: "smithy.api#Unit", output: "smithy.api#Unit", errors: [] }"#
309        );
310    }
311
312    #[test]
313    #[cfg(target_pointer_width = "64")]
314    fn size_stays_within_its_budget() {
315        // A 64-byte `ShapeId`, two schema references, and an error slice. Update deliberately.
316        assert_eq!(std::mem::size_of::<OperationSchema<'static>>(), 96);
317    }
318}