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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use {error::Error, identity, util::defer};
use log::{info, warn};
use osaka::{osaka, FutureResult};
use prost::Message;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::mem;


use packet;
use headers;
use endpoint;
use proto;
use config;

#[derive(Default)]
struct SubscriberState {
    route:      Option<packet::RoutingKey>,
    streams:    gcmap::HashMap<Vec<u8>, ()>,
    waitreopen: HashMap<Vec<u8>, Instant>
}

#[derive(Default)]
struct ConduitState {
    publishers: HashMap<identity::Identity, ()>,
    subscribed: HashMap<identity::Identity, SubscriberState>,
}

struct ScheduledStream {
    every:      Duration,
    headers:    headers::Headers,
    f:          Box<FnMut(osaka::Poll, endpoint::Stream, identity::Identity, gcmap::MarkOnDrop) -> osaka::Task<()>>,
}


struct Oneshot {
    target:     identity::Identity,
    path:       Vec<u8>,
    headers:    headers::Headers,
    f:          Box<FnMut(osaka::Poll, endpoint::Stream, identity::Identity, gcmap::MarkOnDrop) -> osaka::Task<()>>,
}

/// A conduit is a combined subscribe+connect client that subscribes to all devices on a shadow and streams data from them.
/// For convenience, most common functionality is implemented into this struct, and users only need to implement handling the data.

pub struct Conduit {
    poll:       osaka::Poll,
    ep:         endpoint::Endpoint,
    state:      Arc<RefCell<ConduitState>>,
    last_sync:  Instant,
    schedules:  HashMap<Vec<u8>, ScheduledStream>,
    oneshots:   Vec<Oneshot>,
}

impl Conduit {

    /// create a new conduit as a future.
    /// it will subscribe to the shadow address and maintain a connection to all peers on it
    #[osaka]
    pub fn new(poll: osaka::Poll, config: config::Config) -> Result<Self, Error> {
        let state = Arc::new(RefCell::new(ConduitState::default()));

        let mut ep = endpoint::EndpointBuilder::new(&config)?.connect(poll.clone());
        let mut ep = osaka::sync!(ep)?;

        let shadow = config.subscribe.expect("[subscribe] must be set").shadow;
        let broker = ep.broker();
        ep.open(
            broker,
            headers::Headers::with_path("/carrier.broker.v1/broker/subscribe"),
            |poll, mut stream| {
                stream.small_message(proto::SubscribeRequest {
                    shadow: shadow.as_bytes().to_vec(),
                    filter: Vec::new(),
                });
                handler(poll, stream, state.clone())
            },
        );

        Ok(Self {
            ep,
            poll,
            state,
            last_sync:  Instant::now(),
            schedules:  HashMap::new(),
            oneshots:   Vec::new(),
        })
    }

    #[allow(unreachable_code)]
    #[osaka]
    fn f_schedule<F, M>(_poll: osaka::Poll, mut stream: endpoint::Stream,
                        identity: identity::Identity, mut f: F, mark: gcmap::MarkOnDrop)
    where
        F: 'static + FnMut(&identity::Identity, M),
        M: prost::Message + Default,
    {
        let headers = headers::Headers::decode(&osaka::sync!(stream)).unwrap();
        println!("{:?}", headers);

        loop {
            let ph = osaka::sync!(stream);
            let ph = proto::ProtoHeader::decode(&ph).unwrap();

            let mut b = Vec::new();
            while (b.len() as u64) < ph.len {
                let m = osaka::sync!(stream);
                b.extend(&m);
            }
            let m = M::decode(&b).unwrap();
            f(&identity, m);
        }
        drop(mark);
    }

    /// schedule opening a stream on all devices with the given headers
    ///
    /// `every` is the restart delay, that means if a stream is closed, it wont be restarted before
    /// delay expired. You can use this to poll a get endpoint.
    pub fn schedule<F, M>(&mut self, every: Duration, headers: headers::Headers, f: F)
    where
        F: 'static + FnMut(&identity::Identity, M) + Clone,
        M: prost::Message + Default,
    {
        self.schedules.insert(
            headers.path().expect("header must contain :path").into(),
            ScheduledStream {
                every,
                headers,
                f: Box::new(move |poll, stream, identity, mark|Self::f_schedule(poll,stream, identity, f.clone(), mark)),
            },
        );
    }

    #[allow(unreachable_code)]
    #[osaka]
    fn f_schedule_small<F, M>(_poll: osaka::Poll, mut stream: endpoint::Stream, identity: identity::Identity, mut f: F, mark: gcmap::MarkOnDrop)
    where
        F: 'static + FnMut(&identity::Identity, M),
        M: prost::Message + Default,
    {
        let headers = headers::Headers::decode(&osaka::sync!(stream)).unwrap();
        println!("{:?}", headers);

        loop {
            let m = osaka::sync!(stream);
            let m = M::decode(&m).unwrap();
            f(&identity, m);
        }
        drop(mark);
    }

