celerity 0.1.1

Pure Rust sans-IO ZMTP 3.1 messaging core with Tokio TCP and Unix socket transports.
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
//! Higher-level Tokio socket wrappers built on top of [`TokioCelerity`].

use std::collections::{HashMap, HashSet, VecDeque};
use std::net::SocketAddr;

use bytes::Bytes;
use tokio::sync::{mpsc, oneshot, watch};
use tokio::task::JoinHandle;

use crate::{
    HwmConfig, LinkScope, LocalAuthPolicy, Multipart, PatternAction, PeerConfig, PeerEvent,
    PubCore, RepCore, ReqCore, SecurityConfig, SecurityRole, SocketType, SubCore,
};

use super::runtime::{
    ConnectionHandle, TokioCelerity, send_runtime_command, try_send_runtime_command,
};
use super::transport::{AnyListener, bind_any_listener, connect_any_stream};
use super::{
    BindOptions, ConnectOptions, Endpoint, SUBSCRIPTION_SETTLE_DELAY, TokioCelerityError,
    capacity_from_hwm,
};

/// A convenience wrapper for PUB semantics over Tokio transports.
#[derive(Debug)]
pub struct PubSocket {
    command_tx: mpsc::Sender<PubCommand>,
    ready_rx: watch::Receiver<usize>,
    endpoint: Endpoint,
    local_addr: Option<SocketAddr>,
    task: JoinHandle<Result<(), TokioCelerityError>>,
}

impl PubSocket {
    /// Binds a publisher to an endpoint using default bind options.
    ///
    /// # Errors
    ///
    /// Returns endpoint parsing, binding, or local-authorization errors.
    pub async fn bind(endpoint: &str) -> Result<Self, TokioCelerityError> {
        Self::bind_with_options(endpoint, BindOptions::default()).await
    }

    /// Binds a publisher to an endpoint with explicit bind options.
    ///
    /// # Errors
    ///
    /// Returns endpoint parsing, binding, or local-authorization errors.
    pub async fn bind_with_options(
        endpoint: &str,
        bind_options: BindOptions,
    ) -> Result<Self, TokioCelerityError> {
        let endpoint = Endpoint::parse(endpoint)?;
        let listener = bind_any_listener(
            &endpoint,
            bind_options,
            SecurityConfig::default_for(LinkScope::Local).local_auth,
        )
        .await?;
        let local_addr = listener.local_addr();
        let bound_endpoint = listener.endpoint().clone();
        let command_capacity = capacity_from_hwm(HwmConfig::default().outbound_messages);
        let (command_tx, command_rx) = mpsc::channel(command_capacity);
        let (ready_tx, ready_rx) = watch::channel(0_usize);

        let task =
            tokio::spawn(async move { run_pub_socket(listener, command_rx, ready_tx).await });

        Ok(Self {
            command_tx,
            ready_rx,
            endpoint: bound_endpoint,
            local_addr,
            task,
        })
    }

    /// Returns the bound endpoint.
    #[must_use]
    pub fn endpoint(&self) -> &Endpoint {
        &self.endpoint
    }

    /// Returns the bound TCP socket address.
    ///
    /// # Panics
    ///
    /// Panics when the publisher is not bound on TCP.
    #[must_use]
    pub fn local_addr(&self) -> SocketAddr {
        match self.local_addr {
            Some(addr) => addr,
            None => panic!("publisher is not bound on TCP"),
        }
    }

    /// Waits for at least one subscriber to become ready.
    ///
    /// # Errors
    ///
    /// Returns a runtime error if the readiness watcher task fails.
    pub async fn wait_for_subscriber(
        &mut self,
        timeout: std::time::Duration,
    ) -> Result<bool, TokioCelerityError> {
        if *self.ready_rx.borrow() > 0 {
            // Give subscription frames a brief moment to reach the publisher.
            tokio::time::sleep(SUBSCRIPTION_SETTLE_DELAY).await;
            return Ok(true);
        }

        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let changed = tokio::time::timeout_at(deadline, self.ready_rx.changed()).await;
            match changed {
                Ok(Ok(())) if *self.ready_rx.borrow() > 0 => {
                    tokio::time::sleep(SUBSCRIPTION_SETTLE_DELAY).await;
                    return Ok(true);
                }
                Ok(Ok(())) => {}
                Ok(Err(_)) | Err(_) => return Ok(*self.ready_rx.borrow() > 0),
            }
        }
    }

    /// Publishes a multipart message to connected subscribers.
    ///
    /// # Errors
    ///
    /// Returns a runtime error if the background task has ended or rejects the
    /// message.
    pub async fn send(&self, message: Multipart) -> Result<(), TokioCelerityError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(PubCommand::Send(message, reply_tx))
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("pub command channel"))?;
        reply_rx
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("pub command response channel"))?
    }

    /// Waits for the publisher task to finish.
    ///
    /// # Errors
    ///
    /// Returns the terminal runtime error if the task failed.
    pub async fn join(self) -> Result<(), TokioCelerityError> {
        self.task.await?
    }
}

