wiring 0.1.4

An async binary serialization framework with channels support
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
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
use std::{any::TypeId, fmt::Debug, pin::Pin, task::Poll};

use futures::{FutureExt, StreamExt};
use pin_project::pin_project;
use tokio::{
    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
    net::{tcp::OwnedWriteHalf, TcpStream},
    sync::{
        mpsc::{UnboundedReceiver, UnboundedSender},
        oneshot,
    },
};
use url::Url;

use super::{
    listener::{ConnectInfo, Local, Peer, WireListenerEvent},
    unwire::{Unwire, Unwiring},
    wired::{HandleEvent, WiredHandle, WiredServer},
    ConnectConfig, IoSplit, SplitStream,
};

type WireId = u64;

#[derive(Debug, Clone)]
pub struct WireInfo {
    wire_id: WireId,
    access_key: u128,
    connect_info: ConnectInfo,
}

impl WireInfo {
    pub(crate) fn new(wire_id: WireId, access_key: u128, connect_info: ConnectInfo) -> Self {
        Self {
            wire_id,
            access_key,
            connect_info,
        }
    }
    pub fn wire_id(&self) -> WireId {
        self.wire_id
    }
    pub fn access_key(&self) -> u128 {
        self.access_key
    }
}

impl Unwiring for WireInfo {
    fn unwiring<W: Unwire>(wire: &mut W) -> impl std::future::Future<Output = Result<Self, std::io::Error>> + Send {
        async move {
            Ok(Self {
                wire_id: wire.unwiring().await?,
                access_key: wire.unwiring().await?,
                connect_info: wire.unwiring().await?,
            })
        }
    }
}

pub trait Wire: AsyncWrite + Unpin + Send + 'static + Sync + Sized {
    type Stream: SplitStream;
    fn stream(&mut self) -> impl std::future::Future<Output = Result<Self::Stream, std::io::Error>> + Send;
    fn wire<T: Wiring>(&mut self, t: T) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move {
            t.wiring(self).await?;
            self.flush().await?;
            Ok(())
        }
    }
    fn wiring<T: Wiring>(&mut self, item: T) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        item.wiring(self)
    }
}

impl<T: AsyncWrite + Send + AsyncRead + 'static + Sync + Unpin + Debug> Wire for tokio::io::WriteHalf<T> {
    type Stream = IoSplit<T>;
    fn stream(&mut self) -> impl std::future::Future<Output = Result<Self::Stream, std::io::Error>> + Send {
        async {
            Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "Cannot to establish stream from WriteHalf",
            ))
        }
    }
}

impl Wire for OwnedWriteHalf {
    type Stream = TcpStream;

    fn stream(&mut self) -> impl std::future::Future<Output = Result<TcpStream, std::io::Error>> + Send {
        async {
            Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "TcpStream from OwnedWriteHalf is not supported",
            ))
        }
    }
}

impl Wire for TcpStream {
    type Stream = Self;

    fn stream(&mut self) -> impl std::future::Future<Output = Result<TcpStream, std::io::Error>> + Send {
        async {
            Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "TcpStream from stream is not supported",
            ))
        }
    }
}

#[derive(Debug)]
struct ConsumeWire<T>(Option<T>);

impl<T: SplitStream> Unwire for ConsumeWire<T> {
    type Stream = T;
    fn stream(&mut self) -> impl std::future::Future<Output = Result<Self::Stream, std::io::Error>> + Send {
        async move {
            if let Some(wire) = Option::take(&mut self.0) {
                return Ok(wire);
            }
            Err(std::io::Error::new(
                std::io::ErrorKind::BrokenPipe,
                "Unable to consume a wire",
            ))
        }
    }
}

impl<T: AsyncRead + Unpin> AsyncRead for ConsumeWire<T> {
    fn poll_read(
        self: Pin<&mut Self>,
        _: &mut std::task::Context<'_>,
        _: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        Poll::Ready(Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "Unable to poll_read from a consumed wire",
        )))
    }
}

