ramqp 0.5.3

A from-scratch, clean-room AMQP 1.0 client.
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
//! The [`Connection`] handle (WP-5.2): a cheap, clonable entry point that
//! spawns and talks to the driver task.

use std::sync::Arc;

use tokio::sync::{broadcast, mpsc, oneshot};
use tokio::task::JoinHandle;

use crate::api::session::Session;
use crate::config::Config;
use crate::connection::driver::Driver;
use crate::error::{ConnectError, ErrorKind, SessionError};
use crate::observe::{ConnectionEvent, EventBus, SharedMetrics};
use crate::proto::DriverCommand;
use crate::sasl::SaslProfile;
use crate::transport::header::ProtocolHeader;
use crate::transport::{self, Address};
use crate::transport::frame::FramedTransport;
use crate::types::performatives::Begin;

/// An open AMQP connection. Dropping the last handle (this plus all sessions)
/// triggers a graceful close; [`close`](Connection::close) awaits it explicitly.
#[derive(Debug)]
pub struct Connection {
    commands: mpsc::Sender<DriverCommand>,
    events: EventBus,
    config: Arc<Config>,
    driver: Option<JoinHandle<Result<(), ConnectError>>>,
}

impl Connection {
    /// Open a connection to `url` with default config (PLAIN if the URL carries
    /// credentials, else ANONYMOUS).
    ///
    /// # Examples
    /// ```no_run
    /// # async fn ex() -> Result<(), Box<dyn std::error::Error>> {
    /// use ramqp::{Connection, Message};
    ///
    /// let conn = Connection::open("amqp://guest:guest@localhost:5672").await?;
    /// let session = conn.begin_session().await?;
    ///
    /// let producer = session.create_producer("my-queue").await?;
    /// producer.send(Message::text("hello")).await?;
    ///
    /// let mut consumer = session.create_consumer("my-queue").await?;
    /// let delivery = consumer.recv().await?;
    /// consumer.accept(&delivery).await?;
    ///
    /// conn.close().await?;
    /// # Ok(()) }
    /// ```
    pub async fn open(url: &str) -> Result<Connection, ConnectError> {
        crate::api::client::ConnectionBuilder::new(url).connect().await
    }

    /// Start building a connection to `url`.
    pub fn builder(url: &str) -> crate::api::client::ConnectionBuilder {
        crate::api::client::ConnectionBuilder::new(url)
    }

    /// Open a connection, retrying retryable failures with jittered backoff per
    /// `config.connection.reconnect`.
    pub async fn open_resilient(url: &str, config: Config) -> Result<Connection, ConnectError> {
        crate::resilience::connect_with_retry(url, config, crate::observe::noop_metrics()).await
    }

    /// Establish the transport, run the SASL + AMQP handshakes, and spawn the
    /// driver. Used by [`ConnectionBuilder`](crate::api::client::ConnectionBuilder).
    pub(crate) async fn establish(
        addr: Address,
        config: Config,
        metrics: SharedMetrics,
        profile: SaslProfile,
        tls: crate::transport::TlsConfig,
    ) -> Result<Connection, ConnectError> {
        let config = Arc::new(config);

        let mut stream = transport::connect(&addr, &tls).await?;

        // SASL layer: header → mechanism negotiation → AMQP header.
        ProtocolHeader::SASL.negotiate(&mut stream).await?;
        let mut framed = FramedTransport::new(stream, config.connection.max_frame_size);
        crate::sasl::negotiate(&mut framed, &profile, Some(&addr.host)).await?;
        ProtocolHeader::AMQP.negotiate(framed.stream_mut()).await?;

        // Connection open + driver spawn.
        let events = EventBus::default();
        let (commands, rx) = mpsc::channel(config.connection.command_buffer);
        let driver = Driver::open(framed, config.clone(), metrics, events.clone(), rx).await?;
        let join = tokio::spawn(driver.run());

        Ok(Connection {
            commands,
            events,
            config,
            driver: Some(join),
        })
    }