/// A convenience wrapper for SUB semantics over Tokio transports.
#[derive(Debug)]
pub struct SubSocket {
    command_tx: mpsc::Sender<SubCommand>,
    message_rx: mpsc::Receiver<Result<Multipart, TokioCelerityError>>,
    task: JoinHandle<Result<(), TokioCelerityError>>,
}

impl SubSocket {
    /// Connects a subscriber to an endpoint.
    ///
    /// # Errors
    ///
    /// Returns endpoint parsing, connect, or local-authorization errors.
    pub async fn connect(endpoint: &str) -> Result<Self, TokioCelerityError> {
        Self::connect_with_options(endpoint, ConnectOptions).await
    }

    /// Connects a subscriber with explicit connect options.
    ///
    /// # Errors
    ///
    /// Returns endpoint parsing, connect, or local-authorization errors.
    pub async fn connect_with_options(
        endpoint: &str,
        _options: ConnectOptions,
    ) -> Result<Self, TokioCelerityError> {
        let endpoint = Endpoint::parse(endpoint)?;
        let (stream, transport) =
            connect_any_stream(&endpoint, LocalAuthPolicy::FilesystemStrict).await?;
        let config = PeerConfig::new(SocketType::Sub, SecurityRole::Client, transport.link_scope);
        let connection = TokioCelerity::from_stream(stream, transport, config)?;
        let (command_tx, command_rx) =
            mpsc::channel(capacity_from_hwm(HwmConfig::default().outbound_messages));
        let (message_tx, message_rx) =
            mpsc::channel(capacity_from_hwm(HwmConfig::default().inbound_messages));
        let task =
            tokio::spawn(async move { run_sub_socket(connection, command_rx, message_tx).await });

        Ok(Self {
            command_tx,
            message_rx,
            task,
        })
    }

    /// Registers a subscription prefix.
    ///
    /// # Errors
    ///
    /// Returns a runtime or protocol error if the background task rejects the
    /// subscription.
    pub async fn subscribe(&self, topic: Bytes) -> Result<(), TokioCelerityError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(SubCommand::Subscribe(topic, reply_tx))
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("sub command channel"))?;
        reply_rx
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("sub command response channel"))?
    }

    /// Cancels a previously registered subscription prefix.
    ///
    /// # Errors
    ///
    /// Returns a runtime or protocol error if the background task rejects the
    /// cancellation.
    pub async fn cancel(&self, topic: Bytes) -> Result<(), TokioCelerityError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(SubCommand::Cancel(topic, reply_tx))
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("sub command channel"))?;
        reply_rx
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("sub command response channel"))?
    }

    /// Receives the next delivered multipart message.
    ///
    /// # Errors
    ///
    /// Returns the terminal runtime error if the background task has ended.
    pub async fn recv(&mut self) -> Result<Multipart, TokioCelerityError> {
        match self.message_rx.recv().await {
            Some(result) => result,
            None => Err(self.join_on_closed_channel().await),
        }
    }

    /// Waits for the subscriber task to finish.
    ///
    /// # Errors
    ///
    /// Returns the terminal runtime error if the task failed.
    pub async fn join(self) -> Result<(), TokioCelerityError> {
        self.task.await?
    }

    async fn join_on_closed_channel(&mut self) -> TokioCelerityError {
        match (&mut self.task).await {
            Ok(Ok(())) => TokioCelerityError::BackgroundTaskEnded,
            Ok(Err(err)) => err,
            Err(err) => TokioCelerityError::Join(err),
        }
    }
}