impl<T: AsyncWrite + Send + Sync + Unpin + 'static, C: ConnectConfig> Wire for WireStream<T, C>
where
    C::Stream: SplitStream,
{
    type Stream = WireStream<C::Stream, C>;

    fn stream(&mut self) -> impl std::future::Future<Output = Result<Self::Stream, std::io::Error>> + Send {
        async {
            // establish connection with server.
            let peer = self.peer.as_ref().ok_or(std::io::Error::new(
                std::io::ErrorKind::AddrNotAvailable,
                "Wire doesn't have peer connect info",
            ))?;
            let connect_info = &peer.wire_info.connect_info;

            let stream: <C as ConnectConfig>::RawStream = peer.connect_config.connect_stream(connect_info).await?;
            let stream = peer.connect_config.enhance_stream(stream)?;
            if let Some(local_handle) = &peer.local_handle {
                // bi connect
                let (reply, rx) = oneshot::channel();
                local_handle
                    .send(WireListenerEvent::OutgoingWire {
                        stream,
                        forward_info: Some((peer.wire_info.wire_id(), peer.wire_info.access_key())),
                        reply,
                    })
                    .ok();
                let mut wire = rx
                    .await
                    .map_err(|e| std::io::Error::new(std::io::ErrorKind::Interrupted, e))??;
                // unwire the first message from server.
                let remote_info: WireInfo = wire.unwire().await?;
                let remote_wire_id = remote_info.wire_id();
                wire = wire.with_peer(Peer::<C>::new(
                    remote_info,
                    Some(local_handle.clone()),
                    peer.connect_config.clone(),
                ));
                self.wiring(remote_wire_id).await?;
                Ok(wire)
            } else {
                let mut wire = WireStream::new(stream);
                // connect one way, we wire none, which is 0u8
                0u8.wiring(&mut wire).await?;
                // wire the forward info
                let forward_info = Some((peer.wire_info.wire_id(), peer.wire_info.access_key()));
                wire.wire(forward_info).await?;
                // create the wirestream without local
                // must decode
                let remote_info: WireInfo = wire.unwire().await?;
                let remote_wire_id = remote_info.wire_id();
                wire = wire.with_peer(Peer::new(remote_info, None, peer.connect_config.clone()));
                self.wiring(remote_wire_id).await?;
                Ok(wire)
            }
        }
    }
}

impl<T: AsyncRead, C: ConnectConfig> AsyncRead for WireStream<T, C> {
    fn poll_read(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        self.project().stream.poll_read(cx, buf)
    }
}