    /// schedule opening a small stream on all devices with the given headers
    ///
    /// decodes each datagram as message without size prefix, like old carrier clients did
    pub fn schedule_small<F, M>(&mut self, every: Duration, headers: headers::Headers, f: F)
    where
        F: 'static + FnMut(&identity::Identity, M) + Clone,
        M: prost::Message + Default,
    {
        self.schedules.insert(
            headers.path().expect("header must contain :path").into(),
            ScheduledStream {
                every,
                headers,
                f: Box::new(move |poll, stream, identity, mark|Self::f_schedule_small(poll,stream, identity, f.clone(), mark)),
            },
        );
    }

    #[allow(unreachable_code)]
    #[osaka]
    fn f_schedule_raw<F>(_poll: osaka::Poll, mut stream: endpoint::Stream, identity: identity::Identity, mut f: F, mark: gcmap::MarkOnDrop)
    where
        F: 'static + FnMut(&identity::Identity, Vec<u8>),
    {
        let headers = headers::Headers::decode(&osaka::sync!(stream)).unwrap();
        println!("{:?}", headers);

        loop {
            let m = osaka::sync!(stream);
            f(&identity, m);
        }
        drop(mark);
    }

    /// schedule opening a raw stream on all devices with the given headers
    ///
    /// gives you all datagrams as bytes
    pub fn schedule_raw<F>(&mut self, every: Duration, headers: headers::Headers, f: F)
    where
        F: 'static + FnMut(&identity::Identity, Vec<u8>) + Clone,
    {
        self.schedules.insert(
            headers.path().expect("header must contain :path").into(),
            ScheduledStream {
                every,
                headers,
                f: Box::new(move |poll, stream, identity, mark|Self::f_schedule_raw(poll,stream, identity, f.clone(), mark)),
            },
        );
    }


    #[allow(unreachable_code)]
    #[osaka]
    fn f_schedule_null_terminated<F>(_poll: osaka::Poll, mut stream: endpoint::Stream, identity: identity::Identity, mut f: F, mark: gcmap::MarkOnDrop)
    where
        F: 'static + FnMut(&identity::Identity, Vec<u8>),
    {
        let headers = headers::Headers::decode(&osaka::sync!(stream)).unwrap();
        println!("{:?}", headers);

        let mut v : Vec<u8> =  Vec::new();

        loop {
            let m = osaka::sync!(stream);
            v.reserve(m.len());
            for ch in m {
                if ch == 0 {
                    f(&identity, mem::replace(&mut v, Vec::new()));
                } else {
                    v.push(ch);
                }
            }
        }
        drop(mark);
    }

    /// schedule opening a stream where each message is terminated with \0
    ///
    /// it is memory unbounded, meaning an infinite stream will OOM your system
    ///
    /// this stream type was a bad idea and you should only use it if you have legacy devices out there
    /// that need it
    ///
    ///
    ///
    pub fn schedule_null_terminated<F>(&mut self, every: Duration, headers: headers::Headers, f: F)
    where
        F: 'static + FnMut(&identity::Identity, Vec<u8>) + Clone,
    {
        self.schedules.insert(
            headers.path().expect("header must contain :path").into(),
            ScheduledStream {
                every,
                headers,
                f: Box::new(move |poll, stream, identity, mark|Self::f_schedule_null_terminated(poll,stream, identity, f.clone(), mark)),
            },
        );
    }

    /// open a stream on a specific peer, once
    ///
    pub fn call<F, M>(&mut self, target: identity::Identity, headers: headers::Headers, f: F)
    where
        F: 'static + FnMut(&identity::Identity, M) + Clone,
        M: prost::Message + Default,
    {
        self.oneshots.push(Oneshot{
            path: headers.path().expect("header must contain :path").into(),
            headers,
            target,
            f: Box::new(move |poll, stream, identity, mark|Self::f_schedule(poll,stream, identity, f.clone(), mark)),
        });
    }

}

