snocat 0.7.0

Streaming Network Overlay Connection Arbitration Tunnel
Documentation
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license OR Apache 2.0
use authentication::perform_authentication;
use dashmap::DashMap;
use futures::{
  future::{self, BoxFuture, TryFutureExt},
  Future, Stream, StreamExt, TryStreamExt,
};
use std::{
  fmt::{Debug, Display},
  hash::Hash,
  sync::{Arc, Mutex, Weak},
  time::{Instant, SystemTime},
};
use tokio::sync::broadcast::{channel as event_channel, Sender as Broadcaster};
use tracing::Instrument;

use crate::{
  common::{
    authentication::{self, AuthenticationError, AuthenticationHandler},
    protocol::{
      negotiation::{self, NegotiationError, NegotiationService},
      service::Router,
      tunnel::{
        self, id::TunnelIDGenerator, registry::TunnelRegistry, AssignTunnelId, Tunnel,
        TunnelDownlink, TunnelError, TunnelId, TunnelIncomingType, TunnelName, WithTunnelId,
      },
      RouteAddress, ServiceRegistry,
    },
  },
  util::{cancellation::CancellationListener, dropkick::Dropkick, tunnel_stream::WrappedStream},
};

use super::{
  authentication::{AuthenticationAttributes, AuthenticationHandlingError},
  protocol::tunnel::{ArcTunnel, TunnelControl, TunnelMonitoring},
};

#[derive(Clone)]
pub struct PeerRecord {
  pub id: TunnelId,
  pub name: TunnelName,
  pub registered_at: (Instant, std::time::SystemTime),
  pub attributes: Arc<AuthenticationAttributes>,
  pub tunnel: Arc<dyn Tunnel + Send + Sync + 'static>,
}

impl Debug for PeerRecord {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_struct("PeerTunnel")
      .field("id", &self.id)
      .field("name", &self.name)
      .finish_non_exhaustive()
  }
}

impl PartialEq for PeerRecord {
  fn eq(&self, other: &Self) -> bool {
    self.id == other.id && self.name == other.name
  }
}
impl Eq for PeerRecord {}

/// [PeerTunnel] uses the ID and Name fields for hashing, skipping tunnel attributes
impl Hash for PeerRecord {
  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
    self.id.hash(state);
    self.name.hash(state);
  }
}

#[derive(Clone)]
pub struct PeersView {
  by_name: Weak<DashMap<TunnelName, Arc<DashMap<TunnelId, Weak<PeerRecord>>>>>,
  by_id: Weak<Arc<DashMap<TunnelId, Weak<PeerRecord>>>>,
}

impl PeersView {
  #[must_use]
  pub fn new(
    peers_by_name: Weak<DashMap<TunnelName, Arc<DashMap<TunnelId, Weak<PeerRecord>>>>>,
    peers_by_id: Weak<Arc<DashMap<TunnelId, Weak<PeerRecord>>>>,
  ) -> Self {
    Self {
      by_name: peers_by_name,
      by_id: peers_by_id,
    }
  }

  pub fn get_by_id(&self, tunnel_id: &TunnelId) -> Option<Arc<PeerRecord>> {
    if let Some(peers_by_id) = self.by_id.upgrade() {
      peers_by_id.get(tunnel_id).and_then(|x| x.upgrade())
    } else {
      None
    }
  }

  pub fn get_by_name(&self, tunnel_name: &TunnelName) -> Vec<Arc<PeerRecord>> {
    if let Some(peers_by_name) = self.by_name.upgrade() {
      if let Some(subtable) = peers_by_name.get(tunnel_name) {
        subtable
          .iter()
          .flat_map(|kv| Weak::upgrade(&kv.value()))
          .collect()
      } else {
        Default::default()
      }
    } else {
      Default::default()
    }
  }