impl<T: AsyncWrite, C: ConnectConfig> AsyncWrite for WireStream<T, C> {
    fn is_write_vectored(&self) -> bool {
        self.stream.is_write_vectored()
    }
    fn poll_flush(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), std::io::Error>> {
        self.project().stream.poll_flush(cx)
    }
    fn poll_shutdown(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), std::io::Error>> {
        self.project().stream.poll_shutdown(cx)
    }
    fn poll_write(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &[u8],
    ) -> std::task::Poll<Result<usize, std::io::Error>> {
        self.project().stream.poll_write(cx, buf)
    }
    fn poll_write_vectored(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        bufs: &[std::io::IoSlice<'_>],
    ) -> std::task::Poll<Result<usize, std::io::Error>> {
        self.project().stream.poll_write_vectored(cx, bufs)
    }
}

pub trait HandleWire<C: ConnectConfig> {
    type Error: std::error::Error;
    /// Handle the incoming wire from the client.
    fn handle_wire(&mut self, stream: WireStream<C::Stream, C>) -> Result<(), Self::Error>;
}

impl<C: ConnectConfig> HandleWire<C> for UnboundedSender<WireStream<C::Stream, C>> {
    type Error = tokio::sync::mpsc::error::SendError<WireStream<C::Stream, C>>;
    fn handle_wire(
        &mut self,
        stream: WireStream<C::Stream, C>,
    ) -> Result<(), tokio::sync::mpsc::error::SendError<WireStream<C::Stream, C>>> {
        self.send(stream)
    }
}

#[pin_project]
#[derive(Debug)]
pub struct WireStream<T, C: ConnectConfig> {
    /// NOTE: this local should be under feature as well. only needed
    /// It contains the local wire info, including the handle to register more wires.
    /// And inbox to receive incoming wires from remote.
    pub(crate) local: Option<Local<C>>,
    /// The peer/remote info, used to establish further wires
    pub(crate) peer: Option<Peer<C>>,
    #[pin]
    /// The stream which hold connection to remote end
    pub(crate) stream: T,
}

impl<T, C: ConnectConfig> WireStream<T, C> {
    pub fn new(stream: T) -> Self {
        Self {
            local: None,
            peer: None,
            stream,
        }
    }
    pub(crate) fn with_local(mut self, local: Local<C>) -> Self {
        self.local.replace(local);
        self
    }
    pub(crate) fn with_peer(mut self, peer: Peer<C>) -> Self {
        self.peer.replace(peer);
        self
    }
    /// Convert the wire into a bi-channel or handle or receive
    pub async fn into<R: Unwiring>(self) -> Result<R, std::io::Error>
    where
        C: ConnectConfig<Stream = T>,
        Self: SplitStream,
    {
        // Convert the wire into a consumed wire, to enable stream fn taking ownership of the stream instead of unwiring
        // incoming wire.
        let mut consume = ConsumeWire(Some(self));
        consume.unwire::<R>().await
    }
    /// Convert the wire stream to bi wired
    pub fn wired<LocalEvent, RemoteEvent, H: HandleEvent<RemoteEvent>>(
        self,
        handle_event: H,
    ) -> Result<WiredHandle<LocalEvent>, std::io::Error>
    where
        LocalEvent: Wiring + Debug + 'static,
        RemoteEvent: Unwiring + Debug + 'static,
        Self: SplitStream,
    {
        let h = WiredServer::new(self, handle_event)?.run();
        Ok(h)
    }
}

pub struct WireChannel<Sender, Receiver> {
    pub sender: Sender,
    pub receiver: Receiver,
}

#[allow(dead_code)]
impl<S, R> WireChannel<S, R> {
    fn new(sender: S, receiver: R) -> Self {
        Self { sender, receiver }
    }
    /// Convert this into tuple
    pub fn into_inner(self) -> (S, R) {
        (self.sender, self.receiver)
    }
}

impl<S: Wiring + 'static, R: Unwiring + 'static> Unwiring
    for WireChannel<tokio::sync::mpsc::Sender<S>, tokio::sync::mpsc::Receiver<R>>
{
    fn unwiring<W: Unwire>(wire: &mut W) -> impl std::future::Future<Output = Result<Self, std::io::Error>> + Send {
        async move {
            let buffer = wire.bounded_buffer();
            let wire = wire.stream().await?;
            let (mut r, mut w) = wire.split()?;

            // create the sender channel side.
            let (sender, mut rx) = tokio::sync::mpsc::channel::<S>(buffer.into());

            let sender_task = async move {
                while let Some(item) = rx.recv().await {
                    if let Err(_) = w.wire(item).await {
                        rx.close();
                        break;
                    }
                }
                w.shutdown().await.ok();
            };
            let s_j = tokio::spawn(sender_task.boxed());
            // create receiver channel
            let (tx, receiver) = tokio::sync::mpsc::channel::<R>(buffer.into());
            let recv_task = async move {
                loop {
                    tokio::select! {
                        _ = tx.closed() => {
                            break;
                        },
                        item = r.unwire::<R>() => {
                            if let Ok(item) = item {
                                tx.send(item).await.ok();
                            } else {
                                break;
                            }

                        },
                    }
                }
                s_j.abort();
            };
            tokio::spawn(recv_task.boxed());
            Ok(Self::new(sender, receiver))
        }
    }
}

impl<S: Wiring + 'static, R: Unwiring + 'static> Unwiring for WireChannel<UnboundedSender<S>, UnboundedReceiver<R>> {
    fn unwiring<W: Unwire>(wire: &mut W) -> impl std::future::Future<Output = Result<Self, std::io::Error>> + Send {
        async move {
            let wire = wire.stream().await?;
            let (mut r, mut w) = wire.split()?;

            // create the sender channel side.
            let (sender, mut rx) = tokio::sync::mpsc::unbounded_channel::<S>();

            let sender_task = async move {
                while let Some(item) = rx.recv().await {
                    if let Err(_) = w.wire(item).await {
                        rx.close();
                        break;
                    }
                }
                w.shutdown().await.ok();
            };
            let s_j = tokio::spawn(sender_task.boxed());
            // create receiver channel
            let (tx, receiver) = tokio::sync::mpsc::unbounded_channel::<R>();
            let recv_task = async move {
                loop {
                    tokio::select! {
                        _ = tx.closed() => {
                            break;
                        },
                        item = r.unwire::<R>() => {
                            if let Ok(item) = item {
                                tx.send(item).ok();
                            } else {
                                break;
                            }

                        },
                    }
                }
                s_j.abort();
            };
            tokio::spawn(recv_task.boxed());
            Ok(Self::new(sender, receiver))
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct NoHandle;

#[derive(Debug, Clone, Copy)]
pub struct WireConfig<C: ConnectConfig, H = NoHandle> {
    config: C,
    handle: H,
}

#[allow(dead_code)]
impl<C: ConnectConfig> WireConfig<C> {
    /// Create wireconfig with provided connect config
    pub fn new(config: C) -> Self {
        Self {
            config,
            handle: NoHandle,
        }
    }
    /// Create wire config with handle, for internal use
    pub(crate) fn with_handle(
        config: C,
        handle: tokio::sync::mpsc::UnboundedSender<WireListenerEvent<C>>,
    ) -> WireConfig<C, tokio::sync::mpsc::UnboundedSender<WireListenerEvent<C>>> {
        WireConfig::<C, _> { config, handle }
    }
    /// Connect to remote in client mode
    pub async fn connect(&self, connect_info: &ConnectInfo) -> Result<WireStream<C::Stream, C>, std::io::Error> {
        let stream = self.config.connect_stream(&connect_info).await?;
        let stream = self.config.enhance_stream(stream)?;

        let mut wire = WireStream::new(stream);
        // wire none and none for both wire_info and forward info, as we're not forwarding this.
        wire.wire(0u16).await?;
        // unwire the pushed remote_wire_info.
        let wire_info = wire.unwire().await?;
        let peer = Peer::new(wire_info, None, self.config.clone());
        // set the peer info
        Ok(wire.with_peer(peer))
    }
}

#[allow(dead_code)]
impl<C: ConnectConfig> WireConfig<C, tokio::sync::mpsc::UnboundedSender<WireListenerEvent<C>>> {
    /// Push the stream and RETURN (if set and not nested forward), else it's handled at listener level with handle_wire
    pub async fn wire<const RETURN: bool>(
        &self,
        stream: C::RawStream,
    ) -> Result<Option<WireStream<C::Stream, C>>, std::io::Error> {
        let mut stream = self.config.enhance_stream(stream)?;

        let remote_info = stream.unwire().await?;
        let forward_info = stream.unwire().await?;
        // stream = temp_wire.stream;
        if RETURN {
            let (reply, rx) = oneshot::channel();
            let message = WireListenerEvent::Incomingwire {
                stream,
                remote_info,
                forward_info,
                reply: Some(reply),
            };
            self.handle
                .send(message)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::NotConnected, e))?;
            let w = rx
                .await
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Interrupted, e))?;
            w
        } else {
            let message = WireListenerEvent::Incomingwire {
                stream,
                remote_info,
                forward_info,
                reply: None,
            };
            self.handle
                .send(message)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::NotConnected, e))?;
            Ok(None)
        }
    }
    /// Shutdown the listener
    pub fn shutdown(&self) {
        self.handle.send(WireListenerEvent::<C>::Shutdown).ok();
    }
    /// Connect to remote with enabled bi-directional communication
    pub async fn connect(&self, connect_info: &ConnectInfo) -> Result<WireStream<C::Stream, C>, std::io::Error> {
        let raw_stream = self.config.connect_stream(&connect_info).await?;
        let stream = self.config.enhance_stream(raw_stream)?;
        let (reply, rx) = oneshot::channel();

        let event = WireListenerEvent::OutgoingWire {
            stream,
            forward_info: None,
            reply,
        };
        self.handle
            .send(event)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e))?;
        let mut w = rx
            .await
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e))??;
        let peer_info = w.unwire().await?;
        // the first
        Ok(w.with_peer(Peer::new(peer_info, Some(self.handle.clone()), self.config.clone())))
    }
}