    /// Build a connection handle around an already-running command sink + driver
    /// task. Used by the transparent-reconnect supervisor, which presents itself
    /// as a "virtual driver" so ordinary [`Session`]/producer/consumer handles
    /// survive reconnects unchanged.
    pub(crate) fn from_parts(
        commands: mpsc::Sender<DriverCommand>,
        events: EventBus,
        config: Arc<Config>,
        driver: JoinHandle<Result<(), ConnectError>>,
    ) -> Connection {
        Connection {
            commands,
            events,
            config,
            driver: Some(driver),
        }
    }

    /// Decompose into the driver command sink + its join handle, for a
    /// supervisor that manages the connection lifecycle itself.
    pub(crate) fn into_driver_parts(
        self,
    ) -> (
        mpsc::Sender<DriverCommand>,
        JoinHandle<Result<(), ConnectError>>,
    ) {
        (self.commands, self.driver.expect("driver present"))
    }

    /// Begin a new session on this connection.
    pub async fn begin_session(&self) -> Result<Session, SessionError> {
        let begin = Begin {
            next_outgoing_id: 0,
            incoming_window: self.config.session.incoming_window,
            outgoing_window: self.config.session.outgoing_window,
            handle_max: self.config.session.handle_max,
            ..Default::default()
        };
        let (reply_tx, reply_rx) = oneshot::channel();
        let (evt_tx, evt_rx) = mpsc::unbounded_channel();
        self.commands
            .send(DriverCommand::BeginSession {
                begin: Box::new(begin),
                events: evt_tx,
                reply: reply_tx,
            })
            .await
            .map_err(|_| SessionError::msg(ErrorKind::NotConnected, "connection closed"))?;
        let opened = reply_rx
            .await
            .map_err(|_| SessionError::msg(ErrorKind::Cancelled, "driver dropped"))??;
        Ok(Session::new(
            self.commands.clone(),
            opened.channel,
            evt_rx,
            self.config.clone(),
        ))
    }

    /// Subscribe to connection lifecycle events.
    pub fn subscribe(&self) -> broadcast::Receiver<ConnectionEvent> {
        self.events.subscribe()
    }

    /// The configuration in effect.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Whether the driver task is still running (used by the connection pool).
    pub fn is_alive(&self) -> bool {
        self.driver.as_ref().map(|j| !j.is_finished()).unwrap_or(false)
    }