  pub fn find_by_name_and_predicate<P: for<'a> Fn(&'a PeerRecord) -> bool>(
    &self,
    tunnel_name: &TunnelName,
    predicate: P,
  ) -> Option<Arc<PeerRecord>> {
    if let Some(peers_by_name) = self.by_name.upgrade() {
      if let Some(subtable) = peers_by_name.get(tunnel_name) {
        subtable.iter().find_map(|kv| {
          if let Some(upgraded) = kv.upgrade() {
            if predicate(upgraded.as_ref()) {
              Some(upgraded)
            } else {
              None
            }
          } else {
            None
          }
        })
      } else {
        Default::default()
      }
    } else {
      Default::default()
    }
  }

  /// Allows fetching a tunnel by comparing its attributes with those of all others
  pub fn find_by_comparator<Ordering: std::cmp::Ord, P: for<'a> Fn(&'a PeerRecord) -> Ordering>(
    &self,
    comparator_predicate: P,
  ) -> Option<Arc<PeerRecord>> {
    if let Some(peers_by_id) = self.by_id.upgrade() {
      peers_by_id
        .iter()
        .filter_map(|kv| kv.upgrade())
        .max_by_key(|tunnel| comparator_predicate(tunnel.as_ref()))
    } else {
      Default::default()
    }
  }

  /// Allows fetching a tunnel by comparing its attributes with those of others with the same name
  pub fn find_by_name_and_comparator<
    Ordering: std::cmp::Ord,
    P: for<'a> Fn(&'a PeerRecord) -> Ordering,
  >(
    &self,
    tunnel_name: &TunnelName,
    comparator_predicate: P,
  ) -> Option<Arc<PeerRecord>> {
    if let Some(peers_by_name) = self.by_name.upgrade() {
      if let Some(subtable) = peers_by_name.get(tunnel_name) {
        subtable
          .iter()
          .filter_map(|kv| kv.upgrade())
          .max_by_key(|tunnel| comparator_predicate(tunnel.as_ref()))
      } else {
        Default::default()
      }
    } else {
      Default::default()
    }
  }

  /// Fetch a vector of all active tunnels
  pub fn all(&self) -> Vec<Arc<PeerRecord>> {
    self
      .by_id
      .upgrade()
      .iter()
      .flat_map(|by_id| by_id.iter().filter_map(|kv| kv.value().upgrade()))
      .collect()
  }
}

#[derive(Clone, Default)]
pub struct PeerTracker {
  by_name: Arc<DashMap<TunnelName, Arc<DashMap<TunnelId, Weak<PeerRecord>>>>>,
  by_id: Arc<Arc<DashMap<TunnelId, Weak<PeerRecord>>>>,
}

impl PeerTracker {
  #[must_use]
  pub fn new() -> Self {
    Self {
      by_id: Default::default(),
      by_name: Default::default(),
    }
  }

  #[must_use]
  pub fn view(&self) -> PeersView {
    PeersView {
      by_name: Arc::downgrade(&self.by_name),
      by_id: Arc::downgrade(&self.by_id),
    }
  }

  fn insert(&self, record: &Arc<PeerRecord>) {
    self.by_id.insert(record.id, Arc::downgrade(record));
    self
      .by_name
      .entry(record.name.clone())
      .or_insert_with(|| Default::default())
      .insert(record.id, Arc::downgrade(record));
  }
}

struct DeregisteringTunnelWrapper<TRegistry: ?Sized, TRecordIdent> {
  registry: Arc<TRegistry>,
  record_identifier: TRecordIdent,
  peers: PeersView,
  peer_record: Arc<PeerRecord>,
  disconnection_broadcaster: Arc<Broadcaster<TunnelDisconnectedEvent>>,
}

impl<TRegistry: ?Sized>
  DeregisteringTunnelWrapper<TRegistry, <TRegistry as TunnelRegistry>::Identifier>
where
  TRegistry: TunnelRegistry,
{
  pub fn into_deregistration_dropkick(
    self,
  ) -> Dropkick<Arc<Mutex<Option<Box<dyn FnOnce() + Send + Sync + 'static>>>>> {
    Dropkick::new(Arc::new(Mutex::new(Some(Box::new(move || {
      tokio::task::spawn(async move {
        self.deregister_identifier().await;
      });
    })))))
  }

  async fn deregister_identifier(self) {
    // Fire disconnected event
    let _ = self
      .disconnection_broadcaster
      .send(TunnelDisconnectedEvent {
        id: self.peer_record.id,
      });
    // Deregister from local by-id and by-name tables
    // These are held behind a weakref, because if they're already gone, we have no need to clear them
    // Because these map containers perform a lot of mutexing, we run them in a blocking thread and move on.
    tokio::task::spawn_blocking({
      let peers_by_name = self.peers.by_name;
      let peers_by_id = self.peers.by_id;
      let peer_record = self.peer_record;
      move || {
        if let Some(peers_by_id) = peers_by_id.upgrade() {
          peers_by_id.remove(&peer_record.id);
        }
        if let Some(peers_by_name) = peers_by_name.upgrade() {
          // Fetch by-id sub-entry for the specified name
          let by_id = peers_by_name.get(&peer_record.name).map(|x| Arc::clone(&x));
          // Clear the given ID from the map, if it is present
          by_id.map(|peers_by_id| peers_by_id.remove(&peer_record.id));
          // Shrink by-name table by removing empty by-id sub-entries
          peers_by_name.retain(|_, peers_by_id: &mut Arc<DashMap<_, _>>| !peers_by_id.is_empty());
        }
      }
    })
    .await
    .expect("PeerTunnel clear operation failed to rejoin");
    let res = self
      .registry
      .deregister_identifier(self.record_identifier)
      .await;
    if let Err(e) = res {
      tracing::warn!(error = ?e, "Failed to deregister tunnel: {}", e);
    }
  }
}

