1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

use aws_smithy_runtime_api::client::interceptors::context::{Error, Input, Output};
use aws_smithy_runtime_api::client::orchestrator::HttpResponse;
use aws_smithy_runtime_api::client::result::SdkError;
use aws_smithy_runtime_api::http::StatusCode;
use aws_smithy_types::body::SdkBody;
use std::fmt;
use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

/// A mock response that can be returned by a rule.
///
/// This enum represents the different types of responses that can be returned by a mock rule:
/// - `Output`: A successful modeled response
/// - `Error`: A modeled error
/// - `Http`: An HTTP response
///
#[derive(Debug)]
pub(crate) enum MockResponse<O, E> {
    /// A successful modeled response.
    Output(O),
    /// A modeled error.
    Error(E),
    /// An HTTP response.
    Http(HttpResponse),
}

/// A function that matches requests.
type MatchFn = Arc<dyn Fn(&Input) -> bool + Send + Sync>;
type ServeFn = Arc<dyn Fn(usize) -> Option<MockResponse<Output, Error>> + Send + Sync>;

/// A rule for matching requests and providing mock responses.
///
/// Rules are created using the `mock!` macro or the `RuleBuilder`.
///
#[derive(Clone)]
pub struct Rule {
    /// Function that determines if this rule matches a request.
    pub(crate) matcher: MatchFn,

    /// Handler function that generates responses.
    pub(crate) response_handler: ServeFn,

    /// Number of times this rule has been called.
    pub(crate) call_count: Arc<AtomicUsize>,

    /// Maximum number of responses this rule will provide.
    pub(crate) max_responses: usize,
}

impl fmt::Debug for Rule {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Rule")
    }
}

impl Rule {
    /// Creates a new rule with the given matcher, response handler, and max responses.
    pub(crate) fn new<O, E>(
        matcher: MatchFn,
        response_handler: Arc<dyn Fn(usize) -> Option<MockResponse<O, E>> + Send + Sync>,
        max_responses: usize,
    ) -> Self
    where
        O: fmt::Debug + Send + Sync + 'static,
        E: fmt::Debug + Send + Sync + std::error::Error + 'static,
    {
        Rule {
            matcher,
            response_handler: Arc::new(move |idx: usize| {
                if idx < max_responses {
                    response_handler(idx).map(|resp| match resp {
                        MockResponse::Output(o) => MockResponse::Output(Output::erase(o)),
                        MockResponse::Error(e) => MockResponse::Error(Error::erase(e)),
                        MockResponse::Http(http_resp) => MockResponse::Http(http_resp),
                    })
                } else {
                    None
                }
            }),
            call_count: Arc::new(AtomicUsize::new(0)),
            max_responses,
        }
    }

    /// Gets the next response.
    pub(crate) fn next_response(&self) -> Option<MockResponse<Output, Error>> {
        let idx = self.call_count.fetch_add(1, Ordering::SeqCst);
        (self.response_handler)(idx)
    }

    /// Returns the number of times this rule has been called.
    pub fn num_calls(&self) -> usize {
        self.call_count.load(Ordering::SeqCst)
    }

    /// Checks if this rule is exhausted (has provided all its responses).
    pub fn is_exhausted(&self) -> bool {
        self.num_calls() >= self.max_responses
    }
}

/// RuleMode describes how rules will be interpreted.
/// - In RuleMode::MatchAny, the first matching rule will be applied, and the rules will remain unchanged.
/// - In RuleMode::Sequential, the first matching rule will be applied, and that rule will be removed from the list of rules **once it is exhausted**.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleMode {
    /// Match rules in the order they were added. The first matching rule will be applied and the
    /// rules will remain unchanged
    Sequential,
    /// The first matching rule will be applied, and that rule will be removed from the list of rules
    /// **once it is exhausted**. Each rule can have multiple responses, and all responses in a rule
    /// will be consumed before moving to the next rule.
    MatchAny,
}

/// A builder for creating rules.
///
/// This builder provides a fluent API for creating rules with different response types.
///
pub struct RuleBuilder<I, O, E> {
    /// Function that determines if this rule matches a request.
    pub(crate) input_filter: MatchFn,

    /// Phantom data for the input type.
    pub(crate) _ty: std::marker::PhantomData<(I, O, E)>,
}

