azservicebus 0.25.1

An unofficial AMQP 1.0 rust client for Azure Service Bus
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
//! Error types for AMQP operations

use fe2o3_amqp::{
    connection::{self, OpenError},
    link::{
        DetachError, DetachThenResumeReceiverError, DetachThenResumeSenderError,
        IllegalLinkStateError, LinkStateError, ReceiverAttachError, ReceiverResumeErrorKind,
        RecvError, SendError, SenderAttachError, SenderResumeErrorKind,
    },
    session::{self, BeginError},
};
use fe2o3_amqp_management::error::{AttachError, Error as ManagementError};
use fe2o3_amqp_types::messaging::{Modified, Rejected, Released};
use timer_kit::error::Elapsed;

use crate::{
    primitives::{
        error::ClientDisposedError,
        service_bus_retry_policy::{
            should_try_recover_from_management_error, ServiceBusRetryPolicyError,
        },
    },
    util::IntoAzureCoreError,
    ServiceBusMessage,
};

// Conditional import for docs.rs
#[cfg(docsrs)]
use crate::{ServiceBusPeekedMessage, ServiceBusReceivedMessage};

#[derive(Debug, thiserror::Error)]
pub(crate) enum AmqpConnectionScopeError {
    #[error(transparent)]
    Open(#[from] OpenError),

    #[error(transparent)]
    WebSocket(#[from] fe2o3_amqp_ws::Error),

    #[error(transparent)]
    Begin(#[from] BeginError),

    #[error(transparent)]
    ManagementLinkAttach(#[from] AttachError),

    #[error("The connection scope is disposed")]
    ScopeDisposed,

    #[cfg(feature = "transaction")]
    #[error(transparent)]
    ControllerAttach(SenderAttachError),
}

/// Error with AMQP client
#[derive(Debug, thiserror::Error)]
pub(crate) enum AmqpClientError {
    /// Error parsing the URL
    #[error(transparent)]
    UrlParseError(#[from] url::ParseError),

    /// Error with opening the connection
    #[error(transparent)]
    Open(#[from] OpenError),

    /// Error with establishing the WebSocket transport
    #[error(transparent)]
    WebSocket(#[from] fe2o3_amqp_ws::Error),

    /// Operation timed out
    #[error(transparent)]
    Elapsed(#[from] Elapsed),

    /// Error beginning the AMQP session
    #[error(transparent)]
    Begin(#[from] BeginError),

    #[error(transparent)]
    ManagementLinkAttach(#[from] AttachError),

    /// Error closing the AMQP client
    #[error(transparent)]
    Dispose(#[from] DisposeError),

    /// Client is already disposed
    #[error("The client is disposed")]
    ClientDisposed(#[from] ClientDisposedError),

    /// Error with attaching attaching a control link
    #[cfg(feature = "transaction")]
    #[error(transparent)]
    ControllerAttach(SenderAttachError),
}

impl From<AmqpClientError> for azure_core::Error {
    fn from(value: AmqpClientError) -> Self {
        match value {
            AmqpClientError::UrlParseError(error) => error.into(),
            AmqpClientError::Open(error) => error.into_azure_core_error(),
            AmqpClientError::WebSocket(error) => error.into_azure_core_error(),
            AmqpClientError::Elapsed(error) => error.into_azure_core_error(),
            AmqpClientError::Begin(error) => error.into_azure_core_error(),
            AmqpClientError::ManagementLinkAttach(error) => error.into_azure_core_error(),
            AmqpClientError::Dispose(error) => error.into(),
            AmqpClientError::ClientDisposed(error) => error.into(),
            #[cfg(feature = "transaction")]
            AmqpClientError::ControllerAttach(error) => error.into_azure_core_error(),
        }
    }
}

impl From<AmqpConnectionScopeError> for AmqpClientError {
    fn from(err: AmqpConnectionScopeError) -> Self {
        match err {
            AmqpConnectionScopeError::Open(err) => Self::Open(err),
            AmqpConnectionScopeError::WebSocket(err) => Self::WebSocket(err),
            AmqpConnectionScopeError::Begin(err) => Self::Begin(err),
            AmqpConnectionScopeError::ManagementLinkAttach(err) => Self::ManagementLinkAttach(err),
            AmqpConnectionScopeError::ScopeDisposed => Self::ClientDisposed(ClientDisposedError),
            #[cfg(feature = "transaction")]
            AmqpConnectionScopeError::ControllerAttach(err) => Self::ControllerAttach(err),
        }
    }
}

/// The value exceeds the maximum length allowed
#[derive(Debug)]
pub struct MaxLengthExceededError {
    pub(crate) message: String,
}

impl MaxLengthExceededError {
    pub(crate) fn new(actual_length: usize, max_length: usize) -> Self {
        Self {
            message: format!(
                "The actual length {} exceeds the maximum length {}",
                actual_length, max_length
            ),
        }
    }
}

impl std::fmt::Display for MaxLengthExceededError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MaxLengthExceededError: {}", self.message)
    }
}

impl std::error::Error for MaxLengthExceededError {}

/// Error setting the message ID
#[derive(Debug, thiserror::Error)]
pub enum SetMessageIdError {
    /// Value cannot be empty
    #[error("Value cannot be empty")]
    Empty,

    /// Max allowed length exceeded
    #[error(transparent)]
    MaxLengthExceeded(#[from] MaxLengthExceededError),
}

/// Error setting the partition key
#[derive(Debug, thiserror::Error)]
pub enum SetPartitionKeyError {
    /// Max allowed length exceeded
    #[error(transparent)]
    MaxLengthExceeded(#[from] MaxLengthExceededError),

    /// PartitionKey cannot be set to a different value from SessionId
    #[error("PartitionKey cannot be set to a different value from SessionId")]
    PartitionKeyAndSessionIdAreDifferent,
}

/// Maximum allowed TTL exceeded
#[derive(Debug)]
pub struct MaxAllowedTtlExceededError {}

impl std::fmt::Display for MaxAllowedTtlExceededError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "MaxAllowedTtlExceededError: The maximum allowed TTL is u32::MAX milliseconds"
        )
    }
}

impl std::error::Error for MaxAllowedTtlExceededError {}

/// The message carried in `ServiceBusReceivedMessage` or `ServiceBusPeekedMessage` is a raw AMQP
/// message. Please use [`ServiceBusReceivedMessage::raw_amqp_message`] or
/// [`ServiceBusPeekedMessage::raw_amqp_message`] to access the raw AMQP message body.
#[derive(Debug, Clone)]
pub struct RawAmqpMessageError {}

impl std::fmt::Display for RawAmqpMessageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "RawAmqpMessageError: The message is a raw AMQP message")
    }
}

impl std::error::Error for RawAmqpMessageError {}

/// The sent message is not accepted by the service
#[derive(Debug, thiserror::Error)]
pub enum NotAcceptedError {
    /// 3.4.2 Rejected
    #[error("Rejceted: {:?}", .0)]
    Rejected(Rejected),

    /// 3.4.4 Released
    #[error("Released: {:?}", .0)]
    Released(Released),

    /// 3.4.5 Modified
    #[error("Modified: {:?}", .0)]
    Modified(Modified),
}

/// Error closing the AMQP connection and AMQP session
#[derive(Debug, thiserror::Error)]
pub(crate) enum DisposeError {
    /// Error closing the AMQP session
    #[error(transparent)]
    SessionCloseError(#[from] session::Error),

    /// Error closing the AMQP connection
    #[error(transparent)]
    ConnectionCloseError(#[from] connection::Error),
}

impl From<DisposeError> for azure_core::Error {
    fn from(value: DisposeError) -> Self {
        match value {
            DisposeError::SessionCloseError(error) => error.into_azure_core_error(),
            DisposeError::ConnectionCloseError(error) => error.into_azure_core_error(),
        }
    }
}

/// Error opening a management link
#[derive(Debug, thiserror::Error)]
pub(crate) enum OpenMgmtLinkError {
    /// Connection scope is disposed
    #[error("Scope is disposed")]
    ConnectionScopeDisposed,

    /// Error attaching the management link
    #[error(transparent)]
    Attach(#[from] AttachError),

    /// Error with CBS auth the management link
    #[error(transparent)]
    CbsAuth(#[from] CbsAuthError),
}

/// Error opening a sender link
#[derive(Debug, thiserror::Error)]
pub(crate) enum OpenSenderError {
    /// Connection scope is disposed
    #[error("The connection scope is disposed")]
    ConnectionScopeDisposed,

    /// Error attaching the management link
    #[error(transparent)]
    ManagementLinkAttach(#[from] AttachError),

    /// Error attaching the sender link
    #[error(transparent)]
    SenderAttach(#[from] SenderAttachError),

    /// Error with CBS auth the sender link
    #[error(transparent)]
    CbsAuth(#[from] CbsAuthError),
}

impl From<OpenSenderError> for azure_core::Error {
    fn from(value: OpenSenderError) -> Self {
        match value {
            OpenSenderError::ConnectionScopeDisposed => ClientDisposedError.into(),
            OpenSenderError::ManagementLinkAttach(error) => error.into_azure_core_error(),
            OpenSenderError::SenderAttach(error) => error.into_azure_core_error(),
            OpenSenderError::CbsAuth(error) => error.into(),
        }
    }
}

impl From<OpenMgmtLinkError> for OpenSenderError {
    fn from(err: OpenMgmtLinkError) -> Self {
        match err {
            OpenMgmtLinkError::ConnectionScopeDisposed => OpenSenderError::ConnectionScopeDisposed,
            OpenMgmtLinkError::Attach(err) => OpenSenderError::ManagementLinkAttach(err),
            OpenMgmtLinkError::CbsAuth(err) => OpenSenderError::CbsAuth(err),
        }
    }
}

/// Error recovering a sender link
#[derive(Debug, thiserror::Error)]
pub(crate) enum RecoverSenderError {
    /// Connection scope is disposed
    #[error("The connection scope is disposed")]
    ConnectionScopeDisposed,

    #[error(transparent)]
    Open(#[from] OpenError),

    #[error(transparent)]
    WebSocket(#[from] fe2o3_amqp_ws::Error),

    #[error(transparent)]
    Begin(#[from] BeginError),

    /// Error attaching the management link
    #[error(transparent)]
    ManagementLinkAttach(#[from] AttachError),

    /// Error detaching the current sender link
    #[error(transparent)]
    SenderDetach(#[from] DetachError),

    /// Error attaching the sender link to new session
    #[error(transparent)]
    SenderResume(#[from] SenderResumeErrorKind),

    /// Error with CBS auth the recovering sender link
    #[error(transparent)]
    CbsAuth(#[from] CbsAuthError),

    /// Error attaching the controller
    #[cfg(feature = "transaction")]
    #[error(transparent)]
    ControllerAttach(SenderAttachError),
}

impl ServiceBusRetryPolicyError for RecoverSenderError {
    fn should_try_recover(&self) -> bool {
        // This error is only returned if the recover operation fails.
        false
    }

    fn is_scope_disposed(&self) -> bool {
        matches!(self, RecoverSenderError::ConnectionScopeDisposed)
    }
}

impl From<AmqpConnectionScopeError> for RecoverSenderError {
    fn from(value: AmqpConnectionScopeError) -> Self {
        match value {
            AmqpConnectionScopeError::Open(err) => err.into(),
            AmqpConnectionScopeError::WebSocket(err) => err.into(),
            AmqpConnectionScopeError::Begin(err) => err.into(),
            AmqpConnectionScopeError::ManagementLinkAttach(err) => err.into(),
            AmqpConnectionScopeError::ScopeDisposed => Self::ConnectionScopeDisposed,
            #[cfg(feature = "transaction")]
            AmqpConnectionScopeError::ControllerAttach(err) => Self::ControllerAttach(err),
        }
    }
}

impl From<DetachThenResumeSenderError> for RecoverSenderError {
    fn from(value: DetachThenResumeSenderError) -> Self {
        match value {
            DetachThenResumeSenderError::Detach(err) => RecoverSenderError::SenderDetach(err),
            DetachThenResumeSenderError::Resume(err) => RecoverSenderError::SenderResume(err),
        }
    }
}

impl From<OpenMgmtLinkError> for RecoverSenderError {
    fn from(err: OpenMgmtLinkError) -> Self {
        match err {
            OpenMgmtLinkError::ConnectionScopeDisposed => {
                RecoverSenderError::ConnectionScopeDisposed
            }
            OpenMgmtLinkError::Attach(err) => RecoverSenderError::ManagementLinkAttach(err),
            OpenMgmtLinkError::CbsAuth(err) => RecoverSenderError::CbsAuth(err),
        }
    }
}

/// Error opening a receiver link
#[derive(Debug, thiserror::Error)]
pub(crate) enum OpenReceiverError {
    /// Connection scope is disposed
    #[error("The connection scope is disposed")]
    ConnectionScopeDisposed,

    /// Error attaching the management link
    #[error(transparent)]
    ManagementLinkAttach(#[from] AttachError),

    /// Error attaching the receiver link
    #[error(transparent)]
    ReceiverAttach(#[from] ReceiverAttachError),

    /// Error with CBS auth the receiver link
    #[error(transparent)]
    CbsAuth(#[from] CbsAuthError),
}

impl From<OpenReceiverError> for azure_core::Error {
    fn from(value: OpenReceiverError) -> Self {
        match value {
            OpenReceiverError::ConnectionScopeDisposed => ClientDisposedError.into(),
            OpenReceiverError::ManagementLinkAttach(error) => error.into_azure_core_error(),
            OpenReceiverError::ReceiverAttach(error) => error.into_azure_core_error(),
            OpenReceiverError::CbsAuth(error) => error.into(),
        }
    }
}

impl From<OpenMgmtLinkError> for OpenReceiverError {
    fn from(err: OpenMgmtLinkError) -> Self {
        match err {
            OpenMgmtLinkError::ConnectionScopeDisposed => {
                OpenReceiverError::ConnectionScopeDisposed
            }
            OpenMgmtLinkError::Attach(err) => OpenReceiverError::ManagementLinkAttach(err),
            OpenMgmtLinkError::CbsAuth(err) => OpenReceiverError::CbsAuth(err),
        }
    }
}

/// Error recovering a receiver link
#[derive(Debug, thiserror::Error)]
pub(crate) enum RecoverReceiverError {
    /// Connection scope is disposed
    #[error("The connection scope is disposed")]
    ConnectionScopeDisposed,

    #[error(transparent)]
    Open(#[from] OpenError),

    #[error(transparent)]
    WebSocket(#[from] fe2o3_amqp_ws::Error),

    #[error(transparent)]
    Begin(#[from] BeginError),

    /// Error attaching the management link
    #[error(transparent)]
    ManagementLinkAttach(#[from] AttachError),

    /// Error detaching the current receiver link
    #[error(transparent)]
    ReceiverDetach(#[from] DetachError),

    /// Error attaching the receiver link to new session
    #[error(transparent)]
    ReceiverResume(#[from] ReceiverResumeErrorKind),

    /// Error with CBS auth the recovering receiver link
    #[error(transparent)]
    CbsAuth(#[from] CbsAuthError),

    /// Error attaching the controller
    #[cfg(feature = "transaction")]
    #[error(transparent)]
    ControllerAttach(SenderAttachError),
}

impl From<AmqpConnectionScopeError> for RecoverReceiverError {
    fn from(value: AmqpConnectionScopeError) -> Self {
        match value {
            AmqpConnectionScopeError::Open(err) => err.into(),
            AmqpConnectionScopeError::WebSocket(err) => err.into(),
            AmqpConnectionScopeError::Begin(err) => err.into(),
            AmqpConnectionScopeError::ManagementLinkAttach(err) => err.into(),
            AmqpConnectionScopeError::ScopeDisposed => Self::ConnectionScopeDisposed,
            #[cfg(feature = "transaction")]
            AmqpConnectionScopeError::ControllerAttach(err) => Self::ControllerAttach(err),
        }
    }
}

impl ServiceBusRetryPolicyError for RecoverReceiverError {
    fn should_try_recover(&self) -> bool {
        // This error is only returned if the recover operation fails.
        false
    }

    fn is_scope_disposed(&self) -> bool {
        matches!(self, RecoverReceiverError::ConnectionScopeDisposed)
    }
}

impl From<DetachThenResumeReceiverError> for RecoverReceiverError {
    fn from(value: DetachThenResumeReceiverError) -> Self {
        match value {
            DetachThenResumeReceiverError::Detach(err) => RecoverReceiverError::ReceiverDetach(err),
            DetachThenResumeReceiverError::Resume(err) => RecoverReceiverError::ReceiverResume(err),
        }
    }
}

impl From<OpenMgmtLinkError> for RecoverReceiverError {
    fn from(err: OpenMgmtLinkError) -> Self {
        match err {
            OpenMgmtLinkError::ConnectionScopeDisposed => {
                RecoverReceiverError::ConnectionScopeDisposed
            }
            OpenMgmtLinkError::Attach(err) => RecoverReceiverError::ManagementLinkAttach(err),
            OpenMgmtLinkError::CbsAuth(err) => RecoverReceiverError::CbsAuth(err),
        }
    }
}

/// Error opening a rule manager
#[derive(Debug, thiserror::Error)]
pub(crate) enum OpenRuleManagerError {
    /// Connection scope is disposed
    #[error("The connection scope is disposed")]
    ConnectionScopeDisposed,

    /// Error attaching the management link
    #[error(transparent)]
    ManagementLinkAttach(#[from] AttachError),

    /// Error with CBS auth the rule manager
    #[error(transparent)]
    CbsAuth(#[from] CbsAuthError),
}

impl From<OpenRuleManagerError> for azure_core::Error {
    fn from(value: OpenRuleManagerError) -> Self {
        match value {
            OpenRuleManagerError::ConnectionScopeDisposed => ClientDisposedError.into(),
            OpenRuleManagerError::ManagementLinkAttach(error) => error.into_azure_core_error(),
            OpenRuleManagerError::CbsAuth(error) => error.into(),
        }
    }
}

impl ServiceBusRetryPolicyError for OpenRuleManagerError {
    fn should_try_recover(&self) -> bool {
        false
    }

    fn is_scope_disposed(&self) -> bool {
        matches!(self, OpenRuleManagerError::ConnectionScopeDisposed)
    }
}

impl From<OpenMgmtLinkError> for OpenRuleManagerError {
    fn from(err: OpenMgmtLinkError) -> Self {
        match err {
            OpenMgmtLinkError::ConnectionScopeDisposed => {
                OpenRuleManagerError::ConnectionScopeDisposed
            }
            OpenMgmtLinkError::Attach(err) => OpenRuleManagerError::ManagementLinkAttach(err),
            OpenMgmtLinkError::CbsAuth(err) => OpenRuleManagerError::CbsAuth(err),
        }
    }
}

/// Error sending message to the service
#[derive(Debug, thiserror::Error)]
pub(crate) enum AmqpSendError {
    /// Error with sending the message
    #[error(transparent)]
    Send(#[from] fe2o3_amqp::link::SendError),

    /// The sent message is not accepted by the service
    #[error(transparent)]
    NotAccepted(#[from] NotAcceptedError),

    /// The operation timed out
    #[error(transparent)]
    Elapsed(#[from] Elapsed),
}

impl ServiceBusRetryPolicyError for LinkStateError {
    fn should_try_recover(&self) -> bool {
        matches!(
            self,
            LinkStateError::IllegalState
                | LinkStateError::IllegalSessionState
                | LinkStateError::ExpectImmediateDetach
                | LinkStateError::RemoteDetached
        )
    }

    fn is_scope_disposed(&self) -> bool {
        false
    }
}

impl ServiceBusRetryPolicyError for DetachError {
    fn should_try_recover(&self) -> bool {
        matches!(
            self,
            DetachError::IllegalState
                | DetachError::IllegalSessionState
                | DetachError::RemoteDetachedWithError(_)
                | DetachError::DetachedByRemote
        )
    }

    fn is_scope_disposed(&self) -> bool {
        false
    }
}

impl ServiceBusRetryPolicyError for SendError {
    fn should_try_recover(&self) -> bool {
        match self {
            SendError::LinkStateError(err) => err.should_try_recover(),
            SendError::Detached(err) => err.should_try_recover(),
            _ => false,
        }
    }

    fn is_scope_disposed(&self) -> bool {
        false
    }
}

impl ServiceBusRetryPolicyError for AmqpSendError {
    fn should_try_recover(&self) -> bool {
        match self {
            Self::Send(err) => err.should_try_recover(),
            Self::Elapsed(_) => true,
            _ => false,
        }
    }

    fn is_scope_disposed(&self) -> bool {
        false
    }
}

/// Error receiving message from the service
#[derive(Debug, thiserror::Error)]
pub(crate) enum AmqpRecvError {
    /// Error with receiving the message
    #[error(transparent)]
    Recv(#[from] RecvError),

    /// Wrong link state
    #[error(transparent)]
    LinkState(#[from] IllegalLinkStateError),

    /// The operation timed out
    #[error(transparent)]
    Elapsed(#[from] Elapsed),

    /// The lock token is not found in the message
    #[error("A valid lock token was not found in the message")]
    LockTokenNotFound,
}

impl ServiceBusRetryPolicyError for AmqpRecvError {
    fn should_try_recover(&self) -> bool {
        matches!(
            self,
            Self::Recv(RecvError::LinkStateError(
                LinkStateError::IllegalState
                    | LinkStateError::IllegalSessionState
                    | LinkStateError::ExpectImmediateDetach
                    | LinkStateError::RemoteDetached
            )) | Self::LinkState(_)
        )
    }

    fn is_scope_disposed(&self) -> bool {
        false
    }
}

/// Error with message disposition
#[derive(Debug, thiserror::Error)]
pub(crate) enum AmqpDispositionError {
    /// Error with the link state
    #[error(transparent)]
    IllegalState(#[from] IllegalLinkStateError),

    /// Error with the request-response operation on the management link
    #[error(transparent)]
    RequestResponse(#[from] ManagementError),

    /// The operation timed out
    #[error(transparent)]
    Elapsed(#[from] Elapsed),
}

impl ServiceBusRetryPolicyError for AmqpDispositionError {
    fn should_try_recover(&self) -> bool {
        match self {
            Self::IllegalState(IllegalLinkStateError::IllegalSessionState) => true,
            Self::IllegalState(IllegalLinkStateError::IllegalState) => false,
            Self::RequestResponse(err) => should_try_recover_from_management_error(err),
            Self::Elapsed(_) => false,
        }
    }

    fn is_scope_disposed(&self) -> bool {
        false
    }
}

/// Error with request-response operation
#[derive(Debug, thiserror::Error)]
pub(crate) enum AmqpRequestResponseError {
    /// Error with the request-response operation on the management link
    #[error(transparent)]
    RequestResponse(#[from] ManagementError),

    /// The operation timed out
    #[error(transparent)]
    Elapsed(#[from] Elapsed),
}

impl ServiceBusRetryPolicyError for AmqpRequestResponseError {
    fn should_try_recover(&self) -> bool {
        match self {
            Self::RequestResponse(err) => should_try_recover_from_management_error(err),
            Self::Elapsed(_) => false,
        }
    }

    fn is_scope_disposed(&self) -> bool {
        false
    }
}

impl From<serde_amqp::Error> for AmqpRequestResponseError {
    fn from(_: serde_amqp::Error) -> Self {
        Self::RequestResponse(ManagementError::DecodeError(None))
    }
}

/// Error with CBS auth
#[derive(Debug, thiserror::Error)]
pub(crate) enum CbsAuthError {
    /// Error with the token provider
    #[error(transparent)]
    TokenCredential(#[from] azure_core::Error),

    /// Error with the CBS link
    #[error(transparent)]
    Cbs(#[from] ManagementError),
}

impl From<CbsAuthError> for azure_core::Error {
    fn from(value: CbsAuthError) -> Self {
        match value {
            CbsAuthError::TokenCredential(error) => error,
            CbsAuthError::Cbs(error) => error.into_azure_core_error(),
        }
    }
}

/// Error with adding a message to a batch
#[derive(Debug, thiserror::Error)]
pub enum TryAddMessageError {
    /// The message is too large to fit in a batch
    #[error("Message is too large to fit in a batch")]
    BatchFull(ServiceBusMessage),

    /// The message cannot be serialized
    #[error("Cannot serialize message")]
    Codec {
        /// The error from the codec
        source: serde_amqp::Error,
        /// The message that could not be serialized
        message: ServiceBusMessage,
    },
}

/// The requested message batch size is out of range
#[derive(Debug)]
pub struct RequestedSizeOutOfRange {}

impl std::fmt::Display for RequestedSizeOutOfRange {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Requested size is out of range")
    }
}

impl std::error::Error for RequestedSizeOutOfRange {}

/// The correlation rule filter must have at least one non-empty entry
#[derive(Debug, Clone, thiserror::Error)]
pub enum CorrelationFilterError {
    /// The correlation filter must have at least one non-empty entry
    #[error("Correlation filter must include at least one entry")]
    EmptyFilter,
}

/// The CBS event loop has stopped
#[derive(Debug)]
pub(crate) struct AmqpCbsEventLoopStopped {}

impl std::fmt::Display for AmqpCbsEventLoopStopped {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "The CBS event loop has stopped")
    }
}

impl std::error::Error for AmqpCbsEventLoopStopped {}

/// Error with creating a rule
#[derive(Debug, thiserror::Error)]
pub enum CreateRuleError {
    /// The correlation filter must have at least one entry
    #[error("The correlation filter must have at least one entry")]
    EmptyCorrelationFilter,

    /// Error while performing request/response operation
    #[error(transparent)]
    RequestResponse(#[from] ManagementError),

    /// Operation timed out
    #[error(transparent)]
    Elapsed(#[from] Elapsed),

    /// Connection scope is disposed
    #[error("Connection scope is disposed")]
    ConnectionScopeDisposed,
}

impl From<CorrelationFilterError> for CreateRuleError {
    fn from(err: CorrelationFilterError) -> Self {
        match err {
            CorrelationFilterError::EmptyFilter => Self::EmptyCorrelationFilter,
        }
    }
}

impl From<AmqpRequestResponseError> for CreateRuleError {
    fn from(err: AmqpRequestResponseError) -> Self {
        match err {
            AmqpRequestResponseError::RequestResponse(err) => Self::RequestResponse(err),
            AmqpRequestResponseError::Elapsed(err) => Self::Elapsed(err),
        }
    }
}

impl ServiceBusRetryPolicyError for CreateRuleError {
    fn should_try_recover(&self) -> bool {
        match self {
            Self::RequestResponse(err) => should_try_recover_from_management_error(err),
            Self::Elapsed(_) => false,
            Self::ConnectionScopeDisposed => false,
            Self::EmptyCorrelationFilter => false,
        }
    }

    fn is_scope_disposed(&self) -> bool {
        matches!(self, Self::ConnectionScopeDisposed)
    }
}