azure_messaging_eventhubs 0.16.0

Rust client for Azure Eventhubs Service
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
// Copyright (c) Microsoft Corporation. All Rights reserved
// Licensed under the MIT license.

#![doc = include_str!("README.md")]
/// Receive messages from a partition.
pub(crate) mod event_receiver;

use crate::{
    common::{recoverable::RecoverableConnection, ManagementInstance},
    error::Result,
    models::{ConsumerClientDetails, EventHubPartitionProperties, EventHubProperties},
    EventHubsError, RetryOptions,
};
use azure_core::{credentials::TokenCredential, http::Url, time::Duration, Uuid};
#[cfg(test)]
use azure_core_amqp::AmqpError;
use azure_core_amqp::{
    message::AmqpSourceFilter, AmqpDescribed, AmqpOrderedMap, AmqpReceiverOptions, AmqpSource,
    AmqpSymbol, AmqpTransport, AmqpValue, ReceiverCreditMode,
};
pub use event_receiver::EventReceiver;
use std::{
    default::Default,
    fmt::Debug,
    sync::Arc,
    time::{SystemTime, UNIX_EPOCH},
};
use tracing::{info, trace};

/// A client that can be used to receive events from an Event Hub.
pub struct ConsumerClient {
    recoverable_connection: Arc<RecoverableConnection>,
    consumer_group: String,
    eventhub: String,
    endpoint: Url,
    // The instance ID to set.
    instance_id: Option<String>,
}

// Clippy complains if a method has too many parameters, so we put some of the
// parameters into a private client options structure.
struct ConsumerClientOptions {
    application_id: Option<String>,
    instance_id: Option<String>,
    retry_options: Option<RetryOptions>,
    custom_endpoint: Option<Url>,
    cbs_token_type: Option<&'static str>,
    transport: AmqpTransport,
}

impl ConsumerClient {
    /// Builds a new [`ConsumerClient`] instance with the specified parameters.
    ///
    /// This function returns a builder which enables creation of a new [`ConsumerClient`]
    /// instance with the specified parameters.
    ///
    ///
    /// # Returns
    ///
    /// A new [`builders::ConsumerClientBuilder`] instance which can be used to create and open a consumer client.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use azure_messaging_eventhubs::ConsumerClient;
    /// use azure_identity::DeveloperToolsCredential;
    ///
    ///     let my_credential = DeveloperToolsCredential::new(None)?;
    /// let consumer = ConsumerClient::builder()
    ///    .open("my_namespace", "my_eventhub".to_string(), my_credential.clone()).await?;
    /// # Ok(())}
    /// ```
    ///
    pub fn builder() -> builders::ConsumerClientBuilder {
        builders::ConsumerClientBuilder::new()
    }

    fn new(
        fully_qualified_namespace: &str,
        eventhub_name: String,
        consumer_group: Option<String>,
        credential: Arc<dyn TokenCredential>,
        options: ConsumerClientOptions,
    ) -> Result<Self> {
        let consumer_group = consumer_group.unwrap_or("$Default".into());
        let url = format!(
            "amqps://{}/{}/ConsumerGroups/{}",
            fully_qualified_namespace, eventhub_name, consumer_group
        );
        let url = Url::parse(&url).map_err(azure_core::Error::from)?;

        trace!("Creating consumer client for {url}.");
        let retry_options = options.retry_options.unwrap_or_default();
        Ok(Self {
            instance_id: options.instance_id,
            recoverable_connection: RecoverableConnection::new(
                url.clone(),
                options.application_id,
                options.custom_endpoint,
                options.transport,
                credential,
                retry_options,
                options.cbs_token_type,
            ),
            eventhub: eventhub_name,
            endpoint: url,
            consumer_group,
        })
    }

    /// Closes the connection to the Event Hub.
    ///
    /// This method closes the connection to the Event Hubs instance associated with the [`ConsumerClient`].
    /// It returns a [`Result`] indicating whether the operation was successful or not.
    ///
    /// Note that closing a consumer will cancel all outstanding receive requests.
    ///
    /// # Returns
    ///
    /// A [`Result`] indicating whether the operation was successful or not.
    ///
    /// # Examples
    ///
    /// ``` no_run
    /// use azure_messaging_eventhubs::ConsumerClient;
    /// use azure_identity::DeveloperToolsCredential;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let my_credential = DeveloperToolsCredential::new(None).unwrap();
    ///     let consumer = ConsumerClient::builder()
    ///         .open("my_namespace", "my_eventhub".to_string(), my_credential).await.unwrap();
    ///
    ///     let result = consumer.close().await;
    ///
    ///     match result {
    ///         Ok(_) => {
    ///             // Connection closed successfully
    ///             println!("Connection closed successfully");
    ///         }
    ///         Err(err) => {
    ///             // Handle the error
    ///             eprintln!("Error closing connection: {:?}", err);
    ///         }
    ///     }
    /// }
    /// ```
    pub async fn close(self) -> Result<()> {
        let connection_id = self.recoverable_connection.get_connection_id().to_string();
        trace!(
            connection_id = %connection_id,
            source_url = %self.endpoint,
            "Closing consumer client."
        );
        // The close does not need exclusive ownership of the connection. A
        // handle that the caller still holds, such as an `EventReceiver`, used
        // to make this method report an error and leave the connection open
        // with no owner, because `Drop` does not close it. The connection now
        // records the close, so such a handle fails on its next call instead of
        // opening a second connection.
        self.recoverable_connection.close_connection().await?;
        trace!(
            connection_id = %connection_id,
            source_url = %self.endpoint,
            "Closed consumer connection."
        );
        Ok(())
    }