/// A convenience wrapper for REQ semantics over Tokio transports.
#[derive(Debug)]
pub struct ReqSocket {
    command_tx: mpsc::Sender<ReqCommand>,
    task: JoinHandle<Result<(), TokioCelerityError>>,
}

impl ReqSocket {
    /// Connects a requester to an endpoint.
    ///
    /// # Errors
    ///
    /// Returns endpoint parsing, connect, or local-authorization errors.
    pub async fn connect(endpoint: &str) -> Result<Self, TokioCelerityError> {
        let endpoint = Endpoint::parse(endpoint)?;
        let (stream, transport) =
            connect_any_stream(&endpoint, LocalAuthPolicy::FilesystemStrict).await?;
        let config = PeerConfig::new(SocketType::Req, SecurityRole::Client, transport.link_scope);
        let connection = TokioCelerity::from_stream(stream, transport, config)?;
        let (command_tx, command_rx) =
            mpsc::channel(capacity_from_hwm(HwmConfig::default().outbound_messages));
        let task = tokio::spawn(async move { run_req_socket(connection, command_rx).await });

        Ok(Self { command_tx, task })
    }

    /// Sends a request and waits for the corresponding reply.
    ///
    /// # Errors
    ///
    /// Returns a runtime or protocol error if the request cannot be processed.
    pub async fn request(&self, message: Multipart) -> Result<Multipart, TokioCelerityError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(ReqCommand::Request(message, reply_tx))
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("req command channel"))?;
        reply_rx
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("req response channel"))?
    }

    /// Waits for the requester task to finish.
    ///
    /// # Errors
    ///
    /// Returns the terminal runtime error if the task failed.
    pub async fn join(self) -> Result<(), TokioCelerityError> {
        self.task.await?
    }
}

/// A convenience wrapper for REP semantics over Tokio transports.
#[derive(Debug)]
pub struct RepSocket {
    command_tx: mpsc::Sender<RepCommand>,
    request_rx: mpsc::Receiver<Result<Multipart, TokioCelerityError>>,
    endpoint: Endpoint,
    local_addr: Option<SocketAddr>,
    task: JoinHandle<Result<(), TokioCelerityError>>,
}

impl RepSocket {
    /// Binds a responder to an endpoint using default bind options.
    ///
    /// # Errors
    ///
    /// Returns endpoint parsing, binding, or local-authorization errors.
    pub async fn bind(endpoint: &str) -> Result<Self, TokioCelerityError> {
        Self::bind_with_options(endpoint, BindOptions::default()).await
    }

    /// Binds a responder to an endpoint with explicit bind options.
    ///
    /// # Errors
    ///
    /// Returns endpoint parsing, binding, or local-authorization errors.
    pub async fn bind_with_options(
        endpoint: &str,
        bind_options: BindOptions,
    ) -> Result<Self, TokioCelerityError> {
        let endpoint = Endpoint::parse(endpoint)?;
        let listener = bind_any_listener(
            &endpoint,
            bind_options,
            SecurityConfig::default_for(LinkScope::Local).local_auth,
        )
        .await?;
        let local_addr = listener.local_addr();
        let bound_endpoint = listener.endpoint().clone();
        let (command_tx, command_rx) =
            mpsc::channel(capacity_from_hwm(HwmConfig::default().outbound_messages));
        let (request_tx, request_rx) =
            mpsc::channel(capacity_from_hwm(HwmConfig::default().inbound_messages));
        let task =
            tokio::spawn(async move { run_rep_socket(listener, command_rx, request_tx).await });

        Ok(Self {
            command_tx,
            request_rx,
            endpoint: bound_endpoint,
            local_addr,
            task,
        })
    }

    /// Returns the bound endpoint.
    #[must_use]
    pub fn endpoint(&self) -> &Endpoint {
        &self.endpoint
    }

    /// Returns the bound TCP socket address.
    ///
    /// # Panics
    ///
    /// Panics when the responder is not bound on TCP.
    #[must_use]
    pub fn local_addr(&self) -> SocketAddr {
        match self.local_addr {
            Some(addr) => addr,
            None => panic!("responder is not bound on TCP"),
        }
    }

    /// Receives the next inbound request body.
    ///
    /// # Errors
    ///
    /// Returns the terminal runtime error if the background task has ended.
    pub async fn recv(&mut self) -> Result<Multipart, TokioCelerityError> {
        match self.request_rx.recv().await {
            Some(result) => result,
            None => Err(self.join_on_closed_channel().await),
        }
    }

