Skip to main content

adventure_rusoto_sqs/
lib.rs

1//! A proof-of-concept crate to provides trait implementations of types in [`rusoto_sqs`],
2//! to work with [`adventure`].
3//!
4//! Examples
5//! --------
6//!
7//! ```ignore
8//! ```
9use std::ops::Deref;
10use std::pin::Pin;
11use std::rc::Rc;
12use std::sync::Arc;
13use std::time::Duration;
14
15use adventure::{
16    response::Future01Response, BaseRequest, OneshotRequest, PagedRequest, Request,
17    RetriableRequest,
18};
19use futures::Future;
20use rusoto_core::{RusotoError, RusotoFuture};
21use rusoto_sqs::*;
22
23pub type RusotoResponse<T, E> = Future01Response<RusotoFuture<T, E>>;
24
25/// A wrapper for various type of requests in [`rusoto_sqs`].
26#[derive(Clone, Debug)]
27pub struct AwsSqs<T> {
28    inner: T,
29}
30
31pub trait AsSqs {
32    type Output: Sqs + ?Sized;
33    fn as_sqs(&self) -> &Self::Output;
34}
35
36impl AsSqs for SqsClient {
37    type Output = SqsClient;
38    fn as_sqs(&self) -> &SqsClient {
39        self
40    }
41}
42
43impl<T: ?Sized> AsSqs for &T
44where
45    T: Sqs,
46{
47    type Output = T;
48    fn as_sqs(&self) -> &Self::Output {
49        &**self
50    }
51}
52
53impl<T: ?Sized> AsSqs for Box<T>
54where
55    T: Sqs,
56{
57    type Output = T;
58    fn as_sqs(&self) -> &Self::Output {
59        &**self
60    }
61}
62
63impl<T: ?Sized> AsSqs for Arc<T>
64where
65    T: Sqs,
66{
67    type Output = T;
68    fn as_sqs(&self) -> &Self::Output {
69        &**self
70    }
71}
72
73impl<T: ?Sized> AsSqs for Rc<T>
74where
75    T: Sqs,
76{
77    type Output = T;
78    fn as_sqs(&self) -> &Self::Output {
79        &**self
80    }
81}
82
83impl<P> AsSqs for Pin<P>
84where
85    P: Deref,
86    <P as Deref>::Target: Sqs,
87{
88    type Output = <P as Deref>::Target;
89    fn as_sqs(&self) -> &Self::Output {
90        &**self
91    }
92}
93
94macro_rules! impl_adventure {
95    {
96        wrapper: $wrapper:ident;
97        client: $client:ident;
98        $( impl $name:ident { $($body:tt)* } )*
99    } => {
100        $(
101            impl From<$name> for $wrapper<$name> {
102                fn from(req: $name) -> Self {
103                    $wrapper { inner: req }
104                }
105            }
106
107            impl_adventure!(@ $wrapper, $name, $client; $($body)*);
108        )*
109    };
110
111    (@ $wrapper:ident, $name:ident, $client:ident; type Ok = $ok:ty; type Error = $error:ident; $($rest:tt)*) => {
112        impl BaseRequest for $wrapper<$name> {
113            type Ok = $ok;
114            type Error = RusotoError<$error>;
115        }
116
117        impl_adventure!(@@ $wrapper, $name, $client, $error; $($rest)*);
118    };
119    (@@ $wrapper:ident, $name:ident, $client:ident, $error:ident; ) => { };
120    (@@ $wrapper:ident, $name:ident, $client:ident, $error:ident; retry: $variant:ident; $($rest:tt)*) => {
121        impl RetriableRequest for $wrapper<$name> {
122            fn should_retry(&self, err: &Self::Error, _next_interval: Duration) -> bool {
123                if let RusotoError::HttpDispatch(_) = err {
124                    true
125                } else {
126                    false
127                }
128            }
129        }
130
131        impl_adventure!(@@ $wrapper, $name, $client, $error; $($rest)*);
132    };
133    (@@ $wrapper:ident, $name:ident, $client:ident, $error:ident; send: $method:ident; $($rest:tt)*) => {
134        impl<C> OneshotRequest<C> for $wrapper<$name> where C: AsSqs {
135            type Response = RusotoResponse<Self::Ok, $error>;
136
137            fn send_once(self, client: C) -> Self::Response {
138                Future01Response::new(client.as_sqs().$method(self.inner))
139            }
140        }
141
142        impl<C> Request<C> for $wrapper<$name> where C: AsSqs {
143            type Response = <Self as OneshotRequest<C>>::Response;
144
145            #[inline]
146            fn send(self: Pin<&mut Self>, client: C) -> Self::Response {
147                self.clone().send_once(client)
148            }
149        }
150
151        impl_adventure!(@@ $wrapper, $name, $client, $error; $($rest)*);
152    };
153    (@@ $wrapper:ident, $name:ident, $client:ident, $error:ident; advance: $token:ident; $($rest:tt)*) => {
154        impl PagedRequest for $wrapper<$name> {
155            fn advance(&mut self, response: &Self::Ok) -> bool {
156                if let Some(next) = response.$token.clone() {
157                    self.inner.$token = Some(next);
158                    true
159                } else {
160                    false
161                }
162            }
163        }
164
165        impl_adventure!(@@ $wrapper, $name, $client, $error; $($rest)*);
166    }
167}
168
169impl_adventure! {
170    wrapper: AwsSqs;
171    client: Sqs;
172
173    impl AddPermissionRequest {
174        type Ok = ();
175        type Error = AddPermissionError;
176        retry: Server;
177        send: add_permission;
178    }
179
180    impl ChangeMessageVisibilityRequest {
181        type Ok = ();
182        type Error = ChangeMessageVisibilityError;
183        retry: Server;
184        send: change_message_visibility;
185    }
186
187    impl ChangeMessageVisibilityBatchRequest {
188        type Ok = ChangeMessageVisibilityBatchResult;
189        type Error = ChangeMessageVisibilityBatchError;
190        retry: Server;
191        send: change_message_visibility_batch;
192    }
193
194    impl CreateQueueRequest {
195        type Ok = CreateQueueResult;
196        type Error = CreateQueueError;
197        retry: Server;
198        send: create_queue;
199    }
200
201    impl DeleteMessageRequest {
202        type Ok = ();
203        type Error = DeleteMessageError;
204        retry: Server;
205        send: delete_message;
206    }
207
208    impl DeleteMessageBatchRequest {
209        type Ok = DeleteMessageBatchResult;
210        type Error = DeleteMessageBatchError;
211        retry: Server;
212        send: delete_message_batch;
213    }
214
215    impl DeleteQueueRequest {
216        type Ok = ();
217        type Error = DeleteQueueError;
218        retry: Server;
219        send: delete_queue;
220    }
221
222    impl GetQueueAttributesRequest {
223        type Ok = GetQueueAttributesResult;
224        type Error = GetQueueAttributesError;
225        retry: Server;
226        send: get_queue_attributes;
227    }
228
229    impl GetQueueUrlRequest {
230        type Ok = GetQueueUrlResult;
231        type Error = GetQueueUrlError;
232        retry: Server;
233        send: get_queue_url;
234    }
235
236    impl ListDeadLetterSourceQueuesRequest {
237        type Ok = ListDeadLetterSourceQueuesResult;
238        type Error = ListDeadLetterSourceQueuesError;
239        retry: Server;
240        send: list_dead_letter_source_queues;
241    }
242
243    impl ListQueueTagsRequest {
244        type Ok = ListQueueTagsResult;
245        type Error = ListQueueTagsError;
246        retry: Server;
247        send: list_queue_tags;
248    }
249
250    impl ListQueuesRequest {
251        type Ok = ListQueuesResult;
252        type Error = ListQueuesError;
253        retry: Server;
254        send: list_queues;
255    }
256
257    impl PurgeQueueRequest {
258        type Ok = ();
259        type Error = PurgeQueueError;
260        retry: Server;
261        send: purge_queue;
262    }
263
264    impl ReceiveMessageRequest {
265        type Ok = Vec<Message>;
266        type Error = ReceiveMessageError;
267    }
268
269    impl RemovePermissionRequest {
270        type Ok = ();
271        type Error = RemovePermissionError;
272        retry: Server;
273        send: remove_permission;
274    }
275
276    impl SendMessageRequest {
277        type Ok = SendMessageResult;
278        type Error = SendMessageError;
279        retry: Server;
280        send: send_message;
281    }
282
283    impl SendMessageBatchRequest {
284        type Ok = SendMessageBatchResult;
285        type Error = SendMessageBatchError;
286        retry: Server;
287        send: send_message_batch;
288    }
289
290    impl SetQueueAttributesRequest {
291        type Ok = ();
292        type Error = SetQueueAttributesError;
293        retry: Server;
294        send: set_queue_attributes;
295    }
296
297    impl TagQueueRequest {
298        type Ok = ();
299        type Error = TagQueueError;
300        retry: Server;
301        send: tag_queue;
302    }
303
304    impl UntagQueueRequest {
305        type Ok = ();
306        type Error = UntagQueueError;
307        retry: Server;
308        send: untag_queue;
309    }
310}
311
312impl<C> OneshotRequest<C> for AwsSqs<ReceiveMessageRequest>
313where
314    C: AsSqs,
315{
316    type Response =
317        Future01Response<Box<dyn Future<Item = Self::Ok, Error = Self::Error> + Send + 'static>>;
318
319    fn send_once(self, client: C) -> Self::Response {
320        let f = client
321            .as_sqs()
322            .receive_message(self.inner)
323            .map(|res| res.messages.unwrap_or_else(Vec::new));
324        Future01Response::new(Box::new(f))
325    }
326}
327
328impl<C> Request<C> for AwsSqs<ReceiveMessageRequest>
329where
330    C: AsSqs,
331{
332    type Response = <Self as OneshotRequest<C>>::Response;
333
334    #[inline]
335    fn send(self: Pin<&mut Self>, client: C) -> Self::Response {
336        self.clone().send_once(client)
337    }
338}
339
340impl RetriableRequest for AwsSqs<ReceiveMessageRequest> {
341    fn should_retry(&self, err: &Self::Error, _next_interval: Duration) -> bool {
342        match err {
343            RusotoError::HttpDispatch(_)
344            | RusotoError::Service(ReceiveMessageError::OverLimit(_)) => true,
345            _ => false,
346        }
347    }
348}
349
350impl PagedRequest for AwsSqs<ReceiveMessageRequest> {
351    fn advance(&mut self, response: &Self::Ok) -> bool {
352        if let Some(id) = self.inner.receive_request_attempt_id.as_mut() {
353            use sha2::Digest;
354            use std::fmt::Write;
355            let mut hasher = sha2::Sha256::new();
356            hasher.input(id.as_bytes());
357            hasher.input(b"next");
358            if let Some(i) = response.first().and_then(|m| m.message_id.as_ref()) {
359                hasher.input(i.as_bytes());
360            }
361            id.clear();
362            write!(id, "{:x}", hasher.result()).unwrap();
363        }
364        true
365    }
366}
367
368#[cfg(test)]
369mod test {
370    use super::*;
371
372    #[test]
373    fn receive_message_paged_advance() {
374        let mut req = AwsSqs::from(ReceiveMessageRequest {
375            receive_request_attempt_id: Some("first".to_owned()),
376            ..Default::default()
377        });
378        assert!(req.advance(&vec![]));
379        let id = req.inner.receive_request_attempt_id.unwrap();
380        println!("{}", id);
381        assert_eq!(id.len(), 64);
382        assert!(regex::Regex::new(r"[0-9a-z]{2}+").unwrap().is_match(&id));
383    }
384}