    /// Forces an error on the connection.
    #[cfg(test)]
    pub fn force_error(&self, error: AmqpError) -> Result<()> {
        self.recoverable_connection.force_error(error)
    }

    /// Builds a client that has not opened a connection.
    ///
    /// The public builder opens the connection, so a test that only needs a
    /// client value cannot use it. `RecoverableConnection` connects on demand,
    /// so this client reaches the service only when the test asks it to.
    #[cfg(test)]
    pub(crate) fn new_unconnected(
        fully_qualified_namespace: &str,
        eventhub_name: &str,
        credential: Arc<dyn TokenCredential>,
    ) -> Result<Self> {
        Self::new(
            fully_qualified_namespace,
            eventhub_name.to_string(),
            None,
            credential,
            ConsumerClientOptions {
                application_id: None,
                instance_id: None,
                retry_options: None,
                custom_endpoint: None,
                cbs_token_type: None,
                transport: AmqpTransport::default(),
            },
        )
    }

    /// Returns the connection that this client shares with the handles it
    /// hands out. A test uses it to read the state of the connection after
    /// `close` consumes the client.
    #[cfg(test)]
    pub(crate) fn recoverable_connection(&self) -> Arc<RecoverableConnection> {
        self.recoverable_connection.clone()
    }

    /// Retrieves the details of the consumer client.
    ///
    /// This function retrieves the details of the consumer client associated with the [`ConsumerClient`].
    pub(crate) fn get_details(&self) -> Result<ConsumerClientDetails> {
        Ok(ConsumerClientDetails {
            eventhub_name: self.eventhub.clone(),
            consumer_group: self.consumer_group.clone(),
            fully_qualified_namespace: self
                .endpoint
                .host()
                .ok_or_else(|| {
                    EventHubsError::with_message("Could not find host in consumer client")
                })?
                .to_string(),
            client_id: self.recoverable_connection.get_connection_id().to_string(),
        })
    }