struct WrappedTunnel<TTunnel> {
  tunnel: Arc<TTunnel>,
  drop_callback: Arc<Dropkick<Arc<Mutex<Option<Box<dyn FnOnce() + Send + Sync + 'static>>>>>>,
}

impl<TTunnel> Clone for WrappedTunnel<TTunnel> {
  fn clone(&self) -> Self {
    Self {
      tunnel: Arc::clone(&self.tunnel),
      drop_callback: Arc::clone(&self.drop_callback),
    }
  }
}

impl<TTunnel> WrappedTunnel<TTunnel> {
  pub fn new_deregistering<TRegistry: ?Sized, TRecordIdent>(
    tunnel: Arc<TTunnel>,
    registry: Arc<TRegistry>,
    record_identifier: TRecordIdent,
    peers: PeersView,
    peer_record: Arc<PeerRecord>,
    disconnection_broadcaster: Arc<Broadcaster<TunnelDisconnectedEvent>>,
  ) -> Self
  where
    TRegistry: TunnelRegistry<Identifier = TRecordIdent>,
  {
    let inner = DeregisteringTunnelWrapper {
      registry,
      record_identifier,
      peers,
      peer_record,
      disconnection_broadcaster,
    };
    Self {
      tunnel: tunnel,
      drop_callback: Arc::new(inner.into_deregistration_dropkick()),
    }
  }

  pub fn new_registration_failure_closing(tunnel: Arc<TTunnel>) -> Self
  where
    TTunnel: Send + Sync + TunnelControl + 'static,
  {
    let target = tunnel.clone();
    Self {
      tunnel,
      drop_callback: Arc::new(Dropkick::new(Arc::new(Mutex::new(Some(Box::new(
        move || {
          tokio::task::spawn(async move {
            TunnelControl::close(
              &target,
              tunnel::TunnelCloseReason::AuthenticationFailure {
                remote_responsible: None,
              },
            )
            .await
          });
        },
      )))))),
    }
  }

  /// Removes the tunnel from the wrapper and prevents the drop callback from executing
  pub fn extract_inner(self) -> Arc<TTunnel> {
    self.drop_callback.counter_take_mutex();
    self.tunnel
  }

  pub fn as_inner(&self) -> &Arc<TTunnel> {
    &self.tunnel
  }
}

impl<TTunnel> From<WrappedTunnel<TTunnel>> for Arc<TTunnel> {
  fn from(v: WrappedTunnel<TTunnel>) -> Self {
    v.tunnel
  }
}

impl<TTunnel> Debug for WrappedTunnel<TTunnel>
where
  TTunnel: Debug,
{
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    Debug::fmt(&self.tunnel, f)
  }
}

impl<TTunnel> std::ops::Deref for WrappedTunnel<TTunnel> {
  type Target = TTunnel;

  fn deref(&self) -> &Self::Target {
    &self.tunnel
  }
}

pub struct TunnelConnectedEvent {
  pub tunnel: Arc<dyn Tunnel + 'static>,
}

impl Debug for TunnelConnectedEvent {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_struct(std::any::type_name::<TunnelConnectedEvent>())
      .field("id", self.tunnel.id())
      .finish()
  }
}

impl Clone for TunnelConnectedEvent {
  fn clone(&self) -> Self {
    Self {
      tunnel: self.tunnel.clone(),
    }
  }
}

#[derive(Clone)]
pub struct TunnelAuthenticatedEvent {
  pub tunnel: Arc<dyn Tunnel + 'static>,
  pub name: TunnelName,
  pub attributes: Arc<AuthenticationAttributes>,
}

impl Debug for TunnelAuthenticatedEvent {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_struct(std::any::type_name::<TunnelAuthenticatedEvent>())
      .field("id", self.tunnel.id())
      .finish()
  }
}

#[derive(Debug, Clone)]
pub struct TunnelDisconnectedEvent {
  pub id: TunnelId,
  // pub reason: Option<DisconnectReason>,
}

