azeventhubs 0.20.0

An unofficial AMQP 1.0 rust client for Azure Event Hubs
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
use std::{collections::HashMap, marker::PhantomData};

use crate::{
    amqp::amqp_producer::{AmqpProducer, RecoverableAmqpProducer},
    authorization::{
        event_hub_token_credential::EventHubTokenCredential, AzureNamedKeyCredential,
        AzureSasCredential,
    },
    core::{BasicRetryPolicy, TransportProducer},
    event_hubs_properties::EventHubProperties,
    event_hubs_retry_policy::EventHubsRetryPolicy,
    EventData, EventHubConnection, EventHubsRetryOptions, PartitionProperties,
};

use super::{
    create_batch_options::CreateBatchOptions, event_data_batch::EventDataBatch,
    event_hub_producer_client_options::EventHubProducerClientOptions,
    send_event_options::SendEventOptions,
};

/// The minimum
pub const MINIMUM_BATCH_SIZE_LIMIT_IN_BYTES: u64 = 24;

/// A client responsible for publishing [`EventData`] to a specific Event Hub, grouped together in
/// batches.  Depending on the options specified when sending, events may be automatically assigned
/// an available partition or may request a specific partition.
///
/// The [`EventHubProducerClient`] publishes immediately, ensuring a deterministic outcome for each
/// send operation, though requires that callers own the responsibility of building and managing
/// batches.
#[derive(Debug)]
pub struct EventHubProducerClient<RP> {
    connection: EventHubConnection,
    /// An abstracted Event Hub transport-specific producer that is associated with the
    /// Event Hub gateway rather than a specific partition; intended to perform delegated operations.
    gateway_producer: Option<AmqpProducer<RP>>,
    producer_pool: HashMap<String, AmqpProducer<RP>>,
    options: EventHubProducerClientOptions,
    retry_policy_marker: PhantomData<RP>,
}

impl EventHubProducerClient<BasicRetryPolicy> {
    /// Creates a new client with a custom retry policy.
    pub fn with_policy<P>() -> EventHubProducerClientBuilder<P>
    where
        P: EventHubsRetryPolicy + Send,
    {
        EventHubProducerClientBuilder {
            _retry_policy_marker: PhantomData,
        }
    }

    /// Creates a [`EventHubProducerClient`] using a connection string.
    pub async fn new_from_connection_string(
        connection_string: impl Into<String>,
        event_hub_name: impl Into<Option<String>>,
        client_options: EventHubProducerClientOptions,
    ) -> Result<Self, azure_core::Error> {
        Self::with_policy()
            .new_from_connection_string(connection_string, event_hub_name, client_options)
            .await
    }

    /// Creates a [`EventHubProducerClient`] using a namespace and a credential.
    pub async fn new_from_credential(
        fully_qualified_namespace: impl Into<String>,
        event_hub_name: impl Into<String>,
        credential: impl Into<EventHubTokenCredential>,
        client_options: EventHubProducerClientOptions,
    ) -> Result<Self, azure_core::Error> {
        Self::with_policy()
            .new_from_credential(
                fully_qualified_namespace,
                event_hub_name,
                credential,
                client_options,
            )
            .await
    }

    /// Creates a [`EventHubProducerClient`] using a namespace and a [`AzureNamedKeyCredential`].
    pub async fn new_from_named_key_credential(
        fully_qualified_namespace: impl Into<String>,
        event_hub_name: impl Into<String>,
        credential: AzureNamedKeyCredential,
        client_options: EventHubProducerClientOptions,
    ) -> Result<Self, azure_core::Error> {
        Self::with_policy()
            .new_from_named_key_credential(
                fully_qualified_namespace,
                event_hub_name,
                credential,
                client_options,
            )
            .await
    }

    /// Creates a [`EventHubProducerClient`] using a namespace and a [`AzureSasCredential`].
    pub async fn new_from_sas_credential(
        fully_qualified_namespace: impl Into<String>,
        event_hub_name: impl Into<String>,
        credential: AzureSasCredential,
        client_options: EventHubProducerClientOptions,
    ) -> Result<Self, azure_core::Error> {
        Self::with_policy()
            .from_namespace_and_sas_credential(
                fully_qualified_namespace,
                event_hub_name,
                credential,
                client_options,
            )
            .await
    }

    /// Creates a [`EventHubProducerClient`] using a [`EventHubConnection`].
    pub fn with_connection(
        connection: &mut EventHubConnection,
        client_options: EventHubProducerClientOptions,
    ) -> Self {
        Self::with_policy().with_connection(connection, client_options)
    }
}

/// A builder for creating a [`EventHubProducerClient`].
///
/// This currently is only used for specifying a custom retry policy.
#[derive(Debug)]
pub struct EventHubProducerClientBuilder<RP> {
    _retry_policy_marker: PhantomData<RP>,
}