    /// Attaches a message receiver to a specific partition of the Event Hub.
    ///
    /// This function establishes a connection to the specified partition of the Event Hubs instance and returns a MessageReceiver which can be used to receive messages from it.
    ///
    /// # Arguments
    ///
    /// * `partition_id` - The ID of the partition to receive events from.
    /// * `options` - Optional [`OpenReceiverOptions`] to configure the behavior of the receiver.
    ///
    /// # Returns
    ///
    /// A MessageReceiver which can be used to receive messages from the partition.
    ///
    /// Note that by default, a message receiver will receive events starting from the latest event in the partition (in
    /// other words, it will receive new events only). To receive events from another location within the partition you can
    /// specify a different starting position using the `options` parameter.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use azure_messaging_eventhubs::ConsumerClient;
    /// use azure_identity::DeveloperToolsCredential;
    /// use futures::stream::StreamExt;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let my_credential = DeveloperToolsCredential::new(None)?;
    ///     let consumer = ConsumerClient::builder()
    ///        .open("my_namespace", "my_eventhub".to_string(), my_credential).await?;
    ///     let partition_id = "0".to_string();
    ///
    ///     let receiver  = consumer.open_receiver_on_partition(partition_id, None).await?;
    ///
    ///     let mut event_stream = receiver.stream_events();
    ///
    ///     while let Some(event_result) = event_stream.next().await {
    ///         match event_result {
    ///             Ok(event) => {
    ///                 // Process the received event
    ///                 println!("Received event: {:?}", event);
    ///             }
    ///             Err(err) => {
    ///                 // Handle the error
    ///                 eprintln!("Error receiving event: {:?}", err);
    ///             }
    ///         }
    ///     }
    ///     Ok(())
    /// }
    /// ```
    #[tracing::instrument(
        level = "debug",
        skip_all,
        fields(
            connection_id = %self.recoverable_connection.get_connection_id(),
            partition_id = %partition_id,
            consumer_group = %self.consumer_group,
            eventhub = %self.eventhub,
        ),
        err,
    )]
    pub async fn open_receiver_on_partition(
        &self,
        partition_id: String,
        options: Option<OpenReceiverOptions>,
    ) -> Result<EventReceiver> {
        let options = options.unwrap_or_default();

        let receiver_name = self
            .instance_id
            .clone()
            .unwrap_or_else(|| Uuid::new_v4().to_string());
        let start_expression = StartPosition::start_expression(&options.start_position);

        trace!(
            partition_id = %partition_id,
            source_url = %self.endpoint,
            "Opening receiver on partition."
        );

        let source_url = format!("{}/Partitions/{}", self.endpoint, partition_id);
        let source_url = Url::parse(&source_url).map_err(azure_core::Error::from)?;

        let message_source = AmqpSource::builder()
            .with_address(source_url.to_string())
            .add_to_filter(
                AmqpSourceFilter::selector_filter().description().into(),
                Box::new(AmqpDescribed::new(
                    AmqpSourceFilter::selector_filter().code(),
                    start_expression,
                )),
            )
            .build();
        let mut receiver_properties: AmqpOrderedMap<AmqpSymbol, AmqpValue> =
            vec![("com.microsoft.com:receiver-name", receiver_name.clone())]
                .into_iter()
                .map(|(k, v)| (AmqpSymbol::from(k), AmqpValue::from(v)))
                .collect();

        if let Some(owner_level) = options.owner_level {
            receiver_properties.insert("com.microsoft:epoch".into(), AmqpValue::from(owner_level));
        }

        let receiver_options = AmqpReceiverOptions {
            name: Some(receiver_name),
            properties: Some(receiver_properties),
            credit_mode: Some(ReceiverCreditMode::Auto(options.prefetch.unwrap_or(300))),
            auto_accept: true,
            ..Default::default()
        };

        info!(
            partition_id = %partition_id,
            consumer_group = %self.consumer_group,
            eventhub = %self.eventhub,
            source_url = %source_url,
            "Receiver attached on partition."
        );
        Ok(EventReceiver::new(
            self.recoverable_connection.clone(),
            receiver_options,
            message_source,
            source_url,
            partition_id,
            options.receive_timeout,
        ))
    }

    /// Retrieves the properties of the Event Hub.
    ///
    /// This function retrieves the properties of the Event Hub associated with the [`ConsumerClient`].
    /// It returns a [`Result`] containing the [`EventHubProperties`] if the operation is successful.
    ///
    /// # Returns
    ///
    /// A [`Result`] containing the [`EventHubProperties`] if the operation is successful.
    ///
    /// # Examples
    ///
    /// ``` no_run
    /// use azure_messaging_eventhubs::ConsumerClient;
    /// use azure_identity::DeveloperToolsCredential;
    ///
    /// #[tokio::main]
    /// async fn main(){
    ///     let my_credential = DeveloperToolsCredential::new(None).unwrap();
    ///     let consumer = ConsumerClient::builder()
    ///         .open("my_namespace", "my_eventhub".to_string(), my_credential).await.unwrap();
    ///
    ///     let eventhub_properties = consumer.get_eventhub_properties().await;
    ///
    ///     match eventhub_properties {
    ///         Ok(properties) => {
    ///             // Process the Event Hub instance properties
    ///             println!("Event Hub properties: {:?}", properties);
    ///         }
    ///         Err(err) => {
    ///             // Handle the error
    ///             eprintln!("Error retrieving Event Hubs properties: {:?}", err);
    ///         }
    ///     }
    /// }
    /// ```
    pub async fn get_eventhub_properties(&self) -> Result<EventHubProperties> {
        self.get_management_instance()
            .await?
            .get_eventhub_properties(&self.eventhub)
            .await
    }

    /// Retrieves the properties of a specific partition in the Event Hub.
    ///
    /// This function retrieves the properties of the specified partition in the Event Hub.
    /// It returns a [`Result`] containing the [`EventHubPartitionProperties`] if the operation is successful.
    ///
    /// # Arguments
    ///
    /// * `partition_id` - The ID of the partition to retrieve properties for.
    ///
    /// # Returns
    ///
    /// A [`Result`] containing the [`EventHubPartitionProperties`] if the operation is successful.
    ///
    /// # Examples
    ///
    /// ``` no_run
    /// use azure_messaging_eventhubs::ConsumerClient;
    /// use azure_identity::DeveloperToolsCredential;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let my_credential = DeveloperToolsCredential::new(None).unwrap();
    ///     let consumer = ConsumerClient::builder()
    ///         .open("my_namespace", "my_eventhub".to_string(), my_credential).await.unwrap();
    ///     let partition_id = "0";
    ///
    ///     let partition_properties = consumer.get_partition_properties(partition_id).await;
    ///
    ///     match partition_properties {
    ///         Ok(properties) => {
    ///             // Process the partition properties
    ///             println!("Partition properties: {:?}", properties);
    ///         }
    ///         Err(err) => {
    ///             // Handle the error
    ///             eprintln!("Error retrieving partition properties: {:?}", err);
    ///         }
    ///     }
    /// }
    /// ```
    pub async fn get_partition_properties(
        &self,
        partition_id: &str,
    ) -> Result<EventHubPartitionProperties> {
        self.get_management_instance()
            .await?
            .get_eventhub_partition_properties(&self.eventhub, partition_id)
            .await
    }

    async fn get_management_instance(&self) -> Result<Arc<ManagementInstance>> {
        Ok(ManagementInstance::new(self.recoverable_connection.clone()))
    }

    async fn ensure_connection(&self) -> azure_core_amqp::Result<()> {
        self.recoverable_connection.ensure_connection().await?;
        Ok(())
    }
}

/// Represents the options for receiving events from an Event Hub.
#[derive(Debug, Clone, Default)]
pub struct OpenReceiverOptions {
    /// The owner level for messages being retrieved.
    pub owner_level: Option<i64>,
    /// The prefetch count for messages being retrieved.
    pub prefetch: Option<u32>,
    /// The starting position for messages being retrieved.
    pub start_position: Option<StartPosition>,

    /// Optional timeout for receiving messages. If not provided, the default timeout is infinite.
    ///
    /// Note: This is the timeout for individual messages, not the entire receive operation.
    /// As long as there are messages available, then they will be included in the stream events regardless of the timeout.
    pub receive_timeout: Option<Duration>,
}
/// Represents the options for receiving events from an Event Hub.
impl OpenReceiverOptions {}

/// Represents the starting position of a consumer when receiving events from an Event Hub.
#[derive(Debug, Default, PartialEq, Clone)]
pub enum StartLocation {
    /// The starting position is specified by an offset.
    Offset(String),
    /// The starting position is specified by a sequence number.
    SequenceNumber(i64),
    /// The starting position is specified by an enqueued time.
    EnqueuedTime(SystemTime),
    /// The starting position is the earliest event in the partition.
    Earliest,
    #[default]
    /// The starting position is the latest event in the partition.
    Latest,
}

