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
use std::sync::{Arc, Mutex};
use std::marker::PhantomData;

use chrono::prelude::{DateTime, Utc};
use config::Config;

use futures::{Future, Poll, Async, task, Never};
use futures::channel::oneshot::{channel, Sender, Receiver};

use protocol::{Message, ActorMsg, ESMsg, SystemMsg};
use actors::{Actor, BoxActor, Context, ActorRef, BoxActorProd};
use actors::{Props, ActorRefFactory, TmpActorRefFactory, Tell, SysTell};

// use actor::BoxActorProd;

// pub trait EsManagerProps {
//     type Msg: Message;
//     type Evs: EventStore;

//     fn props(config: &Config) -> Option<BoxActorProd<Self::Msg>>;
// }

// pub fn es_manager<Evs>(config: &Config) -> BoxActor<Evs::Msg>
//     where Evs: EventStore
// {
    

// }

pub struct EsManager<Evs: EventStore> {
    es: Evs,
}

impl<Evs: EventStore> EsManager<Evs> {
    fn new(es: Evs) -> BoxActor<Evs::Msg> {
        let actor: EsManager<Evs> = EsManager {
            es: es,
        };

        Box::new(actor)
    }

    pub fn props(config: &Config) -> BoxActorProd<Evs::Msg> {
        let es = Evs::new(config);
        Props::new_args(Box::new(EsManager::new), es)
    }
}

impl<Evs: EventStore> Actor for EsManager<Evs> {
    type Msg = Evs::Msg;

    fn other_receive(&mut self,
                    _: &Context<Self::Msg>,
                    msg: ActorMsg<Self::Msg>,
                    sender: Option<ActorRef<Self::Msg>>) {

        if let ActorMsg::ES(msg) = msg {
            match msg {
                ESMsg::Persist(evt, id, keyspace) => {
                    self.es.insert(&id, &keyspace, evt.clone());

                    sender.unwrap().sys_tell(SystemMsg::Persisted(evt.msg), None);
                }
                ESMsg::Load(id, keyspace) => {
                    let result = self.es.load(&id, &keyspace);
                    sender.unwrap().tell(ESMsg::LoadResult(result), None);
                }
                _ => {}
            }
        }
    }

    fn receive(&mut self, _: &Context<Self::Msg>, _: Self::Msg, _: Option<ActorRef<Self::Msg>>) {}
}

pub trait EventStore : Clone + Send + Sync + 'static {
    type Msg: Message;

    fn new(config: &Config) -> Self;

    fn insert(&mut self, id: &String, keyspace: &String, evt: Evt<Self::Msg>);

    fn load(&self, id: &String, keyspace: &String) -> Vec<Self::Msg>;
}

#[derive(Clone, Debug)]
pub struct Evt<Msg: Message> {
    pub date: DateTime<Utc>,
    pub msg: Msg,
}

impl<Msg: Message> Evt<Msg> {
    pub fn new(msg: Msg) -> Self {
        Evt {
            date: Utc::now(),
            msg: msg
        }
    }
}

// #[allow(dead_code)]
// pub struct NoPersist<Evs: EventStore> {
//     es: Evs,
// }

// #[allow(dead_code)]
// impl<Evs: EventStore> NoPersist<Evs> {
//     fn new(es: Evs) -> BoxActor<Evs::Msg>
//     {
//         let actor: NoPersist<Evs> = NoPersist {
//             es: es,
//         };

//         Box::new(actor)
//     }
// }

// impl<Evs: EventStore> Actor for NoPersist<Evs> {
//     type Msg = Evs::Msg;

//     fn receive(&mut self, _: &Context<Self::Msg>, _: Self::Msg, _: Option<ActorRef<Self::Msg>>) {}
// }

// impl<Evs: EventStore> EsManagerProps for NoPersist<Evs> {
//     type Msg = Evs::Msg;
//     type Evs = Evs;

//     fn props(_config: &Config) -> Option<BoxActorProd<Self::Msg>> {
//         None
//     }
// }


#[derive(Clone)]
pub struct NoEventStore<Msg: Message> {
    msg: Arc<Mutex<PhantomData<Msg>>>,
}

impl<Msg: Message> EventStore for NoEventStore<Msg> {
    type Msg = Msg;

    fn new(_config: &Config) -> Self {
        NoEventStore {
            msg: Arc::new(Mutex::new(PhantomData))
        }
    }

    fn insert(&mut self, _: &String, _: &String, _: Evt<Msg>) {
        warn!("No event store configured");
        
    }

    fn load(&self, _: &String, _: &String) -> Vec<Msg> {
        warn!("No event store configured");
        vec![]
    }
}

pub struct EsQuery<Msg: Message> {
    inner: Receiver<Vec<Msg>>,
}

impl<Msg> EsQuery<Msg>
    where Msg: Message
{
    pub fn new<Ctx>(id: &String,
                    keyspace: &String,
                    es: &ActorRef<Msg>,
                    ctx: &Ctx) -> EsQuery<Msg>
        where Ctx: TmpActorRefFactory<Msg=Msg>
    {
        let (tx, rx) = channel::<Vec<Msg>>();
        let tx = Arc::new(Mutex::new(Some(tx)));

        let props = Props::new_args(Box::new(EsQueryActor::new), tx);
        let actor = ctx.tmp_actor_of(props).unwrap();
        es.tell(ESMsg::Load(id.clone(), keyspace.clone()), Some(actor));

        EsQuery {
            inner: rx
        }
    }
}

impl<Msg: Message> Future for EsQuery<Msg> {
    type Item = Vec<Msg>;
    type Error = Never;

    fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Never> {
        match self.inner.poll(cx) {
            Ok(Async::Ready(e)) => Ok(Async::Ready(e)),
            Ok(Async::Pending) => return Ok(Async::Pending),
            Err(_) => panic!(),
        }
    }
}

struct EsQueryActor<Msg: Message> {
    tx: Arc<Mutex<Option<Sender<Vec<Msg>>>>>,
}

impl<Msg: Message> EsQueryActor<Msg> {
    fn new(tx: Arc<Mutex<Option<Sender<Vec<Msg>>>>>) -> BoxActor<Msg> {
        let ask = EsQueryActor {
            tx: tx
        };
        Box::new(ask)
    }

    fn fulfill_query(&self, events: Vec<Msg>) {
        match self.tx.lock() {
            Ok(mut tx) => drop(tx.take().unwrap().send(events)),
            _ => {}
        }
    }
}

impl<Msg: Message> Actor for EsQueryActor<Msg> {
    type Msg = Msg;

    fn other_receive(&mut self, ctx: &Context<Msg>, msg: ActorMsg<Msg>, _: Option<ActorRef<Msg>>) {
        match msg {
            ActorMsg::ES(result) => {
                if let ESMsg::LoadResult(events) = result {
                    self.fulfill_query(events);
                    ctx.stop(&ctx.myself);
                }
            }
            _ => {}
        }
    }

    fn receive(&mut self, _: &Context<Msg>, _: Msg, _: Option<ActorRef<Msg>>) {
        
    }
}

type QueryFuture<Msg> = Box<Future<Item=Vec<Msg>, Error=Never> + Send>;

pub fn query<Msg, Ctx>(id: &String,
                        keyspace: &String,
                        es: &ActorRef<Msg>,
                        ctx: &Ctx) -> QueryFuture<Msg>
    where Msg: Message, Ctx: TmpActorRefFactory<Msg=Msg>
{
    Box::new(EsQuery::new(id, keyspace, es, ctx))
}