    /// Gracefully close the connection and await the driver's shutdown,
    /// surfacing a peer-error close or a driver failure to the caller.
    pub async fn close(mut self) -> Result<(), ConnectError> {
        let (tx, rx) = oneshot::channel();
        self.commands
            .send(DriverCommand::CloseConnection {
                error: None,
                reply: tx,
            })
            .await
            .map_err(|_| ConnectError::msg(ErrorKind::NotConnected, "connection already closed"))?;
        let result = rx
            .await
            .map_err(|_| ConnectError::msg(ErrorKind::Cancelled, "driver dropped"))?;
        if let Some(join) = self.driver.take() {
            let _ = join.await;
        }
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::{TcpListener, TcpStream};

    use crate::codec::{Symbol, to_vec};
    use crate::transport::frame::FrameBody;
    use crate::types::definitions::Role;
    use crate::types::messaging::{Accepted, DeliveryState, Message, Source, Target, TargetArchetype};
    use crate::types::performatives::{
        Attach, Begin, Close, Detach, Disposition, End, Flow, Open, Performative, Transfer,
    };
    use crate::types::sasl::{SaslCode, SaslFrame, SaslMechanisms, SaslOutcome};

    /// Complete the SASL + AMQP handshakes and a `begin`, returning the framed
    /// transport positioned just after the session is mapped.
    async fn broker_handshake(stream: TcpStream) -> FramedTransport<TcpStream> {
        let mut stream = stream;
        let mut hdr = [0u8; 8];
        stream.read_exact(&mut hdr).await.unwrap();
        stream
            .write_all(&ProtocolHeader::SASL.to_bytes())
            .await
            .unwrap();
        let mut framed = FramedTransport::new(stream, 1 << 16);
        framed
            .send_sasl(&SaslFrame::Mechanisms(SaslMechanisms {
                sasl_server_mechanisms: vec![Symbol::new("ANONYMOUS")],
            }))
            .await
            .unwrap();
        let _init = framed.read_frame().await.unwrap();
        framed
            .send_sasl(&SaslFrame::Outcome(SaslOutcome {
                code: SaslCode::Ok,
                additional_data: None,
            }))
            .await
            .unwrap();
        let mut hdr2 = [0u8; 8];
        framed.stream_mut().read_exact(&mut hdr2).await.unwrap();
        framed
            .stream_mut()
            .write_all(&ProtocolHeader::AMQP.to_bytes())
            .await
            .unwrap();
        let _ = framed.read_frame().await.unwrap();
        framed
            .send_amqp(0, &Performative::Open(Open::new("broker")), None)
            .await
            .unwrap();
        let begin = framed.read_frame().await.unwrap();
        let ch = begin.channel;
        framed
            .send_amqp(
                0,
                &Performative::Begin(Begin {
                    remote_channel: Some(ch),
                    incoming_window: 100,
                    outgoing_window: 100,
                    ..Default::default()
                }),
                None,
            )
            .await
            .unwrap();
        framed
    }

    /// A minimal AMQP broker that echoes one message in each direction.
    async fn mock_broker(stream: TcpStream) {
        let mut framed = broker_handshake(stream).await;
        let mut sent_to_consumer = false;
        let mut current_delivery: Option<u32> = None;
        loop {
            let frame = match framed.read_frame().await {
                Ok(f) => f,
                Err(_) => break,
            };
            match frame.body {
                FrameBody::Amqp(Performative::Attach(a), _) => {
                    if a.role == Role::Sender {
                        // The client is producing; we are the receiver + grant credit.
                        framed
                            .send_amqp(
                                0,
                                &Performative::Attach(Attach {
                                    name: a.name.clone(),
                                    handle: 0,
                                    role: Role::Receiver,
                                    source: Some(Source::default()),
                                    target: Some(TargetArchetype::from(Target::new("queue"))),
                                    ..Default::default()
                                }),
                                None,
                            )
                            .await
                            .unwrap();
                        framed
                            .send_amqp(
                                0,
                                &Performative::Flow(Flow {
                                    next_incoming_id: Some(0),
                                    incoming_window: 100,
                                    next_outgoing_id: 0,
                                    outgoing_window: 100,
                                    handle: Some(0),
                                    delivery_count: Some(0),
                                    link_credit: Some(10),
                                    ..Default::default()
                                }),
                                None,
                            )
                            .await
                            .unwrap();
                    } else {
                        // The client is consuming; we are the sender.
                        framed
                            .send_amqp(
                                0,
                                &Performative::Attach(Attach {
                                    name: a.name.clone(),
                                    handle: 0,
                                    role: Role::Sender,
                                    source: Some(Source::new("queue")),
                                    target: Some(TargetArchetype::from(Target::default())),
                                    initial_delivery_count: Some(0),
                                    ..Default::default()
                                }),
                                None,
                            )
                            .await
                            .unwrap();
                    }
                }
                FrameBody::Amqp(Performative::Flow(f), _) => {
                    // Consumer granted us credit: deliver one message.
                    if !sent_to_consumer && f.link_credit.unwrap_or(0) > 0 {
                        sent_to_consumer = true;
                        let body = to_vec(&Message::text("from-broker"));
                        framed
                            .send_amqp(
                                0,
                                &Performative::Transfer(Transfer {
                                    handle: 0,
                                    delivery_id: Some(0),
                                    delivery_tag: Some(Bytes::from_static(b"d1")),
                                    message_format: Some(0),
                                    settled: Some(false),
                                    more: false,
                                    ..Default::default()
                                }),
                                Some(&body),
                            )
                            .await
                            .unwrap();
                    }
                }
                FrameBody::Amqp(Performative::Transfer(t), _) => {
                    // Track the delivery id (present only on the first frame) and
                    // settle once the final (more = false) frame arrives.
                    if let Some(id) = t.delivery_id {
                        current_delivery = Some(id);
                    }
                    if !t.more {
                        let id = current_delivery.take().unwrap();
                        framed
                            .send_amqp(
                                0,
                                &Performative::Disposition(Disposition {
                                    role: Role::Receiver,
                                    first: id,
                                    last: None,
                                    settled: true,
                                    state: Some(DeliveryState::Accepted(Accepted::default())),
                                    batchable: false,
                                }),
                                None,
                            )
                            .await
                            .unwrap();
                    }
                }
                FrameBody::Amqp(Performative::Detach(d), _) => {
                    framed
                        .send_amqp(
                            0,
                            &Performative::Detach(Detach {
                                handle: d.handle,
                                closed: true,
                                error: None,
                            }),
                            None,
                        )
                        .await
                        .unwrap();
                }
                FrameBody::Amqp(Performative::End(_), _) => {
                    framed
                        .send_amqp(0, &Performative::End(End { error: None }), None)
                        .await
                        .unwrap();
                }
                FrameBody::Amqp(Performative::Close(_), _) => {
                    framed
                        .send_amqp(0, &Performative::Close(Close { error: None }), None)
                        .await
                        .unwrap();
                    break;
                }
                _ => {}
            }
        }
    }

    async fn spawn_broker() -> (String, tokio::task::JoinHandle<()>) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let handle = tokio::spawn(async move {
            let (sock, _) = listener.accept().await.unwrap();
            mock_broker(sock).await;
        });
        (format!("amqp://127.0.0.1:{port}"), handle)
    }