pub(crate) const ENQUEUED_TIME_ANNOTATION: &str = "amqp.annotation.x-opt-enqueued-time";
pub(crate) const OFFSET_ANNOTATION: &str = "amqp.annotation.x-opt-offset";
pub(crate) const SEQUENCE_NUMBER_ANNOTATION: &str = "amqp.annotation.x-opt-sequence-number";

/// Represents the starting position of a consumer when receiving events from an Event Hub.
///
/// This enum provides different ways to specify the starting position of a consumer when receiving events from an Event Hub.
/// The starting position can be specified using an offset, a sequence number, an enqueued time, or the earliest or latest event in the partition.
///
/// The default starting position is the latest event in the partition (always receive new events).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use azure_messaging_eventhubs::{StartPosition, StartLocation};
///
/// let start_position = StartPosition{
///   location: StartLocation::SequenceNumber(12345),
///    ..Default::default()};;
/// ```
///
/// ```
/// use azure_messaging_eventhubs::{StartPosition, StartLocation};
///
/// let start_position = StartPosition{
///  location: StartLocation::EnqueuedTime(std::time::SystemTime::now()),
///  ..Default::default()
/// };
/// ```
///
/// ```
/// use azure_messaging_eventhubs::{StartPosition, StartLocation};
///
/// let start_position = StartPosition{
///   location: StartLocation::Offset("12345".to_string()),
///   ..Default::default()
/// };
/// ```
///
/// ```
/// use azure_messaging_eventhubs::{StartPosition, StartLocation};
///
/// let start_position = StartPosition{
///   location: StartLocation::Earliest,
///   ..Default::default()
/// };
/// ```
///
/// ```
/// use azure_messaging_eventhubs::{StartPosition, StartLocation};
///
/// let start_position = StartPosition{
///   location: StartLocation::Latest,
///   ..Default::default()
/// };
/// ```
///
/// ```
/// use azure_messaging_eventhubs::StartPosition;
///
/// let start_position = StartPosition::default();
/// ```
///
#[derive(Debug, PartialEq, Clone, Default)]
pub struct StartPosition {
    /// The location of the starting position.
    pub location: StartLocation,

    /// Whether the starting position is inclusive (includes the event at StartLocation).
    pub inclusive: bool,
}

impl StartPosition {
    pub(crate) fn start_expression(position: &Option<StartPosition>) -> String {
        if let Some(position) = position {
            let mut greater_than: &str = ">";
            if position.inclusive {
                greater_than = ">=";
            }
            match &position.location {
                StartLocation::Offset(offset) => {
                    format!("{} {}'{}'", OFFSET_ANNOTATION, greater_than, offset)
                }
                StartLocation::SequenceNumber(sequence_number) => {
                    format!(
                        "{} {}'{}'",
                        SEQUENCE_NUMBER_ANNOTATION, greater_than, sequence_number
                    )
                }
                StartLocation::EnqueuedTime(enqueued_time) => {
                    let enqueued_time = enqueued_time
                        .duration_since(UNIX_EPOCH)
                        .expect("Time went backwards")
                        .as_millis();
                    format!(
                        "{} {}'{}'",
                        ENQUEUED_TIME_ANNOTATION, greater_than, enqueued_time
                    )
                }
                StartLocation::Earliest => "amqp.annotation.x-opt-offset > '-1'".to_string(),
                StartLocation::Latest => "amqp.annotation.x-opt-offset > '@latest'".to_string(),
            }
        } else {
            "amqp.annotation.x-opt-offset > '@latest'".to_string()
        }
    }
}

pub mod builders {
    use super::*;
    use crate::{
        common::{
            connection_string::{resolve_eventhub, ConnectionString},
            sas_credential::SasCredential,
            SAS_TOKEN_TYPE,
        },
        Result,
    };
    use azure_core_amqp::AmqpTransport;
    use std::sync::Arc;

    /// A builder for creating a [`ConsumerClient`].
    ///
    /// This builder is used to create a new [`ConsumerClient`] with the specified parameters.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use azure_messaging_eventhubs::ConsumerClient;
    /// use azure_identity::DeveloperToolsCredential;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///    let my_credential = DeveloperToolsCredential::new(None).unwrap();
    ///   let consumer = ConsumerClient::builder()
    ///      .open("my_namespace", "my_eventhub".to_string(), my_credential).await?;
    ///   Ok(())
    /// }
    /// ```
    #[derive(Default)]
    pub struct ConsumerClientBuilder {
        consumer_group: Option<String>,
        application_id: Option<String>,
        instance_id: Option<String>,
        retry_options: Option<RetryOptions>,
        custom_endpoint: Option<String>,
        transport: Option<AmqpTransport>,
    }

    impl ConsumerClientBuilder {
        pub(super) fn new() -> Self {
            Self {
                ..Default::default()
            }
        }

        /// Specifies the name of the application creating the [`ConsumerClient`].
        pub fn with_application_id(mut self, application_id: String) -> Self {
            self.application_id = Some(application_id);
            self
        }

        /// Specifies the consumer group for the [`ConsumerClient`].
        ///
        /// If not specified, the default consumer group will be used.
        ///
        /// For more information on Event Hubs consumer groups, see
        /// [Consumer groups](https://learn.microsoft.com/azure/event-hubs/event-hubs-features#consumer-groups).
        ///
        /// # Examples
        ///
        /// ```no_run
        /// use azure_messaging_eventhubs::ConsumerClient;
        /// use azure_identity::DeveloperToolsCredential;
        ///
        /// #[tokio::main]
        /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
        ///    let my_credential = DeveloperToolsCredential::new(None)?;
        ///    let consumer = ConsumerClient::builder()
        ///      .with_consumer_group("my_consumer_group".to_string())
        ///      .open("my_namespace", "my_eventhub".to_string(), my_credential).await?;
        ///   Ok(())
        /// }
        ///
        /// ```
        ///
        pub fn with_consumer_group(mut self, consumer_group: String) -> Self {
            self.consumer_group = Some(consumer_group);
            self
        }