pub struct ModularDaemon<
  TTunnelRegistry: ?Sized,
  TServiceRegistry: ?Sized,
  TRouter: ?Sized,
  TAuthenticationHandler: ?Sized,
  FConstructRecord: ?Sized,
> {
  service_registry: Arc<TServiceRegistry>,
  tunnel_registry: Arc<TTunnelRegistry>,
  router: Arc<TRouter>,
  // request_handler: Arc<RequestClientHandler<TTunnel, TTunnelRegistry, TServiceRegistry, TRouter>>,
  authentication_handler: Arc<TAuthenticationHandler>,
  tunnel_id_generator: Arc<dyn TunnelIDGenerator + Send + Sync + 'static>,
  record_constructor: Arc<FConstructRecord>,
  peers: PeerTracker,

  // event hooks
  pub tunnel_connected: Arc<Broadcaster<TunnelConnectedEvent>>,
  pub tunnel_authenticated: Arc<Broadcaster<TunnelAuthenticatedEvent>>,
  pub tunnel_disconnected: Arc<Broadcaster<TunnelDisconnectedEvent>>,
}

#[derive(thiserror::Error, Debug)]
enum TunnelLifecycleError<ApplicationError, AuthHandlingError, RegistryError> {
  #[error("Tunnel registration error")]
  RegistrationError(
    #[source]
    #[cfg_attr(feature = "backtrace", backtrace)]
    RegistryError,
  ),
  #[error("Request Processing Error: {0}")]
  RequestProcessingError(
    #[source]
    #[cfg_attr(feature = "backtrace", backtrace)]
    RequestProcessingError<ApplicationError>,
  ),
  #[error("Authentication refused to remote by either breach of protocol or invalid/inadequate credentials")]
  AuthenticationRefused,
  #[error("Authentication Handling Error: {0}")]
  AuthenticationHandlingError(
    #[source]
    #[cfg_attr(feature = "backtrace", backtrace)]
    AuthenticationHandlingError<AuthHandlingError>,
  ),
  #[error("Application error encountered in tunnel lifecycle: {0:?}")]
  ApplicationError(
    #[source]
    #[cfg_attr(feature = "backtrace", backtrace)]
    ApplicationError,
  ),
}

#[derive(thiserror::Error, Debug)]
enum RequestProcessingError<ApplicationError> {
  #[error("Protocol version mismatch")]
  UnsupportedProtocolVersion,
  #[error("Tunnel error encountered: {0}")]
  TunnelError(
    #[source]
    #[cfg_attr(feature = "backtrace", backtrace)]
    TunnelError,
  ),
  #[error("Fatal application error")]
  ApplicationError(
    #[source]
    #[cfg_attr(feature = "backtrace", backtrace)]
    ApplicationError,
  ),
}

pub struct RecordConstructorArgs {
  pub id: TunnelId,
  pub name: TunnelName,
  pub attributes: AuthenticationAttributes,
  pub tunnel: ArcTunnel<'static>,
}

pub type RecordConstructorResult<Record, Error> =
  BoxFuture<'static, Result<(Record, Arc<AuthenticationAttributes>), Error>>;

pub trait RecordConstructor<Record, Error> = Fn(
    RecordConstructorArgs,
  ) -> BoxFuture<'static, Result<(Record, Arc<AuthenticationAttributes>), Error>>
  + Send
  + Sync
  + 'static;

impl<
    ApplicationError: std::fmt::Debug + std::fmt::Display,
    AuthHandlingError: std::fmt::Debug + std::fmt::Display,
    RegistryError: std::fmt::Debug + std::fmt::Display,
  > From<RequestProcessingError<ApplicationError>>
  for TunnelLifecycleError<ApplicationError, AuthHandlingError, RegistryError>
{
  fn from(e: RequestProcessingError<ApplicationError>) -> Self {
    match e {
      RequestProcessingError::ApplicationError(fatal_error) => {
        TunnelLifecycleError::ApplicationError(fatal_error)
      }
      non_fatal => TunnelLifecycleError::RequestProcessingError(non_fatal),
    }
  }
}

// Implementations with no dependencies on content
impl<
    TTunnelRegistry: ?Sized,
    TServiceRegistry: ?Sized,
    TRouter: ?Sized,
    TAuthenticationHandler: ?Sized,
    FConstructRecord: ?Sized,
  >
  ModularDaemon<
    TTunnelRegistry,
    TServiceRegistry,
    TRouter,
    TAuthenticationHandler,
    FConstructRecord,
  >
{
  pub fn router<'a>(&'a self) -> &Arc<TRouter> {
    &self.router
  }
}