    #[tokio::test]
    async fn end_to_end_produce() {
        let (url, broker) = spawn_broker().await;
        let conn = Connection::open(&url).await.unwrap();
        let session = conn.begin_session().await.unwrap();
        let producer = session.create_producer("queue").await.unwrap();

        let outcome = producer.send(Message::text("hello")).await.unwrap();
        assert!(matches!(outcome, DeliveryState::Accepted(_)));

        producer.detach().await.unwrap();
        session.end().await.unwrap();
        conn.close().await.unwrap();
        broker.await.unwrap();
    }

    #[tokio::test]
    async fn transparent_reconnect_survives_drop() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::time::Duration;

        // A broker that accepts repeatedly. On the FIRST connection it drops the
        // socket right after accepting one message; later connections behave
        // normally. The producer handle must survive the drop transparently.
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let url = format!("amqp://127.0.0.1:{port}");
        let conns = Arc::new(AtomicUsize::new(0));

        let broker = tokio::spawn({
            let conns = conns.clone();
            async move {
                loop {
                    let Ok((sock, _)) = listener.accept().await else { break };
                    let epoch = conns.fetch_add(1, Ordering::SeqCst);
                    // Scope `framed` so it (and its socket) is dropped the moment
                    // this connection's handling ends — that EOF is how the client
                    // observes the simulated mid-stream drop.
                    let mut framed = broker_handshake(sock).await;
                    let mut delivered = 0u32;
                    loop {
                        let frame = match framed.read_frame().await {
                            Ok(f) => f,
                            Err(_) => break,
                        };
                        match frame.body {
                            FrameBody::Amqp(Performative::Attach(a), _) => {
                                framed
                                    .send_amqp(
                                        0,
                                        &Performative::Attach(Attach {
                                            name: a.name.clone(),
                                            handle: 0,
                                            role: Role::Receiver,
                                            source: Some(Source::default()),
                                            target: Some(TargetArchetype::from(Target::new("queue"))),
                                            ..Default::default()
                                        }),
                                        None,
                                    )
                                    .await
                                    .unwrap();
                                framed
                                    .send_amqp(
                                        0,
                                        &Performative::Flow(Flow {
                                            next_incoming_id: Some(0),
                                            incoming_window: 100,
                                            next_outgoing_id: 0,
                                            outgoing_window: 100,
                                            handle: Some(0),
                                            delivery_count: Some(0),
                                            link_credit: Some(50),
                                            ..Default::default()
                                        }),
                                        None,
                                    )
                                    .await
                                    .unwrap();
                            }
                            FrameBody::Amqp(Performative::Transfer(t), _) => {
                                if let Some(id) = t.delivery_id {
                                    framed
                                        .send_amqp(
                                            0,
                                            &Performative::Disposition(Disposition {
                                                role: Role::Receiver,
                                                first: id,
                                                last: None,
                                                settled: true,
                                                state: Some(DeliveryState::Accepted(Accepted::default())),
                                                batchable: false,
                                            }),
                                            None,
                                        )
                                        .await
                                        .unwrap();
                                }
                                delivered += 1;
                                // Simulate a mid-stream drop on the first connection.
                                if epoch == 0 && delivered >= 1 {
                                    break; // drop the socket
                                }
                            }
                            FrameBody::Amqp(Performative::Detach(d), _) => {
                                framed
                                    .send_amqp(
                                        0,
                                        &Performative::Detach(Detach {
                                            handle: d.handle,
                                            closed: true,
                                            error: None,
                                        }),
                                        None,
                                    )
                                    .await
                                    .ok();
                            }
                            FrameBody::Amqp(Performative::End(_), _) => {
                                framed
                                    .send_amqp(0, &Performative::End(End { error: None }), None)
                                    .await
                                    .ok();
                            }
                            FrameBody::Amqp(Performative::Close(_), _) => {
                                framed
                                    .send_amqp(0, &Performative::Close(Close { error: None }), None)
                                    .await
                                    .ok();
                                break;
                            }
                            _ => {}
                        }
                    }
                    // Close this connection's socket now (drop EOF) and accept the
                    // next (the supervisor's reconnect).
                    drop(framed);
                }
            }
        });

