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
// MIT License
// 
// Copyright (c) 2019-2021 Alessandro Cresto Miseroglio <alex179ohm@gmail.com>
// Copyright (c) 2019-2021 Tangram Technologies S.R.L. <https://tngrm.io>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use std::io;
use std::collections::VecDeque;

use actix::actors::resolver::{Connect, Resolver};
use actix::prelude::*;
use futures::unsync::oneshot;
use futures::Future;
use backoff::backoff::Backoff;
use backoff::ExponentialBackoff;
use log::{error, info, debug};
use serde_json;
use tokio_codec::FramedRead;
use tokio_io::io::WriteHalf;
use tokio_io::AsyncRead;
use tokio_tcp::TcpStream;
//use bytes::BytesMut;

use crate::codec::{NsqCodec, Cmd};
use crate::commands::{identify, nop, auth, sub, rdy, publish, VERSION};
use crate::config::{Config, NsqdConfig};
use crate::error::Error;
use crate::msgs::{Auth, Pub, Sub, Ready};
use crate::conn::ConnState;

pub struct Producer
{
    topic: String,
    channel: String,
    addr: String,
    config: Config,
    backoff: ExponentialBackoff,
    cell: Option<actix::io::FramedWrite<WriteHalf<TcpStream>, NsqCodec>>,
    state: ConnState,
    queue: VecDeque<oneshot::Sender<Result<Cmd, Error>>>,
    auth: String,
//    rdy: u32,
}

impl Default for Producer
{
    fn default() -> Producer {
        Producer {
            topic: String::new(),
            channel: String::new(),
            addr: String::new(),
            config: Config::default(),
            backoff: ExponentialBackoff::default(),
            cell: None,
            state: ConnState::Neg,
            queue: VecDeque::new(),
            auth: String::new(),
 //           rdy: 0,
        }
    }
}

impl Producer
{
    pub fn new<S: Into<String>>(
        topic: S,
        channel: S,
        addr: S,
        config: Option<Config>,
        auth: S,
 //       rdy: Option<u32>,
    ) -> Producer {
        let mut backoff = ExponentialBackoff::default();
        let mut _rdy = 0;
        //if rdy.is_some() { _rdy = rdy.unwrap() };
        let cfg = match config {
            Some(cfg) => cfg,
            None => Config::default(),
        };
        backoff.max_elapsed_time = None;
        Producer {
            addr: addr.into(),
            config: cfg,
            backoff,
            cell: None,
            topic: topic.into(),
            channel: channel.into(),
            state: ConnState::Neg,
            queue: VecDeque::new(),
            auth: auth.into(),
  //          rdy: _rdy,
        }
    }
}

impl Actor for Producer
{
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Context<Self>) {
        Resolver::from_registry()
            .send(Connect::host(self.addr.as_str()))
            .into_actor(self)
            .map(|res, act, ctx| match res {
                Ok(stream) => {
                    info!("Connected to nsqd: {}", act.addr);

                    let (r, w) = stream.split();

                    // write connection
                    let mut framed =
                        actix::io::FramedWrite::new(w, NsqCodec{}, ctx);
                    let mut rx = FramedRead::new(r, NsqCodec{});

                    // send magic version
                    framed.write(Cmd::Magic(VERSION));
                    // send configuration to nsqd
                    let json = match serde_json::to_string(&act.config) {
                        Ok(s) => s,
                        Err(e) => {
                            error!("Config cannot be formatted as json string: {}", e);
                            return ctx.stop();
                        }
                    };
                    // read connection
                    ctx.add_stream(rx);
                    framed.write(identify(json));
                    act.cell = Some(framed);

                    // reset backoff
                    act.backoff.reset();
                }
                Err(err) => {
                    error!("Can not connect to nsqd: {}", err);
                    if let Some(timeout) = act.backoff.next_backoff() {
                        ctx.run_later(timeout, |_, ctx| ctx.stop());
                    }
                }
            })
            .map_err(|err, act, ctx| {
                error!("Can not connect to nsqd: {}", err);
                if let Some(timeout) = act.backoff.next_backoff() {
                    ctx.run_later(timeout, |_, ctx| ctx.stop());
                }
            })
            .wait(ctx);
    }
}