    /// Sends a reply for the currently active request.
    ///
    /// # Errors
    ///
    /// Returns a runtime or protocol error if the reply cannot be processed.
    pub async fn reply(&self, message: Multipart) -> Result<(), TokioCelerityError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(RepCommand::Reply(message, reply_tx))
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("rep command channel"))?;
        reply_rx
            .await
            .map_err(|_| TokioCelerityError::ChannelClosed("rep command response channel"))?
    }

    /// Waits for the responder task to finish.
    ///
    /// # Errors
    ///
    /// Returns the terminal runtime error if the task failed.
    pub async fn join(self) -> Result<(), TokioCelerityError> {
        self.task.await?
    }

    async fn join_on_closed_channel(&mut self) -> TokioCelerityError {
        match (&mut self.task).await {
            Ok(Ok(())) => TokioCelerityError::BackgroundTaskEnded,
            Ok(Err(err)) => err,
            Err(err) => TokioCelerityError::Join(err),
        }
    }
}

#[derive(Debug)]
enum PubCommand {
    Send(Multipart, oneshot::Sender<Result<(), TokioCelerityError>>),
}

#[derive(Debug)]
enum SubCommand {
    Subscribe(Bytes, oneshot::Sender<Result<(), TokioCelerityError>>),
    Cancel(Bytes, oneshot::Sender<Result<(), TokioCelerityError>>),
}

#[derive(Debug)]
enum ReqCommand {
    Request(
        Multipart,
        oneshot::Sender<Result<Multipart, TokioCelerityError>>,
    ),
}

#[derive(Debug)]
enum RepCommand {
    Reply(Multipart, oneshot::Sender<Result<(), TokioCelerityError>>),
}

#[derive(Debug)]
enum PeerUpdate {
    Event { peer: u64, event: PeerEvent },
    Closed { peer: u64 },
}

async fn run_pub_socket(
    listener: AnyListener,
    mut command_rx: mpsc::Receiver<PubCommand>,
    ready_tx: watch::Sender<usize>,
) -> Result<(), TokioCelerityError> {
    let (update_tx, mut update_rx) = mpsc::unbounded_channel();
    let mut pub_core = PubCore::new();
    let mut peers = HashMap::new();
    let mut ready_peers = HashSet::new();
    let mut next_peer_id = 0_u64;

    loop {
        tokio::select! {
            accept = listener.accept() => {
                let (stream, transport) = accept?;
                let peer = next_peer_id;
                next_peer_id = next_peer_id.wrapping_add(1);
                let config = PeerConfig::new(SocketType::Pub, SecurityRole::Server, transport.link_scope);
                let connection = TokioCelerity::from_stream(stream, transport, config)?;
                let handle = spawn_peer_forwarder(peer, connection, update_tx.clone());
                peers.insert(peer, handle);
            }
            command = command_rx.recv() => {
                match command {
                    Some(PubCommand::Send(message, reply_tx)) => {
                        let result = dispatch_pub_message(&pub_core, &peers, message).await;
                        let _ = reply_tx.send(result);
                    }
                    None => return Ok(()),
                }
            }
            update = update_rx.recv() => {
                match update {
                    Some(PeerUpdate::Event { peer, event }) => {
                        if matches!(event, PeerEvent::HandshakeComplete { .. }) {
                            // A transport is publish-ready only after the ZMTP handshake finishes.
                            ready_peers.insert(peer);
                            let _ = ready_tx.send(ready_peers.len());
                        }
                        if let PeerEvent::Subscription { .. } = &event {
                            pub_core.on_peer_event(peer, event)?;
                        }
                    }
                    Some(PeerUpdate::Closed { peer }) => {
                        pub_core.remove_peer(peer);
                        peers.remove(&peer);
                        ready_peers.remove(&peer);
                        let _ = ready_tx.send(ready_peers.len());
                    }
                    None => return Ok(()),
                }
            }
        }
    }
}