pub trait Wiring: Send + Sync {
    const SAFE: bool = true;
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send;
}

impl Wiring for WireInfo {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move {
            self.wire_id.wiring(wire).await?;
            self.access_key.wiring(wire).await?;
            self.connect_info.wiring(wire).await
        }
    }
}

impl<'a> Wiring for &'a WireInfo {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move {
            self.wire_id.wiring(wire).await?;
            self.access_key.wiring(wire).await?;
            (&self.connect_info).wiring(wire).await
        }
    }
}

impl Wiring for String {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move { self.as_bytes().wiring(wire).await }
    }
}

impl<'a> Wiring for &'a String {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move { self.as_bytes().wiring(wire).await }
    }
}

impl<'a> Wiring for &'a str {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move { self.as_bytes().wiring(wire).await }
    }
}

impl<'a> Wiring for &'a [u8] {
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move {
            let len = self.len() as u64;
            len.wiring(wire).await?;
            wire.write_all(self).await
        }
    }
}

impl<'a, const LEN: usize> Wiring for &'a [u8; LEN] {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move { wire.write_all(self).await }
    }
}

impl<const LEN: usize> Wiring for [u8; LEN] {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move { wire.write_all(&self).await }
    }
}

impl Wiring for Url {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move { self.as_str().wiring(wire).await }
    }
}