impl<RP> EventHubProducerClientBuilder<RP> {
    /// Creates a [`EventHubProducerClient`] using a connection string.
    pub async fn new_from_connection_string(
        self,
        connection_string: impl Into<String>,
        event_hub_name: impl Into<Option<String>>,
        client_options: EventHubProducerClientOptions,
    ) -> Result<EventHubProducerClient<RP>, azure_core::Error>
    where
        RP: EventHubsRetryPolicy + Send,
    {
        let connection = EventHubConnection::new_from_connection_string(
            connection_string.into(),
            event_hub_name.into(),
            client_options.connection_options.clone(),
        )
        .await?;

        Ok(EventHubProducerClient {
            connection,
            gateway_producer: None,
            producer_pool: HashMap::new(),
            options: client_options,
            retry_policy_marker: PhantomData,
        })
    }

    /// Creates a [`EventHubProducerClient`] using a namespace and a credential.
    pub async fn new_from_credential(
        self,
        fully_qualified_namespace: impl Into<String>,
        event_hub_name: impl Into<String>,
        credential: impl Into<EventHubTokenCredential>,
        client_options: EventHubProducerClientOptions,
    ) -> Result<EventHubProducerClient<RP>, azure_core::Error>
    where
        RP: EventHubsRetryPolicy + Send,
    {
        let connection = EventHubConnection::new_from_credential(
            fully_qualified_namespace.into(),
            event_hub_name.into(),
            credential.into(),
            client_options.connection_options.clone(),
        )
        .await?;

        Ok(EventHubProducerClient {
            connection,
            gateway_producer: None,
            producer_pool: HashMap::new(),
            options: client_options,
            retry_policy_marker: PhantomData,
        })
    }

    /// Creates a [`EventHubProducerClient`] using a namespace and a [`AzureNamedKeyCredential`].
    pub async fn new_from_named_key_credential(
        self,
        fully_qualified_namespace: impl Into<String>,
        event_hub_name: impl Into<String>,
        credential: AzureNamedKeyCredential,
        client_options: EventHubProducerClientOptions,
    ) -> Result<EventHubProducerClient<RP>, azure_core::Error>
    where
        RP: EventHubsRetryPolicy + Send,
    {
        let connection = EventHubConnection::new_from_named_key_credential(
            fully_qualified_namespace.into(),
            event_hub_name.into(),
            credential,
            client_options.connection_options.clone(),
        )
        .await?;

        Ok(EventHubProducerClient {
            connection,
            gateway_producer: None,
            producer_pool: HashMap::new(),
            options: client_options,
            retry_policy_marker: PhantomData,
        })
    }

    /// Creates a [`EventHubProducerClient`] using a namespace and a [`AzureSasCredential`].
    pub async fn from_namespace_and_sas_credential(
        self,
        fully_qualified_namespace: impl Into<String>,
        event_hub_name: impl Into<String>,
        credential: AzureSasCredential,
        client_options: EventHubProducerClientOptions,
    ) -> Result<EventHubProducerClient<RP>, azure_core::Error>
    where
        RP: EventHubsRetryPolicy + Send,
    {
        let connection = EventHubConnection::new_from_sas_credential(
            fully_qualified_namespace.into(),
            event_hub_name.into(),
            credential,
            client_options.connection_options.clone(),
        )
        .await?;

        Ok(EventHubProducerClient {
            connection,
            gateway_producer: None,
            producer_pool: HashMap::new(),
            options: client_options,
            retry_policy_marker: PhantomData,
        })
    }

    /// Creates a [`EventHubProducerClient`] using a [`EventHubConnection`].
    pub fn with_connection(
        self,
        connection: &mut EventHubConnection,
        client_options: EventHubProducerClientOptions,
    ) -> EventHubProducerClient<RP> {
        let connection = connection.clone_as_shared();

        EventHubProducerClient {
            connection,
            gateway_producer: None,
            producer_pool: HashMap::new(),
            options: client_options,
            retry_policy_marker: PhantomData,
        }
    }
}