async fn dispatch_pub_message(
    pub_core: &PubCore<u64>,
    peers: &HashMap<u64, ConnectionHandle>,
    message: Multipart,
) -> Result<(), TokioCelerityError> {
    for action in pub_core.publish(&message)? {
        if let PatternAction::Send { peer, item } = action
            && let Some(handle) = peers.get(&peer)
        {
            // PUB fanout is best-effort; a full peer queue does not stall everyone else.
            match try_send_runtime_command(&handle.command_tx, &handle.terminal_rx, item).await {
                Ok(())
                | Err(
                    TokioCelerityError::QueueFull
                    | TokioCelerityError::BackgroundTaskEnded
                    | TokioCelerityError::ChannelClosed(_),
                ) => {}
                Err(err) => return Err(err),
            }
        }
    }

    Ok(())
}

async fn run_sub_socket(
    mut connection: TokioCelerity,
    mut command_rx: mpsc::Receiver<SubCommand>,
    message_tx: mpsc::Sender<Result<Multipart, TokioCelerityError>>,
) -> Result<(), TokioCelerityError> {
    let peer = 0_u64;
    let mut sub_core = SubCore::new();
    let _ = sub_core.add_peer(peer);

    let result = loop {
        tokio::select! {
            command = command_rx.recv() => {
                match command {
                    Some(SubCommand::Subscribe(topic, reply_tx)) => {
                        let result = async {
                            for action in sub_core.subscribe(&topic)? {
                                send_sub_action(&connection, action).await?;
                            }
                            Ok(())
                        }.await;
                        let _ = reply_tx.send(result);
                    }
                    Some(SubCommand::Cancel(topic, reply_tx)) => {
                        let result = async {
                            for action in sub_core.cancel(&topic)? {
                                send_sub_action(&connection, action).await?;
                            }
                            Ok(())
                        }.await;
                        let _ = reply_tx.send(result);
                    }
                    None => break Ok(()),
                }
            }
            event = connection.recv() => {
                match event {
                    Some(event) => {
                        for action in sub_core.on_peer_event(peer, event)? {
                            if let PatternAction::Deliver { message, .. } = action {
                                message_tx
                                    .send(Ok(message))
                                    .await
                                    .map_err(|_| TokioCelerityError::ChannelClosed("sub message channel"))?;
                            }
                        }
                    }
                    None => break connection.join().await,
                }
            }
        }
    };

    if let Err(err) = &result {
        let _ = message_tx.send(Err(background_error(err))).await;
    }

    result
}

async fn send_sub_action(
    connection: &TokioCelerity,
    action: PatternAction<u64>,
) -> Result<(), TokioCelerityError> {
    if let PatternAction::Send { item, .. } = action {
        connection.send(item).await?;
    }
    Ok(())
}

async fn run_req_socket(
    mut connection: TokioCelerity,
    mut command_rx: mpsc::Receiver<ReqCommand>,
) -> Result<(), TokioCelerityError> {
    let peer = 0_u64;
    let mut req_core = ReqCore::new();
    req_core.add_peer(peer);
    let mut queue = VecDeque::new();
    let mut in_flight: Option<oneshot::Sender<Result<Multipart, TokioCelerityError>>> = None;

    let result = loop {
        tokio::select! {
            command = command_rx.recv() => {
                match command {
                    Some(ReqCommand::Request(message, reply_tx)) => {
                        queue.push_back((message, reply_tx));
                        drive_req_queue(&mut req_core, &connection, &mut queue, &mut in_flight).await?;
                    }
                    None => break Ok(()),
                }
            }
            event = connection.recv() => {
                match event {
                    Some(event) => {
                        for action in req_core.on_peer_event(peer, event)? {
                            if let PatternAction::Deliver { message, .. } = action
                                && let Some(reply_tx) = in_flight.take()
                            {
                                let _ = reply_tx.send(Ok(message));
                            }
                        }
                        drive_req_queue(&mut req_core, &connection, &mut queue, &mut in_flight).await?;
                    }
                    None => break connection.join().await,
                }
            }
        }
    };

    if let Err(err) = &result {
        while let Some((_, reply_tx)) = queue.pop_front() {
            let _ = reply_tx.send(Err(background_error(err)));
        }
        if let Some(reply_tx) = in_flight.take() {
            let _ = reply_tx.send(Err(background_error(err)));
        }
    }

    result
}

