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
use aggligator::control::DisconnectReason;
use async_trait::async_trait;
use futures::{
future::{self, BoxFuture},
stream::FuturesUnordered,
FutureExt, StreamExt,
};
use std::{
collections::HashSet,
fmt::{self, Debug},
future::IntoFuture,
io::{Error, ErrorKind, Result},
iter,
sync::{Arc, Weak},
time::Duration,
};
use tokio::{
sync::{broadcast, mpsc, oneshot, watch, RwLock},
time::sleep,
};
use super::{BoxControl, BoxLink, BoxLinkError, IoBox, LinkTag, LinkTagBox};
use aggligator::{connect, Cfg, IoRxBox, IoTxBox, Link, Outgoing, Task};
#[async_trait]
pub trait ConnectingTransport: Send + Sync + 'static {
fn name(&self) -> &str;
async fn link_tags(&self, tx: watch::Sender<HashSet<LinkTagBox>>) -> Result<()>;
async fn connect(&self, tag: &dyn LinkTag) -> Result<IoBox>;
async fn link_filter(&self, _new: &Link<LinkTagBox>, _existing: &[Link<LinkTagBox>]) -> bool {
true
}
}
type ArcConnectingTransport = Arc<dyn ConnectingTransport>;
#[async_trait]
pub trait ConnectingWrapper: Send + Sync + fmt::Debug + 'static {
fn name(&self) -> &str;
async fn wrap(&self, io: IoBox) -> Result<IoBox>;
}
type BoxConnectingWrapper = Box<dyn ConnectingWrapper>;
struct TransportPack {
transport: ArcConnectingTransport,
result_tx: oneshot::Sender<Result<()>>,
remove_rx: oneshot::Receiver<()>,
}
#[derive(Debug)]
pub struct ConnectorBuilder {
task: Task<IoTxBox, IoRxBox, LinkTagBox>,
outgoing: Outgoing,
control: BoxControl,
reconnect_delay: Duration,
wrappers: Vec<BoxConnectingWrapper>,
}
impl ConnectorBuilder {
pub fn new(cfg: Cfg) -> Self {
let (task, outgoing, control) = connect(cfg);
Self { task, outgoing, control, reconnect_delay: Duration::from_secs(10), wrappers: Vec::new() }
}
pub fn task(&mut self) -> &mut Task<IoTxBox, IoRxBox, LinkTagBox> {
&mut self.task
}
pub fn set_reconnect_delay(&mut self, reconnect_delay: Duration) {
self.reconnect_delay = reconnect_delay
}
pub fn wrap(&mut self, wrapper: impl ConnectingWrapper) {
self.wrappers.push(Box::new(wrapper))
}
pub fn build(self) -> Connector {
let Self { mut task, outgoing, control, reconnect_delay, wrappers } = self;
let active_transports = Arc::new(RwLock::new(Vec::<Weak<dyn ConnectingTransport>>::new()));
let active_transports_filter = active_transports.clone();
task.set_link_filter(move |link, others| {
let active_transports_filter = active_transports_filter.clone();
async move {
let transports = active_transports_filter.read_owned().await;
for transport in &*transports {
let Some(transport) = transport.upgrade() else { continue };
if !transport.link_filter(&link, &others).await {
return false;
}
}
true
}
});
tokio::spawn(task.run());
let (transport_tx, transport_rx) = mpsc::unbounded_channel();
let (tags_tx, tags_rx) = watch::channel(HashSet::new());
let (error_tx, error_rx) = broadcast::channel(1024);
let (disabled_tags_tx, disabled_tags_rx) = watch::channel(HashSet::new());
tokio::spawn(Connector::task(
control.clone(),
active_transports,
transport_rx,
tags_tx,
disabled_tags_rx,
error_tx,
reconnect_delay,
wrappers,
));
Connector { control, outgoing: Some(outgoing), transport_tx, tags_rx, error_rx, disabled_tags_tx }
}
}
pub struct Connector {
control: BoxControl,
outgoing: Option<Outgoing>,
transport_tx: mpsc::UnboundedSender<TransportPack>,
tags_rx: watch::Receiver<HashSet<LinkTagBox>>,
disabled_tags_tx: watch::Sender<HashSet<LinkTagBox>>,
error_rx: broadcast::Receiver<BoxLinkError>,
}
impl fmt::Debug for Connector {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Connector").field("id", &self.control.id()).finish()
}
}
impl Default for Connector {
fn default() -> Self {
Self::new()
}
}
impl Connector {
pub fn new() -> Self {
ConnectorBuilder::new(Cfg::default()).build()
}
pub fn wrapped(wrapper: impl ConnectingWrapper) -> Self {
let mut builder = ConnectorBuilder::new(Cfg::default());
builder.wrap(wrapper);
builder.build()
}
pub fn add(&self, transport: impl ConnectingTransport) -> ConnectingTransportHandle {
let name = transport.name().to_string();
let (result_tx, result_rx) = oneshot::channel();
let (remove_tx, remove_rx) = oneshot::channel();
let pack = TransportPack { transport: Arc::new(transport), result_tx, remove_rx };
let _ = self.transport_tx.send(pack);
ConnectingTransportHandle { name, result_rx, remove_tx }
}
pub fn channel(&mut self) -> Option<Outgoing> {
self.outgoing.take()
}
pub fn control(&self) -> BoxControl {
self.control.clone()
}
pub fn available_tags(&self) -> HashSet<LinkTagBox> {
self.tags_rx.borrow().clone()
}
pub fn available_tags_watch(&self) -> watch::Receiver<HashSet<LinkTagBox>> {
self.tags_rx.clone()
}
pub fn set_disabled_tags(&self, disabled_tags: HashSet<LinkTagBox>) {
self.disabled_tags_tx.send_replace(disabled_tags);
}
pub fn link_errors(&self) -> broadcast::Receiver<BoxLinkError> {
self.error_rx.resubscribe()
}
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(level="debug", skip_all, fields(id=%control.id()))]
async fn task(
control: BoxControl, active_transports: Arc<RwLock<Vec<Weak<dyn ConnectingTransport>>>>,
mut transport_rx: mpsc::UnboundedReceiver<TransportPack>, tags_tx: watch::Sender<HashSet<LinkTagBox>>,
disabled_tags_rx: watch::Receiver<HashSet<LinkTagBox>>, link_error_tx: broadcast::Sender<BoxLinkError>,
reconnect_delay: Duration, wrappers: Vec<BoxConnectingWrapper>,
) {
let wrappers = Arc::new(wrappers);
let mut transport_tasks = FuturesUnordered::new();
let mut transport_tags: Vec<watch::Receiver<HashSet<LinkTagBox>>> = Vec::new();
loop {
transport_tags.retain(|tt| tt.has_changed().is_ok());
let mut all_tags = HashSet::new();
for tt in &mut transport_tags {
let tags = tt.borrow_and_update();
for tag in &*tags {
all_tags.insert(tag.clone());
}
}
tags_tx.send_if_modified(|tags| {
if *tags == all_tags {
false
} else {
*tags = all_tags;
true
}
});
let tags_changed = future::select_all(
transport_tags
.iter_mut()
.map(|tt| tt.changed().boxed())
.chain(iter::once(future::pending().boxed())),
);
enum ConnectorEvent {
TransportAdded(TransportPack),
TagsChanged,
TransportTerminated,
}
let event = tokio::select! {
Some(transport_pack) = transport_rx.recv() => ConnectorEvent::TransportAdded(transport_pack),
_ = tags_changed => ConnectorEvent::TagsChanged,
Some(()) = transport_tasks.next() => ConnectorEvent::TransportTerminated,
() = control.terminated() => {
tracing::debug!("connection was terminated");
break;
}
};
match event {
ConnectorEvent::TransportAdded(transport_pack) => {
let mut active_transports = active_transports.write().await;
active_transports.retain(|at| at.strong_count() > 0);
active_transports.push(Arc::downgrade(&transport_pack.transport));
let (transport_tags_tx, transport_tags_rx) = watch::channel(HashSet::new());
transport_tags.push(transport_tags_rx);
transport_tasks.push(Self::transport_task(
transport_pack,
control.clone(),
transport_tags_tx,
disabled_tags_rx.clone(),
link_error_tx.clone(),
reconnect_delay,
wrappers.clone(),
));
}
ConnectorEvent::TagsChanged => (),
ConnectorEvent::TransportTerminated => (),
}
}
}
#[tracing::instrument(level="debug", skip_all, fields(id=%control.id(), transport=transport_pack.transport.name()))]
async fn transport_task(
transport_pack: TransportPack, control: BoxControl, tags_fw_tx: watch::Sender<HashSet<LinkTagBox>>,
mut disabled_tags_rx: watch::Receiver<HashSet<LinkTagBox>>,
link_error_tx: broadcast::Sender<BoxLinkError>, reconnect_delay: Duration,
wrappers: Arc<Vec<BoxConnectingWrapper>>,
) {
let TransportPack { transport, result_tx, mut remove_rx } = transport_pack;
let conn_id = control.id();
let mut changed_control = control.clone();
let (tags_tx, mut tags_rx) = watch::channel(HashSet::new());
let mut tags_task = transport.link_tags(tags_tx);
let mut tags_changed = true;
let mut connecting_tags = HashSet::new();
let mut connecting_tasks = FuturesUnordered::new();
let mut link_filter_rejected_tags = HashSet::new();
let res = 'outer: loop {
{
let links = control.links();
let disabled_tags = disabled_tags_rx.borrow_and_update();
for link in &links {
if disabled_tags.contains(link.tag()) {
link.start_disconnect();
}
}
let tags = tags_rx.borrow_and_update().clone();
if tags_changed {
tracing::debug!(
"available tags: {}",
tags.iter().map(|tag| tag.to_string()).collect::<Vec<_>>().join(", ")
);
tags_fw_tx.send_replace(tags.clone());
tags_changed = false;
}
for tag in tags {
if tag.transport_name() != transport.name() {
break 'outer Err(Error::new(
ErrorKind::Other,
"link tag transport name mismatch".to_string(),
));
}
if connecting_tags.contains(&tag)
|| disabled_tags.contains(&tag)
|| link_filter_rejected_tags.contains(&tag)
|| links.iter().any(|link| link.tag() == &tag)
{
continue;
}
tracing::debug!("connecting tag: {tag}");
connecting_tags.insert(tag.clone());
let connect_task = async {
tracing::debug!("establishing transport connection for tag {tag}");
let mut io_box = match transport.connect(&*tag).await {
Ok(io_box) => io_box,
Err(err) => {
tracing::debug!("connecting transport for tag {tag} failed: {err}");
let _ = link_error_tx.send(BoxLinkError::outgoing(conn_id, &tag, err));
sleep(reconnect_delay).await;
return (tag, None);
}
};
for wrapper in &*wrappers {
let name = wrapper.name();
tracing::debug!("wrapping tag {tag} in {name}");
match wrapper.wrap(io_box).await {
Ok(wrapped) => io_box = wrapped,
Err(err) => {
tracing::debug!("wrapping tag {tag} in {name} failed: {err}");
let _ = link_error_tx.send(BoxLinkError::outgoing(conn_id, &tag, err));
sleep(reconnect_delay).await;
return (tag, None);
}
}
}
tracing::debug!("adding link for tag {tag} to connection");
let IoBox { read, write } = io_box;
let link = match control.add_io(read, write, tag.clone(), &tag.user_data()).await {
Ok(link) => link,
Err(err) => {
tracing::debug!("adding link for tag {tag} to connection failed: {err}");
let _ = link_error_tx.send(BoxLinkError::outgoing(conn_id, &tag, err.into()));
sleep(reconnect_delay).await;
return (tag, None);
}
};
tracing::debug!("link for tag {tag} connected");
struct DisconnectLink<'a>(&'a BoxLink);
impl<'a> Drop for DisconnectLink<'a> {
fn drop(&mut self) {
self.0.start_disconnect();
}
}
let _disconnect_link = DisconnectLink(&link);
let sleep_until = sleep(reconnect_delay);
let reason = link.disconnected().await;
tracing::debug!("link for tag {tag} disconnected: {reason}");
let _ = link_error_tx.send(BoxLinkError::outgoing(conn_id, &tag, reason.clone().into()));
sleep_until.await;
(tag, Some(reason))
};
connecting_tasks.push(connect_task);
}
}
tokio::select! {
res = &mut tags_task => break res,
Ok(()) = &mut remove_rx => break Ok(()),
Ok(()) = disabled_tags_rx.changed() => (),
Ok(()) = tags_rx.changed() => tags_changed = true,
() = changed_control.links_changed() => (),
() = control.terminated() => break Ok(()),
Some((tag, reason)) = connecting_tasks.next() => {
connecting_tags.remove(&tag);
match reason {
Some(DisconnectReason::LinkFilter) => {
tracing::debug!("blocking tag {tag}");
link_filter_rejected_tags.insert(tag);
}
Some(_) => {
tracing::debug!("clearing tag block list");
link_filter_rejected_tags.clear();
}
None => (),
}
},
}
};
match &res {
Ok(()) => tracing::debug!("transport terminated"),
Err(err) => tracing::debug!("transport failed: {err}"),
}
let _ = result_tx.send(res);
}
}
pub struct ConnectingTransportHandle {
name: String,
result_rx: oneshot::Receiver<Result<()>>,
remove_tx: oneshot::Sender<()>,
}
impl fmt::Debug for ConnectingTransportHandle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ConnectingTransportHandle").field("name", &self.name).finish()
}
}
impl ConnectingTransportHandle {
pub fn name(&self) -> &str {
&self.name
}
pub fn remove(self) {
let Self { remove_tx, .. } = self;
let _ = remove_tx.send(());
}
}
impl IntoFuture for ConnectingTransportHandle {
type Output = Result<()>;
type IntoFuture = BoxFuture<'static, Result<()>>;
fn into_future(self) -> Self::IntoFuture {
let Self { result_rx, .. } = self;
async move {
match result_rx.await {
Ok(res) => res,
Err(_) => Ok(()),
}
}
.boxed()
}
}