carrier 0.12.2

carrier is a generic secure message system for IoT
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
use log::{info, warn};
use osaka::{osaka, FutureResult};
use prost::Message;
use rand::{self, Rng};
use std::collections::HashMap;
use std::mem;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use config;
use endpoint;
use headers;
use packet;
use proto;
use {channel, dns, error::Error, identity, util::defer};

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


#[derive(Default, Clone)]
pub struct PeerSetup {
    schedules:      Arc<Mutex<HashMap<Vec<u8>, ScheduledStream>>>,
    disconnected:   Arc<Mutex<Option<Box<dyn Fn(identity::Identity, channel::DisconnectReason) + Send + Sync>>>>,
}


pub struct ConduitState {
    publishers: HashMap<identity::Identity, PeerSetup>,
    subscribed: HashMap<identity::Identity, SubscriberState>,
}

struct BrokerWorker {
    last_sync: Instant,
    ep:        endpoint::Endpoint,
    poll:      osaka::Poll,
    shard:     usize,
    state:     Arc<Mutex<ConduitState>>,
    cooldown:  HashMap<identity::Identity, Instant>,
}

#[derive(Clone)]
struct ScheduledStream {
    every:   Option<Duration>,
    headers: headers::Headers,
    f: Arc<
        Box<dyn Fn(osaka::Poll, endpoint::Stream, identity::Identity, gcmap::MarkOnDrop) -> osaka::Task<()> + Send + Sync>,
    >,
}

struct Thread {
    running: Arc<Mutex<()>>,
}

/// 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 Builder {
    config:  config::Config,
}


pub trait OnPublish: 'static + Fn(identity::Identity, Arc<Mutex<ConduitState>>) + Send + Sync {}
impl<F>  OnPublish for F where F: 'static + Fn(identity::Identity, Arc<Mutex<ConduitState>>) + Send + Sync {}

impl Builder {
    /// create a new conduit
    /// it will subscribe to the shadow address and maintain a connection to all peers on it
    pub fn new(config: config::Config) -> Result<Self, Error> {
        Ok(Self {
            config,
        })
    }

    fn resolve(brk: &Vec<String>) -> Vec<dns::DnsRecord> {
        if let Ok(v) = std::env::var("CARRIER_BROKERS") {
            v.split(";")
                .filter_map(|v| dns::DnsRecord::from_signed_txt(v))
                .collect()
        } else {
            let d = if let Ok(d) = std::env::var("CARRIER_BROKER_DOMAINS") {
                d.split(":").map(String::from).collect::<Vec<String>>()
            } else {
                brk.clone()
            };

            let v: Vec<String> = match osaka_dns::resolve(osaka::Poll::new(), d).run() {
                Err(e) => {
                    error!("{:?}", e);
                    return Vec::new();
                }
                Ok(v) => v,
            };
            v.into_iter()
                .filter_map(|v| dns::DnsRecord::from_signed_txt(v))
                .collect()
        }
    }

    pub fn start<F: OnPublish + Clone>(self, f: F) {
        let mut threads : HashMap<SocketAddr, (dns::DnsRecord, HashMap<usize, Thread>)> = HashMap::new();
        let mt = num_cpus::get();

        let mut records = Self::resolve(&self.config.broker);
        info!("records: {:?}", records);
        let mut refresh = Instant::now();

        thread::spawn(move || { let dropexit = DropExit{}; loop {
            if refresh.elapsed() >= Duration::from_secs(15) {
                records = Self::resolve(&self.config.broker);
                info!("records: {:?}", records);
                refresh = Instant::now();
            }

            for record in &records {
                if !threads.contains_key(&record.addr) {
                    threads.insert(record.addr, (record.clone(), HashMap::new()));
                }
            }

            let config = self.config.clone();
            threads.retain(|_, (record, threads)| {
                debug!("{} has {} live threads", record.addr, threads.len());

                threads.retain(|_, th| match th.running.try_lock() {
                    Err(std::sync::TryLockError::WouldBlock) => true,
                    _ => false,
                });

                for i in 0..mt {
                    if !threads.contains_key(&i) {
                        info!("spawning new thread for addr {} shard {}", record.addr, i);
                        let lock = Arc::new(Mutex::new(()));
                        let lock_ = lock.clone();

                        let config = config.clone();
                        let record = record.clone();
                        let f = f.clone();
                        thread::Builder::new()
                            .name(format!("cond-{}-{}", i, record.addr))
                            .spawn(move ||{
                                let a = lock_.lock().unwrap();
                                thread::sleep(Duration::from_millis(rand::thread_rng().gen_range(100, 2000)));
                                Self::broker_thread(config.clone(), i, mt, record.clone(), f.clone());
                                error!("end of thread for addr {} shard {}", record.addr, i);
                                drop(a);
                            })
                            .unwrap();
                        threads.insert(i, Thread { running: lock });
                    }
                }

                threads.len() > 0
            });

            thread::sleep(Duration::from_secs(1));

        } drop(dropexit); });
    }


