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
//! Core trait abstractions for publish-subscribe messaging with strongly-typed items.
//!
//! This module provides a set of traits that define the interfaces for publishing and subscribing
//! to typed messages across different messaging backends (NATS, Redis, etc.). These traits abstract
//! away the complexity of serialization, transport, and acknowledgment handling, allowing you to
//! write backend-agnostic code.
//!
//! # Core Traits
//!
//! - [`PubTrait`]: Publish strongly-typed items that implement [`serde::Serialize`]. Handles encoding
//! and delivery to the backing message broker.
//! - [`SubTrait`]: Subscribe to a stream of strongly-typed items that implement [`serde::de::DeserializeOwned`].
//! Returns a stream of decoded messages paired with acknowledgment handles.
//! - [`AckTrait`]: Acknowledge receipt of a message after it has been successfully processed.
//! - [`UnSubTrait`]: Cancel an active subscription gracefully.
//!
//! # Dispatch Patterns
//!
//! The library supports two primary usage patterns for different performance and flexibility trade-offs:
//!
//! ## Static Dispatch (Recommended)
//!
//! Use generic trait bounds to maintain full type information at compile time. This enables
//! monomorphization, inlining, and zero runtime overhead. Ideal for performance-critical paths.
//!
//! ### Publishing with Static Dispatch
//!
//! ```rust
//! use object_transfer::traits::PubTrait;
//! use serde::Serialize;
//!
//! #[derive(Serialize)]
//! struct Event {
//! id: u32,
//! message: String,
//! }
//!
//! async fn send_event<P: PubTrait<Item = Event> + Send + Sync + 'static>(publisher: &P, event: &Event) -> Result<(), Box<dyn std::error::Error>> {
//! publisher.publish(event).await?;
//! Ok(())
//! }
//! ```
//!
//! ### Subscribing with Static Dispatch
//!
//! ```rust
//! use object_transfer::traits::{SubTrait, AckTrait};
//! use serde::Deserialize;
//! use futures::stream::StreamExt;
//!
//! #[derive(Deserialize, Debug)]
//! struct Event {
//! id: u32,
//! message: String,
//! }
//!
//! async fn receive_events<S: SubTrait<Item = Event> + Send + Sync + 'static>(
//! subscriber: &S,
//! ) -> Result<(), Box<dyn std::error::Error>> {
//! let mut stream = subscriber.subscribe().await?;
//! while let Some(result) = stream.next().await {
//! match result {
//! Ok((event, ack)) => {
//! # println!("Received: {:?}", event);
//! ack.ack().await.ok();
//! }
//! Err(e) => eprintln!("Error: {:?}", e),
//! }
//! }
//! Ok(())
//! }
//! ```
//!
//! ### Relay Pattern with Generic Implementations
//!
//! A common pattern is to relay messages between publishers and subscribers:
//!
//! ```rust
//! use object_transfer::traits::{PubTrait, SubTrait};
//! use serde::{Serialize, Deserialize};
//! use futures::stream::StreamExt;
//!
//! #[derive(Serialize, Deserialize, Clone)]
//! struct Message {
//! id: u64,
//! content: String,
//! }
//!
//! async fn relay<P, S>(publisher: &P, subscriber: &S) -> Result<(), Box<dyn std::error::Error>>
//! where
//! P: PubTrait<Item = Message> + Send + Sync + 'static,
//! S: SubTrait<Item = Message> + Send + Sync + 'static,
//! {
//! let mut stream = subscriber.subscribe().await?;
//! while let Some(result) = stream.next().await {
//! if let Ok((msg, ack)) = result {
//! publisher.publish(&msg).await.ok();
//! ack.ack().await.ok();
//! }
//! }
//! Ok(())
//! }
//! ```
//!
//! ## Dynamic Dispatch (Trait Objects)
//!
//! Use trait objects for runtime polymorphism when the concrete type is unknown or must be
//! determined at runtime. This introduces a small runtime cost but provides maximum flexibility.
//! This pattern is common in plugin systems or when accepting multiple publisher/subscriber implementations.
//!
//! ### Publishing with Dynamic Dispatch
//!
//! ```rust
//! use std::sync::Arc;
//! use object_transfer::traits::PubTrait;
//! use serde::Serialize;
//!
//! #[derive(Serialize)]
//! struct Event {
//! id: u32,
//! data: String,
//! }
//!
//! async fn send_via_any_publisher(
//! publisher: Arc<dyn PubTrait<Item = Event, EncodeErr = serde_json::Error>>,
//! event: &Event,
//! ) -> Result<(), Box<dyn std::error::Error>> {
//! publisher.publish(event).await?;
//! Ok(())
//! }
//! ```
//!
//! ### Subscribing with Dynamic Dispatch
//!
//! ```rust
//! use std::sync::Arc;
//! use object_transfer::traits::{SubTrait, AckTrait};
//! use serde::Deserialize;
//! use futures::stream::StreamExt;
//!
//! #[derive(Deserialize, Debug)]
//! struct Event {
//! id: u32,
//! data: String,
//! }
//!
//! async fn receive_via_any_subscriber(
//! subscriber: Arc<dyn SubTrait<Item = Event, DecodeErr = serde_json::Error>>,
//! ) -> Result<(), Box<dyn std::error::Error>> {
//! let mut stream = subscriber.subscribe().await?;
//! while let Some(result) = stream.next().await {
//! match result {
//! Ok((event, ack)) => {
//! # println!("Received: {:?}", event);
//! ack.ack().await.ok();
//! }
//! Err(e) => eprintln!("Error: {:?}", e),
//! }
//! }
//! Ok(())
//! }
//! ```
//!
//! # Integration with Concrete Backends
//!
//! Concrete implementations of these traits are provided for different backends:
//! - NATS: See the [`crate::nats`] module (requires `nats` feature)
//! - Redis: See the [`crate::redis`] module (requires `redis` feature)
//!
//! # Error Handling
//!
//! Operations may fail for various reasons (encoding errors, network issues, etc.).
//! Each trait method returns a `Result` with a specific error type:
//!
//! - [`PubTrait::publish()`] returns [`crate::errors::PubError<Self::EncodeErr>`]
//! - [`SubTrait::subscribe()`] returns [`crate::errors::SubError<Self::DecodeErr>`]
//! - [`AckTrait::ack()`] returns [`crate::errors::AckError`]
//! - [`UnSubTrait::unsubscribe()`] returns [`crate::errors::UnSubError`]
//!
use Arc;
use async_trait;
use BoxStream;
use ;
use crate;
use crate;
use automock;
/// Abstraction for publishing typed items.
///
/// Implementors handle serialization and delivery to a concrete backend.
/// Acknowledge receipt of a message.
/// Subscription interface returning a stream of decoded items and ack handles.
/// Allows canceling a subscription.