        let mut config = Config::default();
        config.connection.reconnect.initial_backoff = Duration::from_millis(20);
        config.connection.reconnect.max_retries = Some(50);
        let conn = crate::api::client::ConnectionBuilder::new(&url)
            .config(config)
            .reconnecting(true)
            .connect()
            .await
            .unwrap();
        let session = conn.begin_session().await.unwrap();
        let producer = session.create_producer("queue").await.unwrap();

        // First send succeeds on the original connection.
        let o1 = producer.send(Message::text("one")).await.unwrap();
        assert!(matches!(o1, DeliveryState::Accepted(_)));

        // The broker dropped the connection; the SAME producer must keep working
        // after the supervisor transparently reconnects + re-attaches.
        let o2 = tokio::time::timeout(Duration::from_secs(5), producer.send(Message::text("two")))
            .await
            .expect("send did not survive the reconnect")
            .expect("send two");
        assert!(matches!(o2, DeliveryState::Accepted(_)));

        let o3 = tokio::time::timeout(Duration::from_secs(5), producer.send(Message::text("three")))
            .await
            .expect("third send timed out")
            .expect("send three");
        assert!(matches!(o3, DeliveryState::Accepted(_)));

        // We reconnected at least once.
        assert!(conns.load(Ordering::SeqCst) >= 2, "expected a reconnect");