    fn broker_thread<F: OnPublish>(mut config: config::Config, i: usize, mt: usize, record: dns::DnsRecord, f: F) {
        //TODO some day when p2p actually works
        config.port = None;

        let poll = osaka::Poll::new();
        let mut ep = endpoint::EndpointBuilder::new(&config).unwrap();
        ep.do_not_move();
        let mut ep = ep
            .connect_to(poll.clone(), record)
            .run()
            .unwrap()
            .0
            .expect("broker con");

        let subconf = config.subscribe.expect("[subscribe] must be set");
        let shadow = subconf.shadow;
        let group = subconf.group;
        let broker = ep.broker();

        let state = Arc::new(Mutex::new(ConduitState {
            publishers: HashMap::new(),
            subscribed: HashMap::new(),
        }));


        let handle = ep.handle();

        ep.open(
            broker,
            headers::Headers::with_path("/carrier.broker.v1/broker/subscribe"),
            None,
            |poll, mut stream| {
                stream.message(proto::SubscribeRequest {
                    shadow:          shadow.as_bytes().to_vec(),
                    group_identity:  group
                        .as_ref()
                        .map(|v| v.identity().as_bytes().to_vec())
                        .unwrap_or(Vec::new()),
                        group_signature: group
                            .as_ref()
                            .map(|v| {
                                v.sign(b"subscribegroup", shadow.as_bytes()).as_bytes().to_vec()
                            })
                    .unwrap_or(Vec::new()),
                });
                subscribe_handler(poll, stream, handle, state.clone(), i, mt, f)
            },
        )
        .unwrap();

        let mut xep = BrokerWorker {
            last_sync: Instant::now(),
            ep,
            state,
            shard: i,
            poll: poll.clone(),
            cooldown: HashMap::new(),
        };

        use osaka::Future;
        let again = match xep.poll() {
            osaka::FutureResult::Done(v) => {
                v.unwrap();
                return;
            }
            osaka::FutureResult::Again(again) => again,
        };
        osaka::Task::new(Box::new(xep), again).run().unwrap();
    }
}