        /// Specifies an instance ID for this instance of a [`ConsumerClient`].
        pub fn with_instance_id(mut self, instance_id: String) -> Self {
            self.instance_id = Some(instance_id);
            self
        }

        /// Specifies the retry options for the [`ConsumerClient`].
        pub fn with_retry_options(mut self, retry_options: RetryOptions) -> Self {
            self.retry_options = Some(retry_options);
            self
        }

        /// Sets a custom endpoint for the Event Hub.
        ///
        /// # Arguments
        /// * `endpoint` - The custom endpoint for the Event Hub.
        ///
        /// # Returns
        /// The updated [`ConsumerClientBuilder`].
        ///
        /// Note: The custom endpoint option allows a customer to specify an AMQP proxy
        /// which will be used to forward requests to the actual Event Hub instance.
        ///
        /// An explicit port on the endpoint carries into the address that the client
        /// dials. Under [`AmqpTransport::WebSocket`] that is the `wss://` address, so
        /// name the port that the proxy accepts WebSockets on, and leave the port out
        /// to dial the default port 443.
        ///
        pub fn with_custom_endpoint(mut self, endpoint: String) -> Self {
            self.custom_endpoint = Some(endpoint);
            self
        }

        /// Sets the transport used to communicate with the Event Hub.
        ///
        /// # Arguments
        /// * `transport` - The transport to use. Defaults to
        ///   [`AmqpTransport::Tcp`]. Use [`AmqpTransport::WebSocket`] to
        ///   tunnel AMQP over WebSockets (port 443) when the native AMQP
        ///   ports are blocked.
        ///
        /// # Returns
        /// The updated [`ConsumerClientBuilder`].
        pub fn with_transport(mut self, transport: AmqpTransport) -> Self {
            self.transport = Some(transport);
            self
        }

        /// Returns the AMQP transport this builder opens the connection with.
        /// Shared by every `open` path so they cannot drift apart.
        pub(crate) fn transport(&self) -> AmqpTransport {
            self.transport.unwrap_or_default()
        }

        /// Opens a connection to the Event Hub.
        ///
        /// This method establishes a connection to the Event Hubs instance associated
        /// with the [`ConsumerClientBuilder`]. It returns a `Result` indicating whether the
        /// operation was successful or not.
        ///
        /// # Returns
        ///
        /// A `Result` indicating whether the operation was successful or not.
        ///
        /// # Examples
        ///
        /// ```
        /// use azure_messaging_eventhubs::ConsumerClient;
        /// use azure_identity::DeveloperToolsCredential;
        ///
        /// #[tokio::main]
        /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
        ///     let my_credential = DeveloperToolsCredential::new(None).unwrap();
        ///     let result = ConsumerClient::builder()
        ///         .open("my_namespace", "my_eventhub".to_string(), my_credential).await;
        ///
        ///     match result {
        ///         Ok(_connection) => {
        ///             // Connection opened successfully
        ///             println!("Connection opened successfully");
        ///         }
        ///         Err(err) => {
        ///             // Handle the error
        ///             eprintln!("Error opening connection: {:?}", err);
        ///         }
        ///     }
        ///     Ok(())
        /// }
        /// ```
        pub async fn open(
            self,
            fully_qualified_namespace: &str,
            eventhub_name: String,
            credential: Arc<dyn azure_core::credentials::TokenCredential>,
        ) -> Result<super::ConsumerClient> {
            let transport = self.transport();
            let custom_endpoint = match self.custom_endpoint {
                Some(endpoint) => Some(Url::parse(&endpoint).map_err(azure_core::Error::from)?),
                None => None,
            };
            trace!("Opening consumer client on {fully_qualified_namespace}.");
            let consumer = super::ConsumerClient::new(
                fully_qualified_namespace,
                eventhub_name,
                self.consumer_group,
                credential,
                ConsumerClientOptions {
                    application_id: self.application_id,
                    instance_id: self.instance_id,
                    retry_options: self.retry_options,
                    custom_endpoint,
                    cbs_token_type: None,
                    transport,
                },
            )?;
            consumer.ensure_connection().await?;
            Ok(consumer)
        }