impl<'a> Wiring for &'a Url {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move { self.as_str().wiring(wire).await }
    }
}

impl<T> Wiring for tokio::sync::oneshot::Sender<T>
where
    T: Unwiring + 'static,
{
    const SAFE: bool = false;
    #[inline]
    fn wiring<W: Wire>(mut self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let mut new: W::Stream = wire.stream().await?;
            let task = async move {
                tokio::select! {
                    _ = self.closed() => {
                        // channel closed
                    },
                    item = new.unwire::<T>() => {
                        if let Ok(item) = item {
                            self.send(item).ok();
                        }
                    },
                }
            };
            tokio::spawn(task.boxed());
            Ok(())
        }
    }
}

impl<T> Wiring for UnboundedSender<T>
where
    T: Unwiring + 'static,
{
    const SAFE: bool = false;
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let new: W::Stream = wire.stream().await?;
            let closed_handle = self.clone();
            let (mut read, mut send) = new.split()?;
            let shutdown = async move {
                closed_handle.closed().await;
                send.shutdown().await.ok();
            };
            let j = tokio::spawn(shutdown.boxed());
            let task = async move {
                while let Ok(item) = read.unwire().await {
                    if let Err(_) = self.send(item) {
                        break;
                    };
                }
                j.abort();
            };
            tokio::spawn(task.boxed());
            Ok(())
        }
    }
}

impl<T: Wiring + 'static + Clone> Wiring for tokio::sync::broadcast::Receiver<T> {
    /// not safe to store
    const SAFE: bool = false;
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move {
            let w = wire.stream().await?;
            let (mut r, mut w) = w.split()?;
            let mut rx = self;
            let task = async move {
                while let Ok(item) = rx.recv().await {
                    if let Err(_) = w.wire(item).await {
                        break;
                    }
                }
            };

            let j = tokio::spawn(task.boxed());
            let detect_shutdown = async move {
                r.read_u8().await.ok();
                // if read_u8 was due to timeout we should not abort right?
                j.abort();
            };
            tokio::spawn(detect_shutdown.boxed());
            Ok(())
        }
    }
}

impl<T: Wiring + 'static + Clone> Wiring for tokio::sync::watch::Receiver<T> {
    /// not safe to store
    const SAFE: bool = false;
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move {
            let w = wire.stream().await?;
            let (mut r, mut w) = w.split()?;
            let mut rx = tokio_stream::wrappers::WatchStream::new(self);
            let task = async move {
                while let Some(item) = rx.next().await {
                    if let Err(_) = w.wire(item).await {
                        break;
                    }
                }
            };
            let j = tokio::spawn(task.boxed());
            let detect_shutdown = async move {
                r.read_u8().await.ok();
                j.abort();
            };
            tokio::spawn(detect_shutdown.boxed());
            Ok(())
        }
    }
}