impl osaka::Future<Result<(), Error>> for Conduit {
    fn poll(&mut self) -> osaka::FutureResult<Result<(), Error>> {
        if self.last_sync.elapsed().as_secs() > 1 {
            self.last_sync = Instant::now();
            let mut state = self
                .state
                .try_borrow_mut()
                .expect("carrier is not thread safe");
            for (p, _) in state.publishers.clone() {
                if !state.subscribed.contains_key(&p) {
                    osaka::try!(self.ep.connect(p.clone()));
                    state.subscribed.insert(p, SubscriberState::default());
                }
            }

            for (id, sc) in &mut state.subscribed {
                if let Some(route) = sc.route {

                    let mut oneshots_remaining = Vec::new();
                    oneshots_remaining.reserve(self.oneshots.len());
                    for mut oneshot in self.oneshots.drain(..) {
                        if &oneshot.target == id {
                            if sc.streams.get(&oneshot.path).is_none() {
                                info!(
                                    "[{}] opening oneshot stream {}",
                                    id,
                                    String::from_utf8_lossy(&oneshot.path)
                                    );
                                let (mark, _) = sc.streams.insert(oneshot.path.clone(), ());
                                self.ep
                                    .open(route, oneshot.headers.clone(), move |poll, stream| {
                                        (oneshot.f)(poll, stream, id.clone(), mark)
                                    });

                            }
                        } else {
                            oneshots_remaining.push(oneshot);
                        }
                    }
                    self.oneshots = oneshots_remaining;


                    for (path, schedule) in &mut self.schedules {
                        if sc.streams.get(path).is_none() {
                            if let Some(wait) = sc.waitreopen.get(path) {
                                if wait.elapsed() < schedule.every {
                                    continue;
                                }
                            }
                            sc.waitreopen.remove(path);

                            info!(
                                "[{}] opening scheduled stream {}",
                                id,
                                String::from_utf8_lossy(path)
                            );
                            let (mark, _) = sc.streams.insert(path.clone(), ());
                            sc.waitreopen.insert(path.clone(), Instant::now());
                            self.ep
                                .open(route, schedule.headers.clone(), |poll, stream| {
                                    (schedule.f)(poll, stream, id.clone(), mark)
                                });
                        }
                    }
                }
            }
        }

        loop {
            match self.ep.poll() {
                FutureResult::Done(Ok(endpoint::Event::Disconnect {
                    identity, ..
                })) => {
                    let mut state = self
                        .state
                        .try_borrow_mut()
                        .expect("carrier is not thread safe");
                    if let Some(_old) = state.subscribed.remove(&identity) {
                        info!("disconnect {}", identity);
                    }
                }
                FutureResult::Done(Ok(endpoint::Event::OutgoingConnect(q))) => {

                    if q.ok() {
                        let identity = q.identity.clone();
                        let identity_ = q.identity.clone();
                        let route = self
                            .ep
                            .accept_outgoing(q, move |h, _s| {
                                warn!("rejecting incomming stream from {}: {:?}", identity, h);
                                None
                            })
                        .unwrap();
                        info!("accepting outgoing connect {} ::> {}", identity_, route);
                        let mut state = self
                            .state
                            .try_borrow_mut()
                            .expect("carrier is not thread safe");
                        if let Some(sc) = state.subscribed.get_mut(&identity_) {
                            sc.route = Some(route);
                        }
                    } else {
                        let mut state = self
                            .state
                            .try_borrow_mut()
                            .expect("carrier is not thread safe");
                        if let Some(_) = state.subscribed.remove(&q.identity) {
                            warn!("failed outgoing connect {}", q.identity);
                        }
                    }

                }
                FutureResult::Done(Ok(endpoint::Event::IncommingConnect(q))) => {
                    warn!("ignoring incomming connect {}", q.identity);
                }
                FutureResult::Done(Err(e)) => return FutureResult::Done(Err(e)),
                FutureResult::Again(mut y) => {
                    y.merge(self.poll.later(Duration::from_secs(1)));
                    return FutureResult::Again(y);
                }
            };
        }
    }
}

#[osaka]
fn handler(
    _poll: osaka::Poll,
    mut stream: endpoint::Stream,
    state: Arc<RefCell<ConduitState>>,
) {
    let _d = defer(|| {
        panic!("subscribe stream closed");
    });
    use prost::Message;

    let m = osaka::sync!(stream);
    let headers = headers::Headers::decode(&m).unwrap();
    info!("pubres: {:?}", headers);

    loop {
        let sc = proto::SubscribeChange::decode(osaka::sync!(stream)).unwrap();
        match sc.m {
            Some(proto::subscribe_change::M::Publish(proto::Publish {
                identity,
                xaddr: _,
            })) => {
                let identity = identity::Identity::from_bytes(identity).unwrap();
                info!("+ {}", identity);

                state
                    .try_borrow_mut()
                    .expect("carrier is not thread safe")
                    .publishers
                    .insert(identity, ());
            }
            Some(proto::subscribe_change::M::Unpublish(proto::Unpublish {
                identity,
            })) => {
                let identity = identity::Identity::from_bytes(identity).unwrap();
                info!("- {}", identity);

                state
                    .try_borrow_mut()
                    .expect("carrier is not thread safe")
                    .publishers
                    .remove(&identity);
            }
            Some(proto::subscribe_change::M::Supersede(_)) => {
                panic!("subscriber superseded");
            }
            None => (),
        }
    }
}