impl<I, O, E> RuleBuilder<I, O, E>
where
    I: fmt::Debug + Send + Sync + 'static,
    O: fmt::Debug + Send + Sync + 'static,
    E: fmt::Debug + Send + Sync + std::error::Error + 'static,
{
    /// Creates a new [`RuleBuilder`]
    #[doc(hidden)]
    pub fn new() -> Self {
        RuleBuilder {
            input_filter: Arc::new(|i: &Input| i.downcast_ref::<I>().is_some()),
            _ty: std::marker::PhantomData,
        }
    }

    /// Creates a new [`RuleBuilder`]. This is normally constructed with the [`mock!`] macro
    #[doc(hidden)]
    pub fn new_from_mock<F, R>(_input_hint: impl Fn() -> I, _output_hint: impl Fn() -> F) -> Self
    where
        F: Future<Output = Result<O, SdkError<E, R>>>,
    {
        Self {
            input_filter: Arc::new(|i: &Input| i.downcast_ref::<I>().is_some()),
            _ty: Default::default(),
        }
    }

    /// Sets the function that determines if this rule matches a request.
    pub fn match_requests<F>(mut self, filter: F) -> Self
    where
        F: Fn(&I) -> bool + Send + Sync + 'static,
    {
        self.input_filter = Arc::new(move |i: &Input| match i.downcast_ref::<I>() {
            Some(typed_input) => filter(typed_input),
            _ => false,
        });
        self
    }

    /// Start building a response sequence
    ///
    /// A sequence allows a single rule to generate multiple responses which can
    /// be used to test retry behavior.
    ///
    /// # Examples
    ///
    /// With repetition using `times()`:
    ///
    /// ```rust,ignore
    /// let rule = mock!(Client::get_object)
    ///     .sequence()
    ///     .http_status(503, None)
    ///     .times(2)                                        // First two calls return 503
    ///     .output(|| GetObjectOutput::builder().build())   // Third call succeeds
    ///     .build();
    /// ```
    pub fn sequence(self) -> ResponseSequenceBuilder<I, O, E> {
        ResponseSequenceBuilder::new(self.input_filter)
    }

    /// Creates a rule that returns a modeled output.
    pub fn then_output<F>(self, output_fn: F) -> Rule
    where
        F: Fn() -> O + Send + Sync + 'static,
    {
        self.sequence().output(output_fn).build()
    }

    /// Creates a rule that returns a modeled error.
    pub fn then_error<F>(self, error_fn: F) -> Rule
    where
        F: Fn() -> E + Send + Sync + 'static,
    {
        self.sequence().error(error_fn).build()
    }

    /// Creates a rule that returns an HTTP response.
    pub fn then_http_response<F>(self, response_fn: F) -> Rule
    where
        F: Fn() -> HttpResponse + Send + Sync + 'static,
    {
        self.sequence().http_response(response_fn).build()
    }
}

type SequenceGeneratorFn<O, E> = Arc<dyn Fn() -> MockResponse<O, E> + Send + Sync>;

/// A builder for creating response sequences
pub struct ResponseSequenceBuilder<I, O, E> {
    /// The response generators in the sequence
    generators: Vec<SequenceGeneratorFn<O, E>>,

    /// Function that determines if this rule matches a request
    input_filter: MatchFn,

    /// Marker for the input, output, and error types
    _marker: std::marker::PhantomData<I>,
}

impl<I, O, E> ResponseSequenceBuilder<I, O, E>
where
    I: fmt::Debug + Send + Sync + 'static,
    O: fmt::Debug + Send + Sync + 'static,
    E: fmt::Debug + Send + Sync + std::error::Error + 'static,
{
    /// Create a new response sequence builder
    pub(crate) fn new(input_filter: MatchFn) -> Self {
        Self {
            generators: Vec::new(),
            input_filter,
            _marker: std::marker::PhantomData,
        }
    }

    /// Add a modeled output response to the sequence
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let rule = mock!(Client::get_object)
    ///     .sequence()
    ///     .output(|| GetObjectOutput::builder().build())
    ///     .build();
    /// ```
    pub fn output<F>(mut self, output_fn: F) -> Self
    where
        F: Fn() -> O + Send + Sync + 'static,
    {
        let generator = Arc::new(move || MockResponse::Output(output_fn()));
        self.generators.push(generator);
        self
    }

    /// Add a modeled error response to the sequence
    pub fn error<F>(mut self, error_fn: F) -> Self
    where
        F: Fn() -> E + Send + Sync + 'static,
    {
        let generator = Arc::new(move || MockResponse::Error(error_fn()));
        self.generators.push(generator);
        self
    }

    /// Add an HTTP status code response to the sequence
    pub fn http_status(mut self, status: u16, body: Option<String>) -> Self {
        let status_code = StatusCode::try_from(status).unwrap();

        let generator: SequenceGeneratorFn<O, E> = match body {
            Some(body) => Arc::new(move || {
                MockResponse::Http(HttpResponse::new(status_code, SdkBody::from(body.clone())))
            }),
            None => Arc::new(move || {
                MockResponse::Http(HttpResponse::new(status_code, SdkBody::empty()))
            }),
        };

        self.generators.push(generator);
        self
    }

    /// Add an HTTP response to the sequence
    pub fn http_response<F>(mut self, response_fn: F) -> Self
    where
        F: Fn() -> HttpResponse + Send + Sync + 'static,
    {
        let generator = Arc::new(move || MockResponse::Http(response_fn()));
        self.generators.push(generator);
        self
    }

    /// Repeat the last added response multiple times (total count)
    pub fn times(mut self, count: usize) -> Self {
        if count <= 1 {
            return self;
        }

        if let Some(last_generator) = self.generators.last().cloned() {
            // Add count-1 more copies (we already have one)
            for _ in 1..count {
                self.generators.push(last_generator.clone());
            }
        }
        self
    }

    /// Build the rule with this response sequence
    pub fn build(self) -> Rule {
        let generators = self.generators;
        let count = generators.len();

        Rule::new(
            self.input_filter,
            Arc::new(move |idx| {
                if idx < count {
                    Some(generators[idx]())
                } else {
                    None
                }
            }),
            count,
        )
    }
}