        /// Opens a connection to the Event Hub using a connection string.
        ///
        /// This is an alternative to [`open`](Self::open) for development and
        /// test scenarios that authenticate with a Shared Access Signature
        /// instead of Microsoft Entra ID. For production, prefer
        /// [`open`](Self::open) with a `TokenCredential`.
        ///
        /// When the connection string carries a `SharedAccessKeyName` /
        /// `SharedAccessKey`, the client signs and refreshes SAS tokens itself.
        /// When it carries a pre-formed `SharedAccessSignature`, that token is
        /// used as-is and *cannot* be refreshed (there is no key to re-sign
        /// with); the broker drops the link once the token's own expiry elapses.
        ///
        /// # Arguments
        /// * `connection_string` - An Event Hubs connection string, e.g.
        ///   `Endpoint=sb://<ns>.servicebus.windows.net/;SharedAccessKeyName=<policy>;SharedAccessKey=<key>`.
        ///   It may include an `EntityPath` naming the Event Hub.
        /// * `eventhub` - The Event Hub name. Required unless the connection
        ///   string includes an `EntityPath`; if both are given they must agree.
        ///
        /// # Returns
        /// A new instance of [`ConsumerClient`].
        ///
        /// # Examples
        ///
        /// ```no_run
        /// use azure_messaging_eventhubs::ConsumerClient;
        ///
        /// #[tokio::main]
        /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
        ///     let connection_string = std::env::var("EVENTHUBS_CONNECTION_STRING")?;
        ///     let consumer = ConsumerClient::builder()
        ///         .open_with_connection_string(&connection_string, Some("my_eventhub"))
        ///         .await?;
        ///     Ok(())
        /// }
        /// ```
        pub async fn open_with_connection_string(
            self,
            connection_string: &str,
            eventhub: Option<&str>,
        ) -> Result<super::ConsumerClient> {
            let transport = self.transport();
            let connection_string: ConnectionString = connection_string.parse()?;
            let eventhub = resolve_eventhub(&connection_string, eventhub)?;
            let credential = Arc::new(SasCredential::from_connection_string(
                &connection_string,
                &eventhub,
            )?);

            let custom_endpoint = match self.custom_endpoint {
                Some(endpoint) => Some(Url::parse(&endpoint).map_err(azure_core::Error::from)?),
                None => None,
            };

            let consumer = super::ConsumerClient::new(
                &connection_string.fully_qualified_namespace,
                eventhub,
                self.consumer_group,
                credential,
                ConsumerClientOptions {
                    application_id: self.application_id,
                    instance_id: self.instance_id,
                    retry_options: self.retry_options,
                    custom_endpoint,
                    cbs_token_type: Some(SAS_TOKEN_TYPE),
                    transport,
                },
            )?;
            consumer.ensure_connection().await?;
            Ok(consumer)
        }
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use crate::{
        common::tests::force_errors, models::EventData, ConsumerClient, EventDataBatchOptions,
        ProducerClient, Result, StartLocation, StartPosition,
    };
    use azure_core::{sleep::sleep, time::Duration};
    use azure_core_amqp::{error::AmqpErrorKind, AmqpError, AmqpTransport};
    use azure_core_test::{recorded, TestContext};
    use futures::stream::StreamExt;
    use std::{
        sync::Arc,
        time::{SystemTime, UNIX_EPOCH},
    };

    // Every `open` path on the builder reads the transport through one helper,
    // so this covers the plumbing that the connection-string path shares.
    #[test]
    fn builder_reads_the_transport_through_one_helper() {
        assert_eq!(
            ConsumerClient::builder()
                .with_transport(AmqpTransport::WebSocket)
                .transport(),
            AmqpTransport::WebSocket
        );
        assert_eq!(
            ConsumerClient::builder()
                .with_transport(AmqpTransport::Tcp)
                .transport(),
            AmqpTransport::Tcp
        );
        // An unset transport keeps the TCP default.
        assert_eq!(ConsumerClient::builder().transport(), AmqpTransport::Tcp);
    }
    use tracing::info;

    // static INIT_LOGGING: std::sync::Once = std::sync::Once::new();

    // #[test]
    // pub(crate) fn setup() {
    //     INIT_LOGGING.call_once(|| {
    //         println!("Setting up test logger...");

    //         use tracing_subscriber::{fmt::format::FmtSpan, EnvFilter};
    //         tracing_subscriber::fmt()
    //             .with_env_filter(EnvFilter::from_default_env())
    //             .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
    //             .with_ansi(std::env::var("NO_COLOR").map_or(true, |v| v.is_empty()))
    //             .with_writer(std::io::stderr)
    //             .init();
    //     });
    // }

    #[recorded::test]
    async fn test_start_position_builder_with_sequence_number(_ctx: TestContext) -> Result<()> {
        let sequence_number = 12345i64;
        let start_position = StartPosition {
            location: StartLocation::SequenceNumber(sequence_number),
            ..Default::default()
        };
        assert_eq!(
            start_position.location,
            StartLocation::SequenceNumber(sequence_number)
        );
        assert_eq!(
            StartPosition::start_expression(&Some(start_position)),
            "amqp.annotation.x-opt-sequence-number >'12345'"
        );

        let start_position = StartPosition {
            location: StartLocation::SequenceNumber(sequence_number),
            inclusive: true,
        };
        assert_eq!(
            StartPosition::start_expression(&Some(start_position)),
            "amqp.annotation.x-opt-sequence-number >='12345'"
        );
        Ok(())
    }

    #[recorded::test]
    async fn test_start_position_builder_with_enqueued_time(_ctx: TestContext) -> Result<()> {
        let enqueued_time = SystemTime::now();
        let start_position = StartPosition {
            location: StartLocation::EnqueuedTime(enqueued_time),
            ..Default::default()
        };
        info!("enqueued_time: {:?}", enqueued_time);
        info!(
            "enqueued_time: {:?}",
            enqueued_time.duration_since(UNIX_EPOCH)
        );
        info!(
            "enqueued_time: {:?}",
            enqueued_time
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_millis()
        );
        assert_eq!(
            start_position.location,
            StartLocation::EnqueuedTime(enqueued_time)
        );
        assert!(!start_position.inclusive);
        assert_eq!(
            StartPosition::start_expression(&Some(start_position)),
            format!(
                "amqp.annotation.x-opt-enqueued-time >'{}'",
                enqueued_time
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_millis()
            )
        );

        let start_position = StartPosition {
            location: StartLocation::EnqueuedTime(enqueued_time),
            inclusive: true,
        };
        assert_eq!(
            StartPosition::start_expression(&Some(start_position)),
            format!(
                "amqp.annotation.x-opt-enqueued-time >='{}'",
                enqueued_time
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_millis()
            )
        );
        Ok(())
    }