impl actix::io::WriteHandler<io::Error> for Producer
{
    fn error(&mut self, err: io::Error, _: &mut Self::Context) -> Running {
        error!("nsqd connection dropped: {} error: {}", self.addr, err);
        Running::Stop
    }
}

// TODO: Implement error
impl StreamHandler<Cmd, Error> for Producer
{
    fn error(&mut self, err: Error, _ctx: &mut Self::Context) -> Running {
        match err {
            Error::Remote(err) => {
                if let Some(tx) = self.queue.pop_front() {
                    let _ = tx.send(Err(Error::Remote(err)));
                }
                return Running::Continue
            },
            _ => {
                error!("Something goes wrong decoding message");
            },
        };
        Running::Stop
    }

    fn handle(&mut self, msg: Cmd, ctx: &mut Self::Context)
    {
        match msg {
            Cmd::Heartbeat => {
                debug!("received heartbeat");
                if let Some(ref mut cell) = self.cell {
                    cell.write(nop());
                } else {
                    error!("Nsqd connection dropped. trying reconnecting");
                    ctx.stop();
                }
            }
            Cmd::Response(s) => {
                match self.state {
                    ConnState::Neg => {
                        let config: NsqdConfig = match serde_json::from_str(s.as_str()) {
                            Ok(s) => s,
                            Err(err) => {
                                error!("Negotiating json response invalid: {:?}", err);
                                return ctx.stop();
                            }
                        };
                        debug!("json response: {:?}", config);
                        if config.auth_required {
                            ctx.notify(Auth);
                        } else {
                            //ctx.notify(Sub);
                            self.state = ConnState::Started;
                        }
                    },
                    ConnState::Sub => {
                        ctx.notify(Sub);
                    },
                    ConnState::Ready => {
                        debug!("sub response: {}", s);
                        ctx.notify(Ready(0));
                    }
                    _ => {
                        debug!("response: {}", s);
                        if let Some(tx) = self.queue.pop_front() {
                            let _ = tx.send(Ok(Cmd::Response(s)));
                        }
                    },
                }
            },
            _ => {},
        }
    }
}

impl Handler<Auth> for Producer
{
    type Result = ();
    fn handle(&mut self, _msg: Auth, ctx: &mut Self::Context) {
        if let Some(ref mut cell) = self.cell {
            cell.write(auth(self.auth.clone()));
        } else {
            error!("Unable to identify nsqd connection dropped");
            ctx.stop();
        }
        self.state = ConnState::Sub;
    }

}

impl Handler<Sub> for Producer
{
    type Result = ();

    fn handle(&mut self, _msg: Sub, _ctx: &mut Self::Context) {
        if let Some(ref mut cell) = self.cell {
            let topic = self.topic.clone();
            let channel = self.channel.clone();
            cell.write(sub(topic.as_str(), channel.as_str()));
        }
        self.state = ConnState::Ready
    }
}

impl Handler<Ready> for Producer
{
    type Result = ();

    fn handle(&mut self, msg: Ready, _ctx: &mut Self::Context) {
        if let Some(ref mut cell) = self.cell {
            cell.write(rdy(msg.0));
        }
        if self.state != ConnState::Started { self.state = ConnState::Started }
    }
}


impl Handler<Pub> for Producer
{
    type Result = ResponseFuture<Cmd, Error>;

    fn handle(&mut self, msg: Pub, _ctx: &mut Self::Context) -> Self::Result {
        let (tx, rx) = oneshot::channel();
        if let Some(ref mut cell) = self.cell {
            self.queue.push_back(tx);
            let topic = self.topic.clone();
            let m = &msg.0.clone();
            println!("publish: {}", m);
            cell.write(publish(topic.as_str(), &msg.0));
        } else {
            let _ = tx.send(Err(Error::NotConnected));
        }
        Box::new(rx.map_err(|_| Error::Disconnected).and_then(|res| res))
    }
}


impl Supervised for Producer
{
    fn restarting(&mut self, _: &mut Self::Context) {}
}