impl<T: Wiring + Unwiring + 'static + Clone> Wiring for tokio::sync::watch::Sender<T> {
    /// not safe to store
    const SAFE: bool = false;
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        async move {
            let mut w = wire.stream().await?;
            // must wire initial value
            let r = self.borrow().clone();
            w.wire(r).await?;
            let task = async move {
                loop {
                    tokio::select! {
                        _ = self.closed() => {
                            w.shutdown().await.ok();
                            break;
                        },
                        item = w.unwire::<T>() => {
                            if let Ok(item ) = item {
                                if let Err(_) = self.send(item) {
                                    break;
                                }
                            } else {
                                break
                            }
                        },
                        else => break,
                    };
                }
            };
            tokio::spawn(task.boxed());

            Ok(())
        }
    }
}

impl<T> Wiring for tokio::sync::broadcast::Sender<T>
where
    T: Unwiring + 'static,
{
    const SAFE: bool = false;
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let mut new: W::Stream = wire.stream().await?;
            let task = async move {
                while let Ok(item) = new.unwire().await {
                    // note: detecting when this otherhalf is dropped is impossible, as tokio doesn't provide closed()
                    if let Err(_) = self.send(item) {
                        break;
                    };
                }
            };
            tokio::spawn(task.boxed());
            Ok(())
        }
    }
}

impl<T> Wiring for tokio::sync::mpsc::Sender<T>
where
    T: Unwiring + 'static,
{
    const SAFE: bool = false;
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let new: W::Stream = wire.stream().await?;
            let closed_handle = self.clone();
            let (mut read, mut send) = new.split()?;
            let shutdown = async move {
                closed_handle.closed().await;
                send.shutdown().await.ok();
            };
            let j = tokio::spawn(shutdown.boxed());
            let task = async move {
                while let Ok(item) = read.unwire().await {
                    if let Err(_) = self.send(item).await {
                        break;
                    };
                }
                j.abort();
            };
            tokio::spawn(task.boxed());
            Ok(())
        }
    }
}

impl<T: Wiring + 'static> Wiring for tokio::sync::oneshot::Receiver<T> {
    const SAFE: bool = false;
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let new: W::Stream = wire.stream().await?;
            let (mut r, mut w) = new.split()?;
            let task = async move {
                tokio::select! {
                    _ = r.read_u8() => {
                    },
                    item = self => {
                        if let Ok(item) = item {
                            w.wire(item).await.ok();
                        };
                    }
                    else => {
                        ()
                    },
                }
                w.shutdown().await.ok();
            };
            tokio::spawn(task.boxed());
            Ok(())
        }
    }
}

impl<T: Wiring + 'static> Wiring for UnboundedReceiver<T> {
    const SAFE: bool = false;
    fn wiring<W: Wire>(mut self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let new: W::Stream = wire.stream().await?;
            let (mut r, mut w) = new.split()?;
            let task = async move {
                while let Some(item) = self.recv().await {
                    if let Err(_) = w.wire(item).await {
                        break;
                    }
                }
            };
            let h = tokio::spawn(task.boxed());
            let detect_shutdown = async move {
                // the stream not supposed to send anything, this is just to detect when is offline.
                r.read_u8().await.ok();
                // if this is closed, it means the wire is closed as well.
                h.abort();
            };
            tokio::spawn(detect_shutdown.boxed());
            Ok(())
        }
    }
}

impl<T: Wiring + 'static> Wiring for tokio::sync::mpsc::Receiver<T> {
    const SAFE: bool = false;
    #[inline]
    fn wiring<W: Wire>(mut self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let new: W::Stream = wire.stream().await?;
            let (mut r, mut w) = new.split()?;
            let task = async move {
                while let Some(item) = self.recv().await {
                    if let Err(_) = w.wire(item).await {
                        break;
                    }
                }
            };
            let h = tokio::spawn(task.boxed());
            let detect_shutdown = async move {
                // the stream not supposed to send anything, this is just to detect when is offline.
                r.read_u8().await.ok();
                // if this is closed, it means the wire is closed as well.
                h.abort();
            };
            tokio::spawn(detect_shutdown.boxed());
            Ok(())
        }
    }
}

impl Wiring for () {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> + Send {
        // Must be wired as rust treats this as type even if it's zerosized. the reason:
        // channel can support sending (), and therefore the other end must detects when () is sent,
        // if it was no-op, then no way for unwire to detect it. think of it as heartbeat.
        wire.wiring(1u8)
    }
}

impl Wiring for bool {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u8(self as u8)
    }
}

