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
use crate::{
connection::Connection,
error::RustRabbitError,
message::{MassTransitEnvelope, MessageEnvelope},
};
use lapin::{
options::{BasicPublishOptions, ExchangeDeclareOptions, QueueDeclareOptions},
types::{AMQPValue, FieldTable},
BasicProperties, Channel, ExchangeKind,
};
use serde::Serialize;
use std::sync::Arc;
use tracing::debug;
use url::Url;
/// Publish options builder
#[derive(Debug, Clone, Default)]
pub struct PublishOptions {
pub mandatory: bool,
pub immediate: bool,
pub expiration: Option<String>,
pub priority: Option<u8>,
/// Enable MassTransit format conversion
pub masstransit: Option<MassTransitOptions>,
}
/// MassTransit-specific options for message publishing
#[derive(Debug, Clone)]
pub struct MassTransitOptions {
/// Message type in URN format: "urn:message:Namespace:TypeName"
/// or simple format: "Namespace:TypeName" (will be converted to URN)
pub message_type: String,
/// Optional correlation ID
pub correlation_id: Option<String>,
/// Optional source address (defaults to exchange/queue if not provided)
pub source_address: Option<String>,
/// Optional destination address (defaults to routing_key/queue if not provided)
pub destination_address: Option<String>,
}
impl PublishOptions {
pub fn new() -> Self {
Self::default()
}
pub fn mandatory(mut self) -> Self {
self.mandatory = true;
self
}
pub fn priority(mut self, priority: u8) -> Self {
self.priority = Some(priority);
self
}
pub fn with_expiration(mut self, expiration: impl Into<String>) -> Self {
self.expiration = Some(expiration.into());
self
}
pub fn with_priority(mut self, priority: u8) -> Self {
self.priority = Some(priority);
self
}
/// Enable MassTransit format conversion
/// Message type can be in format "Namespace:TypeName" or "urn:message:Namespace:TypeName"
pub fn with_masstransit(mut self, message_type: impl Into<String>) -> Self {
self.masstransit = Some(MassTransitOptions {
message_type: message_type.into(),
correlation_id: None,
source_address: None,
destination_address: None,
});
self
}
/// Enable MassTransit format with full options
pub fn with_masstransit_options(mut self, options: MassTransitOptions) -> Self {
self.masstransit = Some(options);
self
}
}
impl MassTransitOptions {
/// Create new MassTransit options with message type
pub fn new(message_type: impl Into<String>) -> Self {
Self {
message_type: message_type.into(),
correlation_id: None,
source_address: None,
destination_address: None,
}
}
/// Set correlation ID
pub fn with_correlation_id(mut self, correlation_id: impl Into<String>) -> Self {
self.correlation_id = Some(correlation_id.into());
self
}
/// Set source address
pub fn with_source_address(mut self, source_address: impl Into<String>) -> Self {
self.source_address = Some(source_address.into());
self
}
/// Set destination address
pub fn with_destination_address(mut self, destination_address: impl Into<String>) -> Self {
self.destination_address = Some(destination_address.into());
self
}
}
/// Simplified Publisher for message publishing
pub struct Publisher {
connection: Arc<Connection>,
}
impl Publisher {
/// Create a new publisher
pub fn new(connection: Arc<Connection>) -> Self {
Self { connection }
}
/// Publish message to an exchange
pub async fn publish_to_exchange<T>(
&self,
exchange: &str,
routing_key: &str,
message: &T,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError>
where
T: Serialize,
{
let channel = self.connection.create_channel().await?;
// Declare exchange (simplified - always topic for flexibility)
channel
.exchange_declare(
exchange,
ExchangeKind::Topic,
ExchangeDeclareOptions {
durable: true,
..Default::default()
},
FieldTable::default(),
)
.await?;
self.publish_message(&channel, exchange, routing_key, message, options)
.await
}
/// Publish message directly to a queue
pub async fn publish_to_queue<T>(
&self,
queue: &str,
message: &T,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError>
where
T: Serialize,
{
let channel = self.connection.create_channel().await?;
// Declare queue
channel
.queue_declare(
queue,
QueueDeclareOptions {
durable: true,
..Default::default()
},
FieldTable::default(),
)
.await?;
// Publish to default exchange with queue name as routing key
self.publish_message(&channel, "", queue, message, options)
.await
}
/// Internal method to publish message
/// Publishes raw payload with headers (retry_attempt and correlation_id in headers)
/// If MassTransit options are provided, wraps message in MassTransit envelope format
async fn publish_message<T>(
&self,
channel: &Channel,
exchange: &str,
routing_key: &str,
message: &T,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError>
where
T: Serialize,
{
let options = options.unwrap_or_default();
// Check if MassTransit conversion is requested
let payload = if let Some(mt_options) = &options.masstransit {
// Create MassTransit envelope
let mut envelope =
MassTransitEnvelope::with_message_type(message, &mt_options.message_type)
.map_err(|e| RustRabbitError::Serialization(e.to_string()))?;
// Set correlation ID if provided
if let Some(corr_id) = &mt_options.correlation_id {
envelope = envelope.with_correlation_id(corr_id.clone());
}
// Extract host from connection URL for MassTransit addresses
let host = self
.connection
.url()
.parse::<Url>()
.ok()
.and_then(|url| url.host_str().map(|h| h.to_string()))
.unwrap_or_else(|| "localhost".to_string());
// Set source address (default to exchange if not provided)
let source = mt_options
.source_address
.clone()
.unwrap_or_else(|| format!("rabbitmq://{}/{}", host, exchange));
envelope = envelope.with_source_address(source);
// Set destination address (default to routing key if not provided)
let dest = mt_options
.destination_address
.clone()
.unwrap_or_else(|| format!("rabbitmq://{}/{}", host, routing_key));
envelope = envelope.with_destination_address(dest);
// Serialize MassTransit envelope
serde_json::to_vec(&envelope)
.map_err(|e| RustRabbitError::Serialization(e.to_string()))?
} else {
// Serialize raw payload (no wrapper)
serde_json::to_vec(message)
.map_err(|e| RustRabbitError::Serialization(e.to_string()))?
};
// Build properties with headers
// Create headers with retry_attempt = 0 (first attempt)
let mut headers = FieldTable::default();
headers.insert("x-retry-attempt".into(), AMQPValue::LongLongInt(0));
let mut properties = BasicProperties::default()
.with_content_type("application/json".into())
.with_delivery_mode(2) // Persistent
.with_headers(headers);
if let Some(expiration) = options.expiration {
properties = properties.with_expiration(expiration.into());
}
if let Some(priority) = options.priority {
properties = properties.with_priority(priority);
}
// Publish message
let confirm = channel
.basic_publish(
exchange,
routing_key,
BasicPublishOptions {
mandatory: options.mandatory,
immediate: options.immediate,
},
&payload,
properties,
)
.await?;
// Wait for confirmation (simplified)
confirm.await?;
if options.masstransit.is_some() {
debug!(
"Published MassTransit message to exchange '{}' with routing key '{}'",
exchange, routing_key
);
} else {
debug!(
"Published message to exchange '{}' with routing key '{}'",
exchange, routing_key
);
}
Ok(())
}
/// Publish a message envelope to an exchange (includes retry metadata)
pub async fn publish_envelope_to_exchange<T>(
&self,
exchange: &str,
routing_key: &str,
envelope: &MessageEnvelope<T>,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError>
where
T: Serialize,
{
self.publish_to_exchange(exchange, routing_key, envelope, options)
.await
}
/// Publish a message envelope directly to a queue (includes retry metadata)
pub async fn publish_envelope_to_queue<T>(
&self,
queue: &str,
envelope: &MessageEnvelope<T>,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError>
where
T: Serialize,
{
self.publish_to_queue(queue, envelope, options).await
}
/// Create a message envelope with source tracking and publish to exchange
pub async fn publish_with_envelope<T>(
&self,
exchange: &str,
routing_key: &str,
payload: &T,
source_queue: &str,
max_retries: u32,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError>
where
T: Serialize + Clone,
{
let envelope = MessageEnvelope::with_source(
payload.clone(),
source_queue,
Some(exchange),
Some(routing_key),
Some("rust-rabbit-publisher"), // Publisher identifier
)
.with_max_retries(max_retries);
self.publish_envelope_to_exchange(exchange, routing_key, &envelope, options)
.await
}
/// Create a message envelope and publish directly to queue
pub async fn publish_with_envelope_to_queue<T>(
&self,
queue: &str,
payload: &T,
max_retries: u32,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError>
where
T: Serialize + Clone,
{
let envelope = MessageEnvelope::new(payload.clone(), queue).with_max_retries(max_retries);
self.publish_envelope_to_queue(queue, &envelope, options)
.await
}
/// Publish a message to MassTransit-compatible exchange
/// This ensures the message format matches MassTransit's expectations
///
/// # Arguments
/// * `exchange` - Exchange name (MassTransit typically uses exchange names)
/// * `routing_key` - Routing key (often the message type name)
/// * `message` - The message payload to publish
/// * `message_type` - Message type name (e.g., "YourNamespace:YourMessageType") - required for MassTransit routing
/// * `options` - Optional publish options
///
/// # Example
/// ```rust,no_run
/// use rust_rabbit::{Connection, Publisher};
///
/// #[derive(serde::Serialize)]
/// struct OrderCreated {
/// order_id: u32,
/// amount: f64,
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let connection = Connection::new("amqp://localhost:5672").await?;
/// let publisher = Publisher::new(connection);
///
/// let order = OrderCreated { order_id: 123, amount: 99.99 };
/// publisher.publish_masstransit_to_exchange(
/// "order-exchange",
/// "order.created",
/// &order,
/// "Contracts:OrderCreated", // Message type for MassTransit
/// None
/// ).await?;
///
/// Ok(())
/// }
/// ```
pub async fn publish_masstransit_to_exchange<T>(
&self,
exchange: &str,
routing_key: &str,
message: &T,
message_type: &str,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError>
where
T: Serialize,
{
let channel = self.connection.create_channel().await?;
// Declare exchange (MassTransit typically uses topic exchanges)
channel
.exchange_declare(
exchange,
ExchangeKind::Topic,
ExchangeDeclareOptions {
durable: true,
..Default::default()
},
FieldTable::default(),
)
.await?;
// Extract host from connection URL for MassTransit addresses
let host = self
.connection
.url()
.parse::<Url>()
.ok()
.and_then(|url| url.host_str().map(|h| h.to_string()))
.unwrap_or_else(|| "localhost".to_string());
// Create MassTransit envelope with message type
let envelope = MassTransitEnvelope::with_message_type(message, message_type)
.map_err(|e| RustRabbitError::Serialization(e.to_string()))?
.with_source_address(format!("rabbitmq://{}/{}", host, exchange))
.with_destination_address(format!("rabbitmq://{}/{}", host, routing_key));
// Serialize envelope
let payload = serde_json::to_vec(&envelope)
.map_err(|e| RustRabbitError::Serialization(e.to_string()))?;
// Build properties
let options = options.unwrap_or_default();
let mut properties = BasicProperties::default()
.with_content_type("application/json".into())
.with_delivery_mode(2) // Persistent
.with_headers(FieldTable::default());
if let Some(expiration) = options.expiration {
properties = properties.with_expiration(expiration.into());
}
if let Some(priority) = options.priority {
properties = properties.with_priority(priority);
}
// Publish message
let confirm = channel
.basic_publish(
exchange,
routing_key,
BasicPublishOptions {
mandatory: options.mandatory,
immediate: options.immediate,
},
&payload,
properties,
)
.await?;
confirm.await?;
debug!(
"Published MassTransit message to exchange '{}' with routing key '{}' (type: {})",
exchange, routing_key, message_type
);
Ok(())
}
/// Publish a message to MassTransit-compatible queue
/// This ensures the message format matches MassTransit's expectations
///
/// # Arguments
/// * `queue` - Queue name
/// * `message` - The message payload to publish
/// * `message_type` - Message type name (e.g., "YourNamespace:YourMessageType") - required for MassTransit routing
/// * `options` - Optional publish options
///
/// # Example
/// ```rust,no_run
/// use rust_rabbit::{Connection, Publisher};
///
/// #[derive(serde::Serialize)]
/// struct OrderCreated {
/// order_id: u32,
/// amount: f64,
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let connection = Connection::new("amqp://localhost:5672").await?;
/// let publisher = Publisher::new(connection);
///
/// let order = OrderCreated { order_id: 123, amount: 99.99 };
/// publisher.publish_masstransit_to_queue(
/// "order-queue",
/// &order,
/// "Contracts:OrderCreated", // Message type for MassTransit
/// None
/// ).await?;
///
/// Ok(())
/// }
/// ```
pub async fn publish_masstransit_to_queue<T>(
&self,
queue: &str,
message: &T,
message_type: &str,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError>
where
T: Serialize,
{
let channel = self.connection.create_channel().await?;
// Declare queue
channel
.queue_declare(
queue,
QueueDeclareOptions {
durable: true,
..Default::default()
},
FieldTable::default(),
)
.await?;
// Extract host from connection URL for MassTransit addresses
let host = self
.connection
.url()
.parse::<Url>()
.ok()
.and_then(|url| url.host_str().map(|h| h.to_string()))
.unwrap_or_else(|| "localhost".to_string());
// Create MassTransit envelope with message type
let envelope = MassTransitEnvelope::with_message_type(message, message_type)
.map_err(|e| RustRabbitError::Serialization(e.to_string()))?
.with_source_address(format!("rabbitmq://{}/{}", host, queue))
.with_destination_address(format!("rabbitmq://{}/{}", host, queue));
// Serialize envelope
let payload = serde_json::to_vec(&envelope)
.map_err(|e| RustRabbitError::Serialization(e.to_string()))?;
// Build properties
let options = options.unwrap_or_default();
let mut properties = BasicProperties::default()
.with_content_type("application/json".into())
.with_delivery_mode(2) // Persistent
.with_headers(FieldTable::default());
if let Some(expiration) = options.expiration {
properties = properties.with_expiration(expiration.into());
}
if let Some(priority) = options.priority {
properties = properties.with_priority(priority);
}
// Publish to default exchange with queue name as routing key
let confirm = channel
.basic_publish(
"", // Default exchange
queue,
BasicPublishOptions {
mandatory: options.mandatory,
immediate: options.immediate,
},
&payload,
properties,
)
.await?;
confirm.await?;
debug!(
"Published MassTransit message to queue '{}' (type: {})",
queue, message_type
);
Ok(())
}
/// Publish a MassTransit envelope (already created) to an exchange
/// Useful when you need full control over the envelope structure
pub async fn publish_masstransit_envelope_to_exchange(
&self,
exchange: &str,
routing_key: &str,
envelope: &MassTransitEnvelope,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError> {
let channel = self.connection.create_channel().await?;
// Declare exchange
channel
.exchange_declare(
exchange,
ExchangeKind::Topic,
ExchangeDeclareOptions {
durable: true,
..Default::default()
},
FieldTable::default(),
)
.await?;
// Serialize envelope
let payload = serde_json::to_vec(envelope)
.map_err(|e| RustRabbitError::Serialization(e.to_string()))?;
// Build properties
let options = options.unwrap_or_default();
let mut properties = BasicProperties::default()
.with_content_type("application/json".into())
.with_delivery_mode(2)
.with_headers(FieldTable::default());
if let Some(expiration) = options.expiration {
properties = properties.with_expiration(expiration.into());
}
if let Some(priority) = options.priority {
properties = properties.with_priority(priority);
}
let confirm = channel
.basic_publish(
exchange,
routing_key,
BasicPublishOptions {
mandatory: options.mandatory,
immediate: options.immediate,
},
&payload,
properties,
)
.await?;
confirm.await?;
debug!(
"Published MassTransit envelope to exchange '{}' with routing key '{}'",
exchange, routing_key
);
Ok(())
}
/// Publish a MassTransit envelope (already created) to a queue
/// Useful when you need full control over the envelope structure
pub async fn publish_masstransit_envelope_to_queue(
&self,
queue: &str,
envelope: &MassTransitEnvelope,
options: Option<PublishOptions>,
) -> Result<(), RustRabbitError> {
let channel = self.connection.create_channel().await?;
// Declare queue
channel
.queue_declare(
queue,
QueueDeclareOptions {
durable: true,
..Default::default()
},
FieldTable::default(),
)
.await?;
// Serialize envelope
let payload = serde_json::to_vec(envelope)
.map_err(|e| RustRabbitError::Serialization(e.to_string()))?;
// Build properties
let options = options.unwrap_or_default();
let mut properties = BasicProperties::default()
.with_content_type("application/json".into())
.with_delivery_mode(2)
.with_headers(FieldTable::default());
if let Some(expiration) = options.expiration {
properties = properties.with_expiration(expiration.into());
}
if let Some(priority) = options.priority {
properties = properties.with_priority(priority);
}
let confirm = channel
.basic_publish(
"",
queue,
BasicPublishOptions {
mandatory: options.mandatory,
immediate: options.immediate,
},
&payload,
properties,
)
.await?;
confirm.await?;
debug!("Published MassTransit envelope to queue '{}'", queue);
Ok(())
}
}