impl osaka::Future<Result<(), Error>> for BrokerWorker {
    fn poll(&mut self) -> osaka::FutureResult<Result<(), Error>> {
        if self.last_sync.elapsed().as_millis() > 200 + rand::thread_rng().gen_range(0, 100) {

            self.last_sync = Instant::now();
            let mut state = self.state.lock().unwrap();

            // subscribe to any client that we don't have
            let mut max_per_second = 0;
            for p in state.publishers.keys().cloned().collect::<Vec<identity::Identity>>().into_iter() {
                if !state.subscribed.contains_key(&p) {
                    if let Some(is) = self.cooldown.remove(&p) {
                        if is.elapsed().as_secs() < 10 {
                            self.cooldown.insert(p, is);
                            continue;
                        }
                    }

                    osaka::try!(self.ep.connect(p.clone(), 20));
                    state.subscribed.insert(p, SubscriberState::default());

                    // don't connect all at once
                    max_per_second += 1;
                    if max_per_second > 100 {
                        break;
                    }
                }
            }

            // for each subscribed client
            let mut max_open_per_second = 0;
            let mut killed = Vec::new();
            let mut subscribed = mem::replace(&mut state.subscribed, HashMap::new());
            for (id, sc) in &mut subscribed {
                // don't starve
                if self.last_sync.elapsed().as_millis() > 1000 {
                    error!("main loop starved");
                    break;
                }
                if sc.kill {
                    info!("killed {} by applicaton choice", id);
                    killed.push(id.clone());
                    if let Some(route) = sc.route {
                        osaka::try!(self.ep.disconnect(route, packet::DisconnectReason::Application));
                    }
                    continue;
                }

                // check all the routes
                if let (Some(route), Some(setup)) = (sc.route, state.publishers.get(id)) {
                    let mut schedules = setup.schedules.try_lock().expect("carrier is not thread safe");
                    let mut remove_schedule = Vec::new();
                    for (path, schedule) in schedules.iter() {
                        // we don't have this route, open it
                        if sc.streams.get(path).is_none() {
                            if let Some(wait) = sc.waitreopen.get(path) {
                                match schedule.every {
                                    Some(every) => {
                                        if wait.elapsed() < every {
                                            continue;
                                        }
                                    },
                                    None => {
                                        remove_schedule.push(path.clone());
                                        continue;
                                    }
                                }
                            }

                            // don't connect all at once
                            max_open_per_second += 1;
                            if max_open_per_second > 100 {
                                break;
                            }

                            sc.waitreopen.remove(path);

                            let (mark, _) = sc.streams.insert(path.clone(), ());
                            sc.waitreopen.insert(path.clone(), Instant::now());
                            let stream = osaka::try!(self.ep.open(
                                route,
                                schedule.headers.clone(),
                                Some(0xfffffff),
                                |poll, stream| { (schedule.f)(poll, stream, id.clone(), mark) }
                            ));
                            debug!(
                                "[{}] [{}] opened scheduled stream {} -> {}",
                                self.shard,
                                id,
                                stream,
                                String::from_utf8_lossy(path)
                            );
                        }
                    }

                    // remove completed onceshots
                    for rm in remove_schedule {
                        schedules.remove(&rm);
                    }
                }
            }

            // remove all disconnected peers
            for id in killed {
                self.cooldown.insert(id.clone(), Instant::now());
                subscribed.remove(&id);

                if let Some(setup) = state.publishers.get(&id) {
                    if let Some(ref mut f) = *setup.disconnected.try_lock().expect("carrier is not thread safe") {
                        f(id.clone(), channel::DisconnectReason::None);
                    }
                }
            }
            state.subscribed = subscribed;
        }

        loop {
            let r = self.ep.poll();
            let mut state = self.state.lock().unwrap();
            match r {
                FutureResult::Done(Ok(endpoint::Event::BrokerGone)) => panic!("broker gone"),
                FutureResult::Done(Ok(endpoint::Event::Disconnect { identity, reason, .. })) => {
                    if let Some(_old) = state.subscribed.remove(&identity) {
                        self.cooldown.insert(identity.clone(), Instant::now());
                        info!("[{}] disconnect {} {:?}", self.shard, identity, reason);
                        if let Some(setup) = state.publishers.get(&identity) {
                            if let Some(ref mut f) = *setup.disconnected.try_lock().expect("carrier is not thread safe") {
                                f(identity.clone(), reason);
                            }
                        }
                    }
                }
                FutureResult::Done(Ok(endpoint::Event::OutgoingConnect(q))) => {
                    if q.ok() {
                        let identity = q.identity.clone();
                        let identity_ = q.identity.clone();
                        let selfshard = self.shard;
                        let route = self
                            .ep
                            .accept_outgoing(q, move |h, _s| {
                                warn!("[{}] rejecting incomming stream from {}: {:?}", selfshard, identity, h);
                                None
                            })
                            .unwrap();
                        info!("[{}] accepting outgoing connect {} ::> {}", self.shard, identity_, route);
                        if let Some(sc) = state.subscribed.get_mut(&identity_) {
                            sc.route = Some(route);
                        }
                        //disconnect
                    } else {
                        if let Some(_) = state.subscribed.remove(&q.identity) {
                            if let Some(cr) = q.cr {
                                warn!("[{}] failed outgoing connect {} : {}", self.shard, q.identity, cr.error);
                                self.cooldown.insert(q.identity.clone(), Instant::now());
                                //disconnect
                            } else {
                                warn!("[{}] failed outgoing connect {}", self.shard, 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 subscribe_handler<F: OnPublish>(
    _poll: osaka::Poll,
    mut stream: endpoint::Stream,
    ep: endpoint::Handle,
    state: Arc<Mutex<ConduitState>>,
    shard: usize,
    shard_count: usize,
    f: F,
) {
    let _d = defer(move || {
        ep.disconnect(ep.broker(), packet::DisconnectReason::Application);
        log::error!("subscribe stream closed");
    });
    use prost::Message;

    let m = osaka::sync!(stream);
    let headers = headers::Headers::decode(&m).unwrap();
    info!("sub response: {:?}", 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();

                use std::collections::hash_map::DefaultHasher;
                use std::hash::{Hash, Hasher};
                let mut hasher = DefaultHasher::new();
                identity.hash(&mut hasher);
                let r = hasher.finish();
                if r % shard_count as u64 == shard as u64 {
                    info!("[{:?} {}] + {}", thread::current().id(), shard, identity);

                    {
                        let mut state = state.lock().unwrap();
                        if let Some(sub) = state.subscribed.get_mut(&identity) {
                            info!("we have a previous subscription");
                            sub.kill = true;
                        }
                    }

                    f(identity, state.clone());
                }
            }
            Some(proto::subscribe_change::M::Unpublish(proto::Unpublish { identity })) => {
                let identity = identity::Identity::from_bytes(identity).unwrap();
                info!("- {}", identity);

                let mut state = state.lock().unwrap();

                if let Some(sub) = state.subscribed.get_mut(&identity) {
                    sub.kill = true;
                }

                if state.publishers.remove(&identity).is_some() {
                    //unpub
                }
            }
            Some(proto::subscribe_change::M::Supersede(_)) => {
                panic!("subscriber superseded");
            }
            None => (),
        }
    }
}



impl ConduitState {
    pub fn connect(&mut self, identity: identity::Identity) -> PeerSetup  {
        let a = PeerSetup::default();
        if self.publishers.insert(identity, a.clone()).is_some() {
            //unpub
        }
        a
    }
}




impl PeerSetup {
    #[allow(unreachable_code)]
    #[osaka]
    fn f_schedule_ph<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();
        log::trace!("{:?}", 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_ph<F, M>(&mut self, every: Duration, headers: headers::Headers, f: F)
    where
        F: 'static + FnMut(&identity::Identity, M) + Clone + Send + Sync,
        M: prost::Message + Default,
    {
        let mut schedules = self.schedules.try_lock().expect("carrier is not thread safe");
        schedules.insert(
            headers.path().expect("header must contain :path").into(),
            ScheduledStream {
                every: Some(every),
                headers,
                f: Arc::new(Box::new(move |poll, stream, identity, mark| {
                    Self::f_schedule_ph(poll, stream, identity, f.clone(), mark)
                })),
            },
        );
    }

    #[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 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<F, M>(&mut self, every: Duration, headers: headers::Headers, f: F)
    where
        F: 'static + FnMut(&identity::Identity, M) + Clone + Send + Sync,
        M: prost::Message + Default,
    {
        let mut schedules = self.schedules.try_lock().expect("carrier is not thread safe");
        schedules.insert(
            headers.path().expect("header must contain :path").into(),
            ScheduledStream {
                every: Some(every),
                headers,
                f: Arc::new(Box::new(move |poll, stream, identity, mark| {
                    Self::f_schedule(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 + Send + Sync,
    {
        let mut schedules = self.schedules.try_lock().expect("carrier is not thread safe");
        schedules.insert(
            headers.path().expect("header must contain :path").into(),
            ScheduledStream {
                every: Some(every),
                headers,
                f: Arc::new(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,
        f: F,
        mark: gcmap::MarkOnDrop,
    ) where
        F: 'static + Fn(&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 + Fn(&identity::Identity, Vec<u8>) + Clone + Send + Sync,
    {
        let mut schedules = self.schedules.try_lock().expect("carrier is not thread safe");
        schedules.insert(
            headers.path().expect("header must contain :path").into(),
            ScheduledStream {
                every: Some(every),
                headers,
                f: Arc::new(Box::new(move |poll, stream, identity, mark| {
                    Self::f_schedule_null_terminated(poll, stream, identity, f.clone(), mark)
                })),
            },
        );
    }



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

        if headers.get(b":status") != Some(b"200") {
            f(proto::DiscoveryResponse::default());
            return;
        }

        loop {
            let m = osaka::sync!(stream);
            let m = proto::DiscoveryResponse::decode(&m).unwrap();
            f(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 discovery<F> (&mut self, f: F)
        where F: 'static + FnMut(proto::DiscoveryResponse) + Send + Sync + Clone
    {
        let headers = headers::Headers::with_path("/v2/carrier.discovery.v1/discover");
        let mut schedules = self.schedules.try_lock().expect("carrier is not thread safe");
        schedules.insert(
            headers.path().expect("header must contain :path").into(),
            ScheduledStream {
                every: None,
                headers,
                f: Arc::new(Box::new(move |poll, stream, identity, mark| {
                    Self::f_discovery(poll, stream, identity, f.clone(), mark)
                })),
            },
        );
    }


    /// callback on disconnect
    pub fn on_disconnect<F> (&mut self, f: F)
    where
        F: 'static + Fn(identity::Identity, channel::DisconnectReason) + Clone + Send + Sync,
    {
        *self.disconnected
            .try_lock()
            .expect("carrier is not thread safe") = Some(Box::new(f));
    }
}

struct DropExit {}
impl Drop for DropExit {
    fn drop(&mut self) {
        eprintln!("exit because conduit main thread dropped");
        std::process::exit(1);
    }
}