impl<'a> Wiring for &'a bool {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u8(*self as u8)
    }
}

impl Wiring for u8 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u8(self)
    }
}

impl<'a> Wiring for &'a u8 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u8(*self)
    }
}

impl Wiring for i8 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i8(self)
    }
}

impl<'a> Wiring for &'a i8 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i8(*self)
    }
}

impl Wiring for u16 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u16(self)
    }
}

impl<'a> Wiring for &'a u16 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u16(*self)
    }
}

impl Wiring for i16 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i16(self)
    }
}

impl<'a> Wiring for &'a i16 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i16(*self)
    }
}

impl Wiring for u32 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u32(self)
    }
}

impl<'a> Wiring for &'a u32 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u32(*self)
    }
}

impl Wiring for i32 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i32(self)
    }
}

impl<'a> Wiring for &'a i32 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i32(*self)
    }
}

impl Wiring for u64 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u64(self)
    }
}

impl<'a> Wiring for &'a u64 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u64(*self)
    }
}

impl Wiring for i64 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i64(self)
    }
}

impl<'a> Wiring for &'a i64 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i64(*self)
    }
}

impl Wiring for u128 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u128(self)
    }
}

impl<'a> Wiring for &'a u128 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_u128(*self)
    }
}

impl Wiring for i128 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i128(self)
    }
}

impl<'a> Wiring for &'a i128 {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        wire.write_i128(*self)
    }
}

impl<T: Wiring + 'static> Wiring for Vec<T> {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let len = self.len() as u64;
            len.wiring(wire).await?;
            let t = TypeId::of::<T>();
            let is_u8 = TypeId::of::<u8>();
            let is_i8 = TypeId::of::<i8>();
            if t == is_u8 || t == is_i8 {
                let vec = unsafe { std::mem::transmute::<_, Vec<u8>>(self) };
                wire.write_all(vec.as_slice()).await?;
            } else {
                for t in self {
                    t.wiring(wire).await?;
                }
            }
            Ok(())
        }
    }
}

impl<'a, T: Wiring> Wiring for &'a Vec<T>
where
    &'a T: Wiring + 'static,
{
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let len = self.len() as u64;
            len.wiring(wire).await?;
            let t = TypeId::of::<T>();
            let is_u8 = TypeId::of::<u8>();
            let is_i8 = TypeId::of::<i8>();
            if t == is_u8 || t == is_i8 {
                let vec = unsafe { std::mem::transmute::<_, &'a Vec<u8>>(self) };
                wire.write_all(vec.as_slice()).await?;
            } else {
                let mut i = self.iter();
                while let Some(t) = i.next() {
                    t.wiring(wire).await?;
                }
            }
            Ok(())
        }
    }
}

impl<T: Wiring> Wiring for std::collections::HashSet<T> {
    #[inline]
    fn wiring<W: Wire>(mut self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async move {
            let len = self.len() as u64;
            len.wiring(wire).await?;
            let mut s = self.drain();
            while let Some(t) = s.next() {
                t.wiring(wire).await?;
            }
            Ok(())
        }
    }
}

impl<'a, T: Wiring> Wiring for &'a std::collections::HashSet<T>
where
    &'a T: Wiring + std::fmt::Debug,
{
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        let mut i = self.iter();
        async move {
            let len = self.len() as u64;
            len.wiring(wire).await?;
            while let Some(t) = i.next() {
                t.wiring(wire).await?;
            }
            Ok(())
        }
    }
}

impl<T: Wiring> Wiring for Option<T> {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async {
            if let Some(t) = self {
                1u8.wiring(wire).await?;
                t.wiring(wire).await
            } else {
                0u8.wiring(wire).await
            }
        }
    }
}

impl<T: Wiring, TT: Wiring> Wiring for (T, TT) {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async {
            self.0.wiring(wire).await?;
            self.1.wiring(wire).await
        }
    }
}

impl<T: Wiring, TT: Wiring, TTT: Wiring> Wiring for (T, TT, TTT) {
    #[inline]
    fn wiring<W: Wire>(self, wire: &mut W) -> impl std::future::Future<Output = Result<(), std::io::Error>> {
        async {
            self.0.wiring(wire).await?;
            self.1.wiring(wire).await?;
            self.2.wiring(wire).await
        }
    }
}