impl<RP> EventHubProducerClient<RP>
where
    RP: EventHubsRetryPolicy + From<EventHubsRetryOptions> + Send,
{
    async fn get_or_create_gateway_producer_mut(
        &mut self,
    ) -> Result<RecoverableAmqpProducer<'_, RP>, azure_core::Error> {
        let producer_identifier = Some(
            self.options
                .identifier
                .clone()
                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
        );
        let requested_features = self.options.create_features();
        let retry_policy = RP::from(self.options.retry_options.clone());

        if self.gateway_producer.is_none() {
            let partition_options = self
                .options
                .get_publishing_options_or_default_for_partition(None);

            let producer = self
                .connection
                .create_transport_producer::<RP>(
                    None,
                    producer_identifier,
                    requested_features,
                    partition_options,
                    retry_policy,
                )
                .await?;
            self.gateway_producer = Some(producer);
        }

        let producer = self.gateway_producer.as_mut().unwrap();
        let client = &mut self.connection.inner;
        Ok(RecoverableAmqpProducer::new(producer, client))
    }

    async fn get_pooled_producer_mut(
        &mut self,
        partition_id: Option<&str>,
    ) -> Result<RecoverableAmqpProducer<'_, RP>, azure_core::Error> {
        let producer_identifier = Some(
            self.options
                .identifier
                .clone()
                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
        );
        let requested_features = self.options.create_features();
        let retry_policy = RP::from(self.options.retry_options.clone());

        let partition_id = partition_id.and_then(|id| if id.is_empty() { None } else { Some(id) });

        match partition_id {
            Some(partition_id) => {
                if !self.producer_pool.contains_key(partition_id) {
                    let partition_options = self
                        .options
                        .get_publishing_options_or_default_for_partition(Some(partition_id));

                    let producer = self
                        .connection
                        .create_transport_producer::<RP>(
                            Some(partition_id.to_string()),
                            producer_identifier,
                            requested_features,
                            partition_options,
                            retry_policy,
                        )
                        .await?;
                    self.producer_pool
                        .insert(partition_id.to_string(), producer);
                }

                // This is safe because we just checked that the key exists.
                let producer = self.producer_pool.get_mut(partition_id).unwrap();
                let client = &mut self.connection.inner;
                Ok(RecoverableAmqpProducer::new(producer, client))
            }
            None => self.get_or_create_gateway_producer_mut().await,
        }
    }

    /// Creates a new [`EventDataBatch`] with the given options.
    pub async fn create_batch(
        &mut self,
        options: CreateBatchOptions,
    ) -> Result<EventDataBatch, azure_core::Error> {
        let inner = self
            .get_or_create_gateway_producer_mut()
            .await?
            .create_batch(options)?;
        Ok(EventDataBatch { inner })
    }

    /// Sends a single event to the Event Hub.
    pub async fn send_event(
        &mut self,
        event: impl Into<EventData>,
        options: SendEventOptions,
    ) -> Result<(), azure_core::Error> {
        self.send_events(std::iter::once(event.into()), options)
            .await
    }

    /// Sends a set of events to the Event Hub.
    pub async fn send_events<E>(
        &mut self,
        events: E,
        options: SendEventOptions,
    ) -> Result<(), azure_core::Error>
    where
        E: IntoIterator<Item = EventData>,
        E::IntoIter: ExactSizeIterator + Send,
    {
        let partition_id = options.partition_id();
        let mut producer = self.get_pooled_producer_mut(partition_id).await?;
        producer
            .send(events.into_iter(), options)
            .await
            .map_err(Into::into)
    }

    /// Sends a batch of events to the Event Hub.
    pub async fn send_batch(
        &mut self,
        batch: EventDataBatch,
        options: SendEventOptions,
    ) -> Result<(), azure_core::Error> {
        let partition_id = options.partition_id();
        let mut producer = self.get_pooled_producer_mut(partition_id).await?;
        producer
            .send_batch(batch.inner, options)
            .await
            .map_err(Into::into)
    }

    /// Retrieves information about the Event Hub that the connection is associated with, including
    /// the number of partitions present and their identifiers.
    pub async fn get_event_hub_properties(
        &mut self,
    ) -> Result<EventHubProperties, azure_core::Error> {
        self.connection
            .get_properties(RP::from(self.options.retry_options.clone()))
            .await
    }

    /// Retrieves the set of identifiers for the partitions of an Event Hub.
    pub async fn get_partition_ids(&mut self) -> Result<Vec<String>, azure_core::Error> {
        self.connection
            .get_partition_ids(RP::from(self.options.retry_options.clone()))
            .await
    }

    /// Retrieves information about a specific partition for an Event Hub, including elements that
    /// describe the available events in the partition event stream.
    pub async fn get_partition_properties(
        &mut self,
        partition_id: &str,
    ) -> Result<PartitionProperties, azure_core::Error> {
        self.connection
            .get_partition_properties(partition_id, RP::from(self.options.retry_options.clone()))
            .await
    }

    /// Performs the task needed to clean up resources used by the [`EventHubProducerClient`],
    /// including ensuring that the client itself has been closed.
    ///
    /// This won't close the underlying connection if the connection was shared among multiple
    /// clients.
    pub async fn close(self) -> Result<(), azure_core::Error> {
        let mut result = Ok(());
        for (_, producer) in self.producer_pool {
            let res = producer.close().await.map_err(Into::into);
            result = result.and(res);
        }

        let res = self.connection.close_if_owned().await;
        result.and(res)
    }
}