impl<
    TTunnelRegistry: ?Sized,
    TServiceRegistry: ?Sized,
    TRouter: ?Sized,
    TAuthenticationHandler: ?Sized,
    FConstructRecord: ?Sized,
  >
  ModularDaemon<
    TTunnelRegistry,
    TServiceRegistry,
    TRouter,
    TAuthenticationHandler,
    FConstructRecord,
  >
where
  Self: 'static,
  TTunnelRegistry: TunnelRegistry + Send + Sync + 'static,
  TTunnelRegistry::Record: Send + Sync + 'static,
  TTunnelRegistry::Error: Debug + Display + Send + 'static,
  TServiceRegistry: ServiceRegistry + Send + Sync + 'static,
  TRouter: Router + Send + Sync + 'static,
  TAuthenticationHandler: AuthenticationHandler + 'static,
  TAuthenticationHandler::Error: Debug + Display + Send + 'static,
  FConstructRecord: RecordConstructor<TTunnelRegistry::Record, TTunnelRegistry::Error>,
{
  pub fn new(
    service_registry: Arc<TServiceRegistry>,
    tunnel_registry: Arc<TTunnelRegistry>,
    peer_tracker: PeerTracker,
    router: Arc<TRouter>,
    authentication_handler: Arc<TAuthenticationHandler>,
    tunnel_id_generator: Arc<dyn TunnelIDGenerator + Send + Sync + 'static>,
    record_constructor: Arc<FConstructRecord>,
  ) -> Self {
    let s = Self {
      service_registry,
      tunnel_registry,
      router,
      authentication_handler,
      tunnel_id_generator,
      record_constructor,
      peers: peer_tracker,

      // For event handlers, we simply drop the receive sides,
      // as new ones can be made with Sender::subscribe(&self)
      tunnel_connected: Arc::new(event_channel(32).0),
      tunnel_authenticated: Arc::new(event_channel(32).0),
      tunnel_disconnected: Arc::new(event_channel(32).0),
    };
    s
  }

  pub fn peers(&self) -> PeersView {
    PeersView {
      by_name: Arc::downgrade(&self.peers.by_name),
      by_id: Arc::downgrade(&self.peers.by_id),
    }
  }

  /// Convert a source of tunnel progenitors into tunnels by assigning IDs from the daemon's ID generator
  pub fn assign_tunnel_ids<TTunnel, TunnelSource, TIntoTunnel>(
    &self,
    tunnel_source: TunnelSource,
  ) -> impl Stream<Item = TTunnel> + Send + 'static
  where
    TTunnel: Tunnel + 'static,
    TunnelSource: Stream<Item = TIntoTunnel> + Send + 'static,
    TIntoTunnel: AssignTunnelId<TTunnel> + 'static,
  {
    let tunnel_id_generator = self.tunnel_id_generator.clone();
    tunnel_source.map(move |pretunnel| pretunnel.assign_tunnel_id(tunnel_id_generator.next()))
  }

  /// Run the server against a tunnel_source.
  ///
  /// This can be performed concurrently against multiple sources, with a shared server instance.
  /// The implementation assumes that shutdown_request_listener will also halt the tunnel_source.
  pub fn run<TTunnel, TunnelSource>(
    self: Arc<Self>,
    tunnels: TunnelSource,
    shutdown_request_listener: CancellationListener,
  ) -> tokio::task::JoinHandle<()>
  where
    TTunnel: Tunnel + TunnelControl + TunnelMonitoring + 'static,
    TunnelSource: Stream<Item = TTunnel> + Send + 'static,
  {
    // Stop accepting new Tunnels when asked to shutdown
    let tunnels = tunnels.take_until({
      let shutdown_request_listener = shutdown_request_listener.clone();
      async move { shutdown_request_listener.cancelled().await }
    });

    // Tunnel Lifecycle - Sub-pipeline performed by futures on a per-tunnel basis
    let lifecycle = tunnels.for_each_concurrent(None, move |tunnel: TTunnel| {
      let this = self.clone();
      let shutdown_request_listener = shutdown_request_listener.clone();
      async move {
        let tunnel_id = *tunnel.id();
        let tunnel: Arc<TTunnel> = Arc::new(tunnel);
        let close_handle: Weak<TTunnel> = Arc::downgrade(&tunnel);
        match this
          .clone()
          .tunnel_lifecycle(tunnel, shutdown_request_listener)
          .await
        {
          Err(TunnelLifecycleError::AuthenticationRefused) => {
            tracing::info!(id=?tunnel_id, "Tunnel lifetime aborted due to authentication refusal");
            if let Some(t) = close_handle.upgrade() {
              // TODO: Determine if remote or local is responsible for the refusal
              tokio::task::spawn(async move {
                t.close(tunnel::TunnelCloseReason::AuthenticationFailure {
                  remote_responsible: None,
                })
                .await
              });
            }
          }
          Err(e) => {
            tracing::info!(id=?tunnel_id, error=?e, "Tunnel lifetime aborted with error {}", e);
            if let Some(t) = close_handle.upgrade() {
              let error_message = e.to_string();
              tokio::task::spawn(async move {
                t.close(tunnel::TunnelCloseReason::ApplicationErrorMessage(
                  Arc::new(error_message) as Arc<_>,
                ))
                .await
              });
            }
          }
          Ok(()) => {
            if let Some(t) = close_handle.upgrade() {
              tokio::task::spawn(async move {
                t.close(tunnel::TunnelCloseReason::GracefulExit {
                  remote_initiated: false,
                })
                .await
              });
            }
          }
        }
      }
    });

    // Spawn an instrumented task for the server which will return
    // when all connections shut down and the tunnel source closes
    tokio::task::spawn(lifecycle.instrument(tracing::span!(tracing::Level::INFO, "modular_server")))
  }

  fn authenticate_tunnel<'a, ApplicationError, TTunnel: Tunnel + Clone + 'static>(
    self: &Arc<Self>,
    tunnel: TTunnel,
    shutdown: CancellationListener,
  ) -> impl Future<
    Output = Result<
      (tunnel::TunnelName, AuthenticationAttributes),
      TunnelLifecycleError<ApplicationError, TAuthenticationHandler::Error, TTunnelRegistry::Error>,
    >,
  > + 'static {
    let authentication_handler = Arc::clone(&self.authentication_handler);
    let tunnel = tunnel.clone();
    async move {
      let result: Result<(_, _), AuthenticationError<_>> = tokio::task::spawn(async move {
        perform_authentication(authentication_handler.as_ref(), &tunnel, &shutdown.into()).await
      })
      .unwrap_or_else(|e| {
        Err(AuthenticationError::Handling(
          AuthenticationHandlingError::JoinError(e),
        ))
      })
      .await;
      match result {
        Err(AuthenticationError::Handling(handling_error)) => {
          // Non-fatal handling errors are passed to tracing and close the tunnel
          // TODO: Feed this upward as a tunnel lifecycle failure
          tracing::warn!(
            reason = ?&handling_error,
            "Tunnel closed due to authentication handling failure"
          );
          Err(TunnelLifecycleError::AuthenticationHandlingError(
            handling_error.err_into(),
          ))
        }
        Err(AuthenticationError::Remote(remote_error)) => {
          tracing::debug!(
            reason = (&remote_error as &dyn std::error::Error),
            "Tunnel closed due to remote authentication failure"
          );
          Err(TunnelLifecycleError::AuthenticationRefused)
        }
        Ok(tunnel) => Ok(tunnel),
      }
    }
  }

  // Sends tunnel_connected event when a tunnel begins being processed by the daemon pipeline
  fn fire_tunnel_connected(&self, ev: TunnelConnectedEvent) {
    // Send; Ignore errors produced when no receivers exist to read the event
    let _ = self.tunnel_connected.send(ev);
  }

  // Sends tunnel_authenticated event when a tunnel has received its name and has been successfully registered
  fn fire_tunnel_authenticated(&self, ev: TunnelAuthenticatedEvent) {
    // Send; Ignore errors produced when no receivers exist to read the event
    let _ = self.tunnel_authenticated.send(ev);
  }

  #[tracing::instrument(err, skip(self, tunnel, shutdown), fields(id=?tunnel.id()))]
  async fn tunnel_lifecycle<TTunnel>(
    self: Arc<Self>,
    tunnel: Arc<TTunnel>,
    shutdown: CancellationListener,
  ) -> Result<
    (),
    TunnelLifecycleError<anyhow::Error, TAuthenticationHandler::Error, TTunnelRegistry::Error>,
  >
  where
    TTunnel: Tunnel + TunnelControl + 'static,
  {
    let tunnel = WrappedTunnel::new_registration_failure_closing(tunnel);
    // Send tunnel_connected event once the tunnel is successfully registered to its ID
    self.fire_tunnel_connected(TunnelConnectedEvent {
      tunnel: tunnel.tunnel.clone() as Arc<_>,
    });

    // Authenticate connections - Each connection will be piped into the authenticator,
    // which has the option of declining the connection, and may save additional metadata.
    let (tunnel_name, tunnel_attrs) = {
      let res = self
        .authenticate_tunnel(tunnel.clone(), shutdown.clone())
        .instrument(tracing::debug_span!("authentication"))
        .await;
      res
    }?;

    // Tunnel naming - The tunnel registry is notified of the authenticator-provided tunnel name
    let tunnel: WrappedTunnel<TTunnel> = {
      self
        .register_tunnel(
          tunnel,
          tunnel_name.clone(),
          self.tunnel_registry.clone(),
          tunnel_attrs,
          self.record_constructor.clone(),
        )
        .instrument(tracing::debug_span!("naming"))
    }
    .await
    .map_err(TunnelLifecycleError::RegistrationError)?;

    // Phases resume in registered_tunnel_lifecycle.
    self
      .clone()
      .registered_tunnel_lifecycle(tunnel, tunnel_name, shutdown)
      .await?;
    Ok(())
  }

  #[tracing::instrument(err, skip(self, tunnel, shutdown), fields(name=?tunnel_name, id=?tunnel.id()))]
  async fn registered_tunnel_lifecycle<TTunnel>(
    self: Arc<Self>,
    tunnel: WrappedTunnel<TTunnel>,
    tunnel_name: TunnelName,
    shutdown: CancellationListener,
  ) -> Result<
    (),
    TunnelLifecycleError<anyhow::Error, TAuthenticationHandler::Error, TTunnelRegistry::Error>,
  >
  where
    TTunnel: Tunnel + 'static,
  {
    // Process incoming requests until the incoming channel is closed.
    {
      let service_registry = Arc::clone(&self.service_registry);
      let incoming =
        tunnel
          .downlink()
          .await
          .ok_or(TunnelLifecycleError::RequestProcessingError(
            RequestProcessingError::TunnelError(TunnelError::ConnectionClosed),
          ))?;
      Self::handle_incoming_requests(tunnel, incoming, service_registry, shutdown)
        .instrument(tracing::debug_span!("request_handling"))
    }
    .await?;

    // The tunnel is dropped by this point, and will be automatically deregistered on a background task
    Ok(())
  }

  // Process incoming requests until the incoming channel is closed.
  // Await a tunnel closure request from the host, or for the tunnel to close on its own.
  // A tunnel has "closed on its own" if incoming closes *or* outgoing requests fail with
  // a notification that the outgoing channel has been closed.
  //
  // The request handler for this side should be configured to send a close request for
  // the tunnel with the given ID when it sees a request fail due to tunnel closure.
  // TODO: configure request handler (?) to do that using a std::sync::Weak<ModularDaemon>.
  async fn handle_incoming_requests<TTunnel, TTunnelDownlink>(
    tunnel: TTunnel,
    mut incoming: TTunnelDownlink,
    service_registry: Arc<TServiceRegistry>,
    shutdown: CancellationListener,
  ) -> Result<(), RequestProcessingError<anyhow::Error>>
  where
    TTunnel: Tunnel + Clone + 'static,
    TTunnelDownlink: TunnelDownlink + Send + Unpin + 'static,
  {
    let negotiator = Arc::new(NegotiationService::new(service_registry));

    incoming
      .as_stream()
      // Stop accepting new requests after a graceful shutdown is requested
      .take_until(shutdown.clone().cancelled())
      .map_err(|e: TunnelError| RequestProcessingError::TunnelError(e))
      .scan((negotiator, shutdown), |(negotiator, shutdown), link| {
        let res = link.map(|content| (Arc::clone(&*negotiator), shutdown.clone(), content));
        future::ready(Some(res))
      })
      .try_for_each_concurrent(None, move |(negotiator, shutdown, link)| {
        Self::handle_incoming_request(tunnel.clone(), link, negotiator, shutdown)
      })
      .await?;

    Ok(())
  }

  async fn handle_incoming_request<TTunnel, Services>(
    tunnel: TTunnel,
    link: TunnelIncomingType,
    negotiator: Arc<NegotiationService<Services>>,
    shutdown: CancellationListener,
  ) -> Result<(), RequestProcessingError<anyhow::Error>>
  where
    TTunnel: Tunnel + Clone + 'static,
    Services: ServiceRegistry + Send + Sync + ?Sized + 'static,
  {
    match link {
      tunnel::TunnelIncomingType::BiStream(link) => {
        Self::handle_incoming_request_bistream(tunnel, link, negotiator, shutdown).await
      }
    }
  }

  async fn handle_incoming_request_bistream<TTunnel, Services>(
    tunnel: TTunnel,
    link: WrappedStream,
    negotiator: Arc<NegotiationService<Services>>,
    shutdown: CancellationListener, // TODO: Respond to shutdown listener requests
  ) -> Result<(), RequestProcessingError<anyhow::Error>>
  where
    TTunnel: Tunnel + Clone + 'static,
    Services: ServiceRegistry + Send + Sync + ?Sized + 'static,
  {
    match negotiator.negotiate(link, tunnel.clone()).await {
      // Tunnels established on an invalid negotiation protocol are useless; consider this fatal
      Err(NegotiationError::UnsupportedProtocolVersion) => {
        Err(RequestProcessingError::UnsupportedProtocolVersion)
      }
      // Protocol violations are not considered fatal, as they do not affect other links
      // They do still destroy the current link, however.
      Err(NegotiationError::ProtocolViolation) => Ok(()),
      Err(NegotiationError::ReadError) => Ok(()),
      Err(NegotiationError::WriteError) => Ok(()),
      // Generic refusal for when a service doesn't accept a route for whatever reason
      Err(NegotiationError::Refused) => {
        tracing::debug!("Refused remote protocol request");
        Ok(())
      }
      // Lack of support for a service is just a more specific refusal
      Err(NegotiationError::UnsupportedServiceVersion) => {
        tracing::debug!("Refused request due to unsupported service version");
        Ok(())
      }
      Err(NegotiationError::ApplicationError(e)) => {
        tracing::warn!(err=?e, "Refused request due to application error in negotiation");
        Ok(())
      }
      Err(NegotiationError::FatalError(e)) => {
        tracing::error!(err=?e, "Refused request due to fatal application error in negotiation");
        Err(RequestProcessingError::ApplicationError(
          NegotiationError::FatalError(e).into(),
        ))
      }
      Ok((link, route_addr, service)) => {
        if shutdown.is_cancelled() {
          // Drop services post-negotiation if the connection is awaiting
          // shutdown, instead of handing them to the service to be performed.
          return Ok(());
        }
        let route_addr: RouteAddress = route_addr;
        let service: negotiation::ArcService<_> = service;
        match service
          .handle(route_addr.clone(), Box::new(link), Arc::new(tunnel) as _)
          .await
        {
          // TODO: Figure out which of these should be considered fatal to the tunnel, if any
          Err(e) => {
            tracing::debug!(
              address = ?route_addr,
              error = ?e,
              "Protocol Service responded with non-fatal error"
            );
            Ok(())
          }
          Ok(()) => {
            tracing::trace!(
              address = ?route_addr,
              "Protocol Service reported success"
            );
            Ok(())
          }
        }
      }
    }
  }

  async fn register_tunnel<TTunnel>(
    &self,
    tunnel: WrappedTunnel<TTunnel>,
    tunnel_name: TunnelName,
    tunnel_registry: Arc<TTunnelRegistry>,
    attributes: AuthenticationAttributes,
    record_constructor: Arc<FConstructRecord>,
  ) -> Result<WrappedTunnel<TTunnel>, TTunnelRegistry::Error>
  where
    TTunnel: Tunnel + TunnelControl + 'static,
  {
    let registered_at = (Instant::now(), SystemTime::now());
    let (record, attributes) = record_constructor(RecordConstructorArgs {
      id: tunnel.id().clone(),
      name: tunnel_name.clone(),
      attributes: attributes,
      tunnel: tunnel.as_inner().clone() as Arc<_>,
    })
    .await?;
    let identifier = tunnel_registry
      .register(tunnel_name.clone(), &record)
      .await?;

    let tunnel_id = *tunnel.id();
    let peer_record = Arc::new(PeerRecord {
      id: tunnel_id,
      name: tunnel_name.clone(),
      registered_at,
      attributes: Arc::clone(&attributes),
      tunnel: tunnel.as_inner().clone() as Arc<_>,
    });
    self.peers.insert(&peer_record);

    // Inform the tunnel of its new registration status, once the registry is aware of it
    if TunnelControl::report_authentication_success(&tunnel, tunnel_name.clone())
      .await
      .is_ok()
    {
      // Send Daemon-level tunnel_authenticated event for the newly-named tunnel,
      // but only if the tunnel was not reported as closed during the authentication event firing.
      self.fire_tunnel_authenticated(TunnelAuthenticatedEvent {
        tunnel: tunnel.as_inner().clone() as Arc<_>,
        name: tunnel_name,
        attributes: attributes,
      });
    }

    Ok(WrappedTunnel::new_deregistering(
      tunnel.extract_inner().clone(),
      tunnel_registry,
      identifier,
      self.peers(),
      peer_record,
      self.tunnel_disconnected.clone(),
    ))
  }
}