    #[recorded::test]
    async fn test_start_position_builder_with_offset(_ctx: TestContext) -> Result<()> {
        let offset = "12345".to_string();
        let start_position = StartPosition {
            location: StartLocation::Offset(offset.clone()),
            ..Default::default()
        };
        assert_eq!(
            start_position.location,
            StartLocation::Offset(offset.clone())
        );
        assert_eq!(
            "amqp.annotation.x-opt-offset >'12345'",
            StartPosition::start_expression(&Some(start_position)),
        );

        let start_position = StartPosition {
            location: StartLocation::Offset(offset.clone()),
            inclusive: true,
        };
        assert_eq!(
            "amqp.annotation.x-opt-offset >='12345'",
            StartPosition::start_expression(&Some(start_position)),
        );
        Ok(())
    }

    #[recorded::test]
    async fn test_start_position_builder_inclusive(_ctx: TestContext) -> Result<()> {
        let start_position = StartPosition {
            inclusive: true,
            ..Default::default()
        };
        assert!(start_position.inclusive);
        let start_position = StartPosition::default();
        assert!(!start_position.inclusive);
        Ok(())
    }

    #[recorded::test(live)]
    async fn force_errors_consumer_properties_link(ctx: TestContext) -> Result<()> {
        const TEST_NAME: &str = "force_errors_consumer_properties_link";
        let recording = ctx.recording();
        let host = recording.var("EVENTHUBS_HOST", None);
        let eventhub = recording.var("EVENTHUB_NAME", None);
        let credential = recording.credential();
        let consumer = Arc::new(
            ConsumerClient::builder()
                .with_application_id(TEST_NAME.to_string())
                .open(host.as_str(), eventhub, credential.clone())
                .await?,
        );

        force_errors(
            consumer.clone(),
            |consumer: Arc<ConsumerClient>| {
                let consumer = consumer.clone();
                async move {
                    loop {
                        consumer.get_eventhub_properties().await.unwrap();
                    }
                }
            },
            |consumer| {
                consumer
                    .force_error(azure_core_amqp::AmqpError::from(
                        AmqpErrorKind::LinkClosedByRemote(Box::new(azure_core::error::Error::new(
                            azure_core::error::ErrorKind::Other,
                            "Forced error",
                        ))),
                    ))
                    .unwrap();
            },
            Duration::seconds(10), // Seconds until forcing the error.
            Duration::seconds(20), // Seconds until test timeout.
        )
        .await?;

        if let Ok(consumer) = Arc::try_unwrap(consumer) {
            consumer.close().await?;
        } else {
            panic!("Consumer client has unresolved references.");
        }

        Ok(())
    }

    #[recorded::test(live)]
    async fn force_errors_consumer_properties_session(ctx: TestContext) -> Result<()> {
        const TEST_NAME: &str = "force_errors_consumer_properties_session";
        let recording = ctx.recording();
        let host = recording.var("EVENTHUBS_HOST", None);
        let eventhub = recording.var("EVENTHUB_NAME", None);
        let credential = recording.credential();
        let consumer = Arc::new(
            ConsumerClient::builder()
                .with_application_id(TEST_NAME.to_string())
                .open(host.as_str(), eventhub, credential.clone())
                .await?,
        );

        force_errors(
            consumer.clone(),
            |consumer: Arc<ConsumerClient>| {
                let consumer = consumer.clone();
                async move {
                    loop {
                        consumer.get_eventhub_properties().await.unwrap();
                    }
                }
            },
            |consumer| {
                consumer
                    .force_error(azure_core_amqp::AmqpError::from(
                        AmqpErrorKind::SessionClosedByRemote(Box::new(
                            azure_core::error::Error::new(
                                azure_core::error::ErrorKind::Other,
                                "Forced error",
                            ),
                        )),
                    ))
                    .unwrap();
            },
            Duration::seconds(10), // Seconds until forcing the error.
            Duration::seconds(20), // Seconds until test timeout.
        )
        .await?;

        if let Ok(consumer) = Arc::try_unwrap(consumer) {
            consumer.close().await?;
        } else {
            panic!("Consumer client has unresolved references.");
        }

        Ok(())
    }
    #[recorded::test(live)]
    async fn force_errors_consumer_properties_connection(ctx: TestContext) -> Result<()> {
        const TEST_NAME: &str = "force_errors_consumer_properties_connection";
        let recording = ctx.recording();
        let host = recording.var("EVENTHUBS_HOST", None);
        let eventhub = recording.var("EVENTHUB_NAME", None);
        let credential = recording.credential();
        let consumer = Arc::new(
            ConsumerClient::builder()
                .with_application_id(TEST_NAME.to_string())
                .open(host.as_str(), eventhub, credential.clone())
                .await?,
        );

        force_errors(
            consumer.clone(),
            |consumer: Arc<ConsumerClient>| {
                let consumer = consumer.clone();
                async move {
                    loop {
                        consumer.get_eventhub_properties().await.unwrap();
                    }
                }
            },
            |consumer| {
                consumer
                    .force_error(azure_core_amqp::AmqpError::from(
                        AmqpErrorKind::ConnectionClosedByRemote(Box::new(
                            azure_core::error::Error::new(
                                azure_core::error::ErrorKind::Other,
                                "Forced error",
                            ),
                        )),
                    ))
                    .unwrap();
            },
            Duration::seconds(10), // Seconds until forcing the error.
            Duration::seconds(20), // Seconds until test timeout.
        )
        .await?;

        Ok(())
    }