async fn drive_req_queue(
    req_core: &mut ReqCore<u64>,
    connection: &TokioCelerity,
    queue: &mut VecDeque<(
        Multipart,
        oneshot::Sender<Result<Multipart, TokioCelerityError>>,
    )>,
    in_flight: &mut Option<oneshot::Sender<Result<Multipart, TokioCelerityError>>>,
) -> Result<(), TokioCelerityError> {
    if in_flight.is_some() {
        // REQ cannot send the next request until the current reply lands.
        return Ok(());
    }

    let Some((message, reply_tx)) = queue.pop_front() else {
        return Ok(());
    };

    match req_core.send(message)? {
        PatternAction::Send { item, .. } => {
            connection.send(item).await?;
            *in_flight = Some(reply_tx);
        }
        PatternAction::Deliver { .. } => {}
    }

    Ok(())
}

async fn run_rep_socket(
    listener: AnyListener,
    mut command_rx: mpsc::Receiver<RepCommand>,
    request_tx: mpsc::Sender<Result<Multipart, TokioCelerityError>>,
) -> Result<(), TokioCelerityError> {
    let (update_tx, mut update_rx) = mpsc::unbounded_channel();
    let mut rep_core = RepCore::new();
    let mut peers = HashMap::new();
    let mut next_peer_id = 0_u64;

    loop {
        tokio::select! {
            accept = listener.accept() => {
                let (stream, transport) = accept?;
                let peer = next_peer_id;
                next_peer_id = next_peer_id.wrapping_add(1);
                // Register the peer before events arrive so request routing has a queue.
                rep_core.add_peer(peer);
                let config = PeerConfig::new(SocketType::Rep, SecurityRole::Server, transport.link_scope);
                let connection = TokioCelerity::from_stream(stream, transport, config)?;
                let handle = spawn_peer_forwarder(peer, connection, update_tx.clone());
                peers.insert(peer, handle);
            }
            command = command_rx.recv() => {
                match command {
                    Some(RepCommand::Reply(message, reply_tx)) => {
                        let result = async {
                            let actions = rep_core.reply(message)?;
                            apply_rep_actions(&peers, &request_tx, actions).await
                        }.await;
                        let _ = reply_tx.send(result);
                    }
                    None => return Ok(()),
                }
            }
            update = update_rx.recv() => {
                match update {
                    Some(PeerUpdate::Event { peer, event }) => {
                        for action in rep_core.on_peer_event(peer, event)? {
                            if let PatternAction::Deliver { message, .. } = action {
                                request_tx
                                    .send(Ok(message))
                                    .await
                                    .map_err(|_| TokioCelerityError::ChannelClosed("rep request channel"))?;
                            }
                        }
                    }
                    Some(PeerUpdate::Closed { peer }) => {
                        peers.remove(&peer);
                        let actions = rep_core.remove_peer(peer)?;
                        apply_rep_actions(&peers, &request_tx, actions).await?;
                    }
                    None => return Ok(()),
                }
            }
        }
    }
}

async fn apply_rep_actions(
    peers: &HashMap<u64, ConnectionHandle>,
    request_tx: &mpsc::Sender<Result<Multipart, TokioCelerityError>>,
    actions: Vec<PatternAction<u64>>,
) -> Result<(), TokioCelerityError> {
    for action in actions {
        match action {
            PatternAction::Send { peer, item } => {
                let Some(handle) = peers.get(&peer) else {
                    return Err(TokioCelerityError::BackgroundTaskEnded);
                };
                send_runtime_command(&handle.command_tx, &handle.terminal_rx, item).await?;
            }
            PatternAction::Deliver { message, .. } => {
                request_tx
                    .send(Ok(message))
                    .await
                    .map_err(|_| TokioCelerityError::ChannelClosed("rep request channel"))?;
            }
        }
    }
    Ok(())
}

fn spawn_peer_forwarder(
    peer: u64,
    connection: TokioCelerity,
    update_tx: mpsc::UnboundedSender<PeerUpdate>,
) -> ConnectionHandle {
    let (handle, mut event_rx, task) = connection.into_parts();
    tokio::spawn(async move {
        while let Some(event) = event_rx.recv().await {
            if update_tx.send(PeerUpdate::Event { peer, event }).is_err() {
                return;
            }
        }

        let _ = task.await;
        let _ = update_tx.send(PeerUpdate::Closed { peer });
    });
    handle
}

fn background_error(err: &TokioCelerityError) -> TokioCelerityError {
    TokioCelerityError::BackgroundTaskFailed(err.to_string())
}