        producer.detach().await.ok();
        session.end().await.ok();
        conn.close().await.ok();
        broker.abort();
    }

    #[tokio::test]
    async fn send_settled_outbox_backpressures_without_credit() {
        use std::time::Duration;
        // A broker that attaches the sender but never grants credit, so nothing
        // can be written: the bounded outbox must back-pressure rather than
        // buffer without limit.
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let url = format!("amqp://127.0.0.1:{port}");
        let broker = tokio::spawn(async move {
            let (sock, _) = listener.accept().await.unwrap();
            let mut framed = broker_handshake(sock).await;
            while let Ok(frame) = framed.read_frame().await {
                if let FrameBody::Amqp(Performative::Attach(a), _) = frame.body {
                    framed
                        .send_amqp(
                            0,
                            &Performative::Attach(Attach {
                                name: a.name.clone(),
                                handle: 0,
                                role: Role::Receiver,
                                source: Some(Source::default()),
                                target: Some(TargetArchetype::from(Target::new("queue"))),
                                ..Default::default()
                            }),
                            None,
                        )
                        .await
                        .unwrap();
                    // Deliberately grant NO link credit.
                }
            }
        });

        let mut config = Config::default();
        config.link.max_outbox = 2;
        let conn = crate::api::client::ConnectionBuilder::new(&url)
            .config(config)
            .connect()
            .await
            .unwrap();
        let session = conn.begin_session().await.unwrap();
        let producer = session.create_producer("queue").await.unwrap();

        // Two fire-and-forget sends fill the bounded outbox (unwritten: no credit).
        producer.send_settled(Message::text("a")).await.unwrap();
        producer.send_settled(Message::text("b")).await.unwrap();
        // The third must block until a slot frees — which never happens here.
        let blocked = tokio::time::timeout(
            Duration::from_millis(300),
            producer.send_settled(Message::text("c")),
        )
        .await;
        assert!(
            blocked.is_err(),
            "send_settled must back-pressure once the bounded outbox is full"
        );

        drop(producer);
        drop(session);
        drop(conn);
        broker.abort();
    }

    #[tokio::test]
    async fn metrics_are_emitted() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU64, Ordering};

        #[derive(Default)]
        struct Counters {
            frames_in: AtomicU64,
            frames_out: AtomicU64,
            sent: AtomicU64,
            settle_latencies: AtomicU64,
        }
        impl crate::observe::Metrics for Counters {
            fn on_frame_received(&self, _bytes: usize) {
                self.frames_in.fetch_add(1, Ordering::Relaxed);
            }
            fn on_frame_sent(&self, _bytes: usize) {
                self.frames_out.fetch_add(1, Ordering::Relaxed);
            }
            fn on_transfer_sent(&self) {
                self.sent.fetch_add(1, Ordering::Relaxed);
            }
            fn on_send_to_settle(&self, _latency: std::time::Duration) {
                self.settle_latencies.fetch_add(1, Ordering::Relaxed);
            }
        }

        let (url, broker) = spawn_broker().await;
        let counters = Arc::new(Counters::default());
        let conn = crate::api::client::ConnectionBuilder::new(&url)
            .metrics(counters.clone())
            .connect()
            .await
            .unwrap();
        let session = conn.begin_session().await.unwrap();
        let producer = session.create_producer("queue").await.unwrap();
        producer.send(Message::text("m")).await.unwrap();
        producer.detach().await.unwrap();
        session.end().await.unwrap();
        conn.close().await.unwrap();
        broker.await.unwrap();

        assert!(counters.frames_in.load(Ordering::Relaxed) > 0);
        assert!(counters.frames_out.load(Ordering::Relaxed) > 0);
        assert_eq!(counters.sent.load(Ordering::Relaxed), 1);
        // the send-to-settle latency metric fired once for the settled delivery
        assert_eq!(counters.settle_latencies.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn end_to_end_consume() {
        let (url, broker) = spawn_broker().await;
        let conn = Connection::open(&url).await.unwrap();
        let session = conn.begin_session().await.unwrap();
        let mut consumer = session.create_consumer("queue").await.unwrap();

        let delivery = consumer.recv().await.unwrap();
        assert_eq!(delivery.message().unwrap(), Message::text("from-broker"));
        consumer.accept(&delivery).await.unwrap();

        consumer.detach().await.unwrap();
        session.end().await.unwrap();
        conn.close().await.unwrap();
        broker.await.unwrap();
    }

    #[tokio::test]
    async fn end_to_end_produce_multiframe() {
        let (url, broker) = spawn_broker().await;
        let mut config = Config::default();
        config.connection.max_frame_size = 512; // force multi-frame splitting
        let conn = crate::api::client::ConnectionBuilder::new(&url)
            .config(config)
            .connect()
            .await
            .unwrap();
        let session = conn.begin_session().await.unwrap();
        let producer = session.create_producer("queue").await.unwrap();

        // A body well over the frame size must split into multiple transfers and
        // be reassembled by the peer.
        let big = "x".repeat(4000);
        let outcome = producer.send(Message::text(&big)).await.unwrap();
        assert!(matches!(outcome, DeliveryState::Accepted(_)));

        producer.detach().await.unwrap();
        session.end().await.unwrap();
        conn.close().await.unwrap();
        broker.await.unwrap();
    }

    #[tokio::test]
    async fn second_mode_settlement() {
        use crate::types::definitions::ReceiverSettleMode;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        let unsettled_seen = Arc::new(AtomicBool::new(false));
        let flag = unsettled_seen.clone();

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let url = format!("amqp://127.0.0.1:{port}");
        let broker = tokio::spawn(async move {
            let (sock, _) = listener.accept().await.unwrap();
            let mut framed = broker_handshake(sock).await;
            loop {
                let frame = match framed.read_frame().await {
                    Ok(f) => f,
                    Err(_) => break,
                };
                match frame.body {
                    FrameBody::Amqp(Performative::Attach(a), _) => {
                        framed
                            .send_amqp(
                                0,
                                &Performative::Attach(Attach {
                                    name: a.name.clone(),
                                    handle: 0,
                                    role: Role::Sender,
                                    rcv_settle_mode: ReceiverSettleMode::Second,
                                    source: Some(Source::new("queue")),
                                    target: Some(TargetArchetype::from(Target::default())),
                                    initial_delivery_count: Some(0),
                                    ..Default::default()
                                }),
                                None,
                            )
                            .await
                            .unwrap();
                    }
                    FrameBody::Amqp(Performative::Flow(f), _) => {
                        if f.link_credit.unwrap_or(0) > 0 {
                            let body = to_vec(&Message::text("second"));
                            framed
                                .send_amqp(
                                    0,
                                    &Performative::Transfer(Transfer {
                                        handle: 0,
                                        delivery_id: Some(0),
                                        delivery_tag: Some(Bytes::from_static(b"d")),
                                        message_format: Some(0),
                                        settled: Some(false),
                                        more: false,
                                        ..Default::default()
                                    }),
                                    Some(&body),
                                )
                                .await
                                .unwrap();
                        }
                    }
                    FrameBody::Amqp(Performative::Disposition(d), _) => {
                        // In `second` mode the consumer proposes the outcome unsettled.
                        if !d.settled {
                            flag.store(true, Ordering::Relaxed);
                        }
                        // The sender then confirms (settled) to complete settlement.
                        framed
                            .send_amqp(
                                0,
                                &Performative::Disposition(Disposition {
                                    role: Role::Sender,
                                    first: d.first,
                                    last: d.last,
                                    settled: true,
                                    state: Some(DeliveryState::Accepted(Accepted::default())),
                                    batchable: false,
                                }),
                                None,
                            )
                            .await
                            .unwrap();
                    }
                    FrameBody::Amqp(Performative::Detach(d), _) => {
                        framed
                            .send_amqp(
                                0,
                                &Performative::Detach(Detach {
                                    handle: d.handle,
                                    closed: true,
                                    error: None,
                                }),
                                None,
                            )
                            .await
                            .unwrap();
                    }
                    FrameBody::Amqp(Performative::End(_), _) => {
                        framed
                            .send_amqp(0, &Performative::End(End { error: None }), None)
                            .await
                            .unwrap();
                    }
                    FrameBody::Amqp(Performative::Close(_), _) => {
                        framed
                            .send_amqp(0, &Performative::Close(Close { error: None }), None)
                            .await
                            .unwrap();
                        break;
                    }
                    _ => {}
                }
            }
        });

        let mut config = Config::default();
        config.link.receiver_settle_mode = ReceiverSettleMode::Second;
        let conn = crate::api::client::ConnectionBuilder::new(&url)
            .config(config)
            .connect()
            .await
            .unwrap();
        let session = conn.begin_session().await.unwrap();
        let mut consumer = session.create_consumer("queue").await.unwrap();
        let delivery = consumer.recv().await.unwrap();
        assert_eq!(delivery.message().unwrap(), Message::text("second"));
        consumer.accept(&delivery).await.unwrap();

        consumer.detach().await.unwrap();
        session.end().await.unwrap();
        conn.close().await.unwrap();
        broker.await.unwrap();

        assert!(
            unsettled_seen.load(Ordering::Relaxed),
            "a second-mode consumer must send an unsettled disposition first"
        );
    }
}