    // --- Receiver-side recovery tests (issue #4563) ------------------------
    //
    // These mirror the producer's `force_errors_send_batch_*` tests but drive
    // the consumer receive path, which re-resolves the per-path receiver cache
    // on every `receive_delivery`. A background producer feeds the partition so
    // the receive loop keeps pulling deliveries; without traffic the loop would
    // block in `receive_delivery` and never re-enter the recovery path the
    // receiver-cache change touches. After the forced error the receiver
    // re-attaches transparently and deliveries resume.

    const RECEIVE_TEST_PARTITION: &str = "0";

    async fn run_receive_recovery(
        ctx: &TestContext,
        test_name: &str,
        make_error: fn() -> AmqpError,
    ) -> Result<()> {
        let recording = ctx.recording();
        let host = recording.var("EVENTHUBS_HOST", None);
        let eventhub = recording.var("EVENTHUB_NAME", None);
        let credential = recording.credential();

        // Feed the partition continuously from an independent producer
        // connection so the consumer always has deliveries to pull. The forced
        // error is injected only on the consumer, so this producer stays stable.
        let producer = Arc::new(
            ProducerClient::builder()
                .with_application_id(format!("{test_name}-feed"))
                .open(host.as_str(), eventhub.as_str(), credential.clone())
                .await?,
        );
        let feed = tokio::spawn({
            let producer = producer.clone();
            async move {
                loop {
                    let batch = producer
                        .create_batch(Some(EventDataBatchOptions {
                            partition_id: Some(RECEIVE_TEST_PARTITION.to_string()),
                            ..Default::default()
                        }))
                        .await
                        .expect("feed: create_batch");
                    batch
                        .try_add_event_data(
                            EventData::builder().with_body(b"heartbeat").build(),
                            None,
                        )
                        .expect("feed: add heartbeat event");
                    producer
                        .send_batch(batch, None)
                        .await
                        .expect("feed: send_batch");
                    sleep(Duration::milliseconds(250)).await;
                }
            }
        });

        let consumer = Arc::new(
            ConsumerClient::builder()
                .with_application_id(test_name.to_string())
                .open(host.as_str(), eventhub, credential.clone())
                .await?,
        );

        force_errors(
            consumer.clone(),
            |consumer: Arc<ConsumerClient>| {
                let consumer = consumer.clone();
                async move {
                    // Default start position is "latest", so we receive the
                    // heartbeat events the feed produces from now on.
                    let receiver = consumer
                        .open_receiver_on_partition(RECEIVE_TEST_PARTITION.to_string(), None)
                        .await
                        .unwrap();
                    let mut stream = std::pin::pin!(receiver.stream_events());
                    while let Some(event) = stream.next().await {
                        // Recovery is transparent: after the forced error the
                        // receiver re-attaches and deliveries resume, so the
                        // stream keeps yielding Ok.
                        event.unwrap();
                    }
                }
            },
            move |consumer: Arc<ConsumerClient>| {
                info!("Forcing error on consumer receiver");
                consumer.force_error(make_error()).unwrap();
            },
            Duration::seconds(10), // Seconds until forcing the error.
            Duration::seconds(30), // Seconds until test timeout.
        )
        .await?;

        // Stop the feed and observe its cancellation. A clean cancel is
        // expected; a panic in the feed (e.g. one of its `expect`s firing) is
        // re-raised here instead of being silently swallowed, which would
        // otherwise surface only as the receive loop starving for deliveries.
        feed.abort();
        match feed.await {
            Ok(()) => {}
            Err(err) if err.is_cancelled() => {}
            Err(err) => std::panic::resume_unwind(err.into_panic()),
        }

        // Close both clients explicitly so neither leaks its AMQP connection
        // across live tests. The feed task has finished by now, so its producer
        // clone is gone and the unwrap holds the sole reference.
        if let Ok(producer) = Arc::try_unwrap(producer) {
            producer.close().await?;
        }
        if let Ok(consumer) = Arc::try_unwrap(consumer) {
            consumer.close().await?;
        }
        Ok(())
    }

    #[recorded::test(live)]
    async fn force_errors_receive_link(ctx: TestContext) -> Result<()> {
        run_receive_recovery(&ctx, "force_errors_receive_link", || {
            AmqpError::from(AmqpErrorKind::LinkClosedByRemote(Box::new(
                azure_core::error::Error::new(azure_core::error::ErrorKind::Other, "Forced error"),
            )))
        })
        .await
    }

    #[recorded::test(live)]
    async fn force_errors_receive_session(ctx: TestContext) -> Result<()> {
        run_receive_recovery(&ctx, "force_errors_receive_session", || {
            AmqpError::from(AmqpErrorKind::SessionClosedByRemote(Box::new(
                azure_core::error::Error::new(azure_core::error::ErrorKind::Other, "Forced error"),
            )))
        })
        .await
    }

    #[recorded::test(live)]
    async fn force_errors_receive_connection(ctx: TestContext) -> Result<()> {
        run_receive_recovery(&ctx, "force_errors_receive_connection", || {
            AmqpError::from(AmqpErrorKind::ConnectionClosedByRemote(Box::new(
                azure_core::error::Error::new(azure_core::error::ErrorKind::Other, "Forced error"),
            )))
        })
        .await
    }
}