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
use std::error::Error;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use futures::compat::Future01CompatExt;

use log::{info, warn};
use rusoto_sqs::{ReceiveMessageRequest, Sqs};
use rusoto_sqs::Message as SqsMessage;
use tokio::sync::mpsc::{channel, Sender};
use async_trait::async_trait;

use crate::event_processor::EventProcessorActor;
use lambda_runtime::Context;

pub struct ConsumePolicy {
    context: Context,
    stop_at: Duration
}

impl ConsumePolicy {
    pub fn new(context: Context, stop_at: Duration) -> Self {
        Self {
            context, stop_at
        }
    }

    pub fn should_consume(&self) -> bool {
        self.stop_at.as_millis() <= self.context.get_time_remaining_millis() as u128
    }
}

pub struct SqsConsumer<S>
    where S: Sqs  + Send + Sync + 'static
{
    sqs_client: S,
    queue_url: String,
    stored_events: Vec<SqsMessage>,
    consume_policy: ConsumePolicy,
    shutdown_subscriber: Option<tokio::sync::oneshot::Sender<()>>,
}

impl<S> SqsConsumer<S>
    where S: Sqs  + Send + Sync + 'static
{
    pub fn new(
        sqs_client: S,
        queue_url: String,
        consume_policy: ConsumePolicy,
        shutdown_subscriber: tokio::sync::oneshot::Sender<()>,
    ) -> SqsConsumer<S>
    where
        S: Sqs,
    {
        Self {
            sqs_client,
            queue_url,
            stored_events: Vec::with_capacity(20),
            consume_policy,
            shutdown_subscriber: Some(shutdown_subscriber),
        }
    }
}

impl<S> SqsConsumer<S>
    where S: Sqs  + Send + Sync + 'static
{
    pub async fn get_new_event(&mut self, event_processor: EventProcessorActor) {
        let should_consume = self.consume_policy.should_consume();

        if self.stored_events.len() == 0 && should_consume {
            let new_events = self.batch_get_events().await.unwrap();
            self.stored_events.extend(new_events);
        }

        if self.stored_events.is_empty() && !should_consume {
            info!("No more events to process, and no time to consume more");
            let shutdown_subscriber = std::mem::replace(&mut self.shutdown_subscriber, None);
            match shutdown_subscriber {
                Some(shutdown_subscriber) => shutdown_subscriber.send(()).unwrap(),
                None => warn!("Attempted to shut down with empty shutdown_subscriber")
            }
        }

        if let Some(next_event) = self.stored_events.pop() {
            event_processor.process_event(next_event).await;
        }
    }

    pub async fn batch_get_events(&self) -> Result<Vec<SqsMessage>, Box<dyn Error>> {
        let recv = self.sqs_client.receive_message(
            ReceiveMessageRequest {
                max_number_of_messages: Some(10),
                queue_url: self.queue_url.clone(),
                wait_time_seconds: Some(1),
                ..Default::default()
            }
        ).compat().await?;



        Ok(recv.messages.unwrap_or(vec![]))
    }
}

#[allow(non_camel_case_types)]
pub enum SqsConsumerMessage {
    get_new_event {
        event_processor: EventProcessorActor,
    },
}

impl<S> SqsConsumer<S>
    where S: Sqs  + Send + Sync + 'static
{
    async fn route_message(&mut self, msg: SqsConsumerMessage) {
        match msg {
            SqsConsumerMessage::get_new_event { event_processor } => {
                self.get_new_event(event_processor).await
            }
        };
    }
}

#[derive(Clone)]
pub struct SqsConsumerActor {
    sender: Sender<SqsConsumerMessage>,
}

impl SqsConsumerActor {
    pub fn new<S>(actor_impl: SqsConsumer<S>) -> Self
        where S: Sqs  + Send + Sync + 'static
    {
        let (sender, receiver) = channel(1);

        tokio::task::spawn(
            route_wrapper(
                SqsConsumerRouter {
                    receiver,
                    actor_impl,
                }
            )
        );
        Self { sender }
    }

    pub async fn get_next_event(&self, event_processor: EventProcessorActor) {
        let msg = SqsConsumerMessage::get_new_event { event_processor };
        if let Err(_e) = self.sender.clone().send(msg).await {
            panic!("Receiver has failed, propagating error. get_new_event")
        }
    }
}

#[async_trait]
pub trait Consumer {
    async fn get_next_event(&self, event_processor: EventProcessorActor);
}

#[async_trait]
impl Consumer for SqsConsumerActor {
    async fn get_next_event(&self, event_processor: EventProcessorActor) {
        SqsConsumerActor::get_next_event(
            self, event_processor
        ).await
    }
}

pub struct SqsConsumerRouter<S>
    where S: Sqs  + Send + Sync + 'static
{
    receiver: tokio::sync::mpsc::Receiver<SqsConsumerMessage>,
    actor_impl: SqsConsumer<S>,
}



async fn route_wrapper<S>(mut router: SqsConsumerRouter<S>)
    where S: Sqs  + Send + Sync + 'static
{
    while let Some(msg) = router.receiver.recv().await {
        router.actor_impl.route_message(msg).await;
    }
}