intercom-rs 1.0.0

A fully typed async wrapper for NATS with JetStream support
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
# Intercom

A fully typed async wrapper for NATS with JetStream support.

## Features

- **Fully typed** publish/subscribe with turbofish syntax support
- **Pluggable codec** support (MessagePack default, JSON optional)
- **JetStream support** with builder pattern for all options
- **Push and pull consumers** with typed messages
- **Interest-based consumers** for complex routing scenarios
- **Work queues** with automatic acknowledgment tracking
- **Stream trait** for subscribers and consumers
- **Sink trait** for publishers

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
intercom = "0.1"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
futures = "0.3"
```

### Codec Features

By default, MessagePack is used for serialization. You can enable JSON support:

```toml
# MessagePack only (default)
intercom = "0.1"

# JSON only
intercom = { version = "0.1", default-features = false, features = ["json"] }

# Both codecs
intercom = { version = "0.1", features = ["json"] }
```

## Quick Start

### Basic Publish/Subscribe

```rust
use intercom::{Client, MsgPackCodec, Result};
use serde::{Deserialize, Serialize};
use futures::StreamExt;

#[derive(Debug, Serialize, Deserialize)]
struct MyMessage {
    content: String,
}

#[tokio::main]
async fn main() -> Result<()> {
    // Specify the codec type when creating the client
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    
    // Type-safe publish with turbofish syntax
    client.publish::<MyMessage>("subject", &MyMessage { 
        content: "hello".into() 
    }).await?;
    
    // Create a typed subscriber that implements Stream
    let mut subscriber = client.subscribe::<MyMessage>("subject").await?;
    
    while let Some(result) = subscriber.next().await {
        match result {
            Ok(msg) => println!("Received: {:?}", msg.payload),
            Err(e) => eprintln!("Error: {}", e),
        }
    }
    
    Ok(())
}
```

### Using JSON Codec

```rust
use intercom::{Client, JsonCodec, Result};  // Requires `json` feature
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct MyMessage { content: String }

async fn example() -> Result<()> {
    // Use JSON for human-readable serialization
    let client = Client::<JsonCodec>::connect("nats://localhost:4222").await?;
    
    client.publish::<MyMessage>("subject", &MyMessage { 
        content: "hello".into() 
    }).await?;
    
    Ok(())
}
```

### Request/Reply

```rust
use intercom::{Client, MsgPackCodec};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Request { query: String }

#[derive(Serialize, Deserialize)]
struct Response { result: String }

async fn example() -> intercom::Result<()> {
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    
    // Type-safe request/reply
    let response = client.request::<Request, Response>(
        "service",
        &Request { query: "hello".into() }
    ).await?;
    
    println!("Response: {}", response.result);
    Ok(())
}
```

### Publisher with Sink Trait

```rust
use intercom::{Client, MsgPackCodec};
use serde::{Deserialize, Serialize};
use futures::SinkExt;

#[derive(Serialize, Deserialize)]
struct MyMessage { content: String }

async fn example() -> intercom::Result<()> {
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    
    // Create a publisher that implements Sink
    let mut publisher = client.publisher::<MyMessage>("subject");
    
    // Use Sink trait methods
    publisher.send(MyMessage { content: "hello".into() }).await?;
    
    // Or batch with feed + flush
    publisher.feed(MyMessage { content: "msg1".into() }).await?;
    publisher.feed(MyMessage { content: "msg2".into() }).await?;
    publisher.flush().await?;
    
    Ok(())
}
```

### Queue Groups

```rust
use intercom::{Client, MsgPackCodec};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Task { id: u64 }

async fn example() -> intercom::Result<()> {
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    
    // Subscribe to a queue group - messages are load-balanced
    let subscriber = client.queue_subscribe::<Task>("tasks", "workers").await?;
    
    Ok(())
}
```

## JetStream

### Creating Streams with Builder Pattern

```rust
use intercom::{Client, MsgPackCodec, RetentionPolicy};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Event { id: u64, data: String }

async fn example() -> intercom::Result<()> {
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    let jetstream = client.jetstream();
    
    // Create a stream with builder pattern
    let stream = jetstream
        .stream_builder("events")
        .subjects(vec!["events.>".to_string()])
        .max_messages(1_000_000)
        .max_bytes(1024 * 1024 * 100)  // 100MB
        .max_age(std::time::Duration::from_secs(86400))  // 1 day
        .replicas(3)
        .create()
        .await?;
    
    Ok(())
}
```

### Publishing to JetStream

```rust
use intercom::{Client, MsgPackCodec};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Event { id: u64, data: String }

async fn example() -> intercom::Result<()> {
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    let jetstream = client.jetstream();
    
    // Publish with acknowledgment
    let ack = jetstream.publish::<Event>("events.user", &Event {
        id: 1,
        data: "user created".to_string(),
    }).await?;
    
    println!("Published to stream: {}, seq: {}", ack.stream, ack.sequence);
    
    // Async publish for batching
    let ack_future = jetstream.publish_async::<Event>("events.user", &Event {
        id: 2,
        data: "user updated".to_string(),
    }).await?;
    
    // Do other work, then await the ack
    let ack = ack_future.await?;
    
    Ok(())
}
```

### Pull Consumers

```rust
use intercom::{Client, MsgPackCodec};
use serde::{Deserialize, Serialize};
use futures::StreamExt;

#[derive(Serialize, Deserialize, Debug)]
struct Event { id: u64 }

async fn example() -> intercom::Result<()> {
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    let jetstream = client.jetstream();
    let stream = jetstream.get_stream("events").await?;
    
    // Create a pull consumer with turbofish syntax
    let consumer = stream
        .pull_consumer_builder::<Event>("my-consumer")
        .durable()
        .filter_subject("events.user.>")
        .ack_wait(std::time::Duration::from_secs(30))
        .max_deliver(3)
        .create()
        .await?;
    
    // Fetch a batch of messages
    let mut messages = consumer.fetch(10).await?;
    while let Some(result) = messages.next().await {
        let msg = result?;
        println!("Got: {:?}", msg.payload);
        msg.ack().await?;
    }
    
    // Or get a continuous stream
    let mut messages = consumer.messages().await?;
    while let Some(result) = messages.next().await {
        let msg = result?;
        // Process message
        msg.ack().await?;
    }
    
    Ok(())
}
```

### Push Consumers

```rust
use intercom::{Client, MsgPackCodec};
use serde::{Deserialize, Serialize};
use futures::StreamExt;

#[derive(Serialize, Deserialize, Debug)]
struct Event { id: u64 }

async fn example() -> intercom::Result<()> {
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    let jetstream = client.jetstream();
    let stream = jetstream.get_stream("events").await?;
    
    // Create a push consumer
    let consumer = stream
        .push_consumer_builder::<Event>("my-push-consumer")
        .deliver_subject("deliver.events")
        .deliver_group("workers")  // Queue group for load balancing
        .durable()
        .create()
        .await?;
    
    // Get messages
    let mut messages = consumer.messages().await?;
    while let Some(result) = messages.next().await {
        let msg = result?;
        println!("Got: {:?}", msg.payload);
        msg.ack().await?;
    }
    
    Ok(())
}
```

### Work Queues

```rust
use intercom::{Client, MsgPackCodec, WorkQueue};
use serde::{Deserialize, Serialize};
use futures::StreamExt;

#[derive(Serialize, Deserialize, Debug)]
struct Job { id: u64, payload: String }

async fn example() -> intercom::Result<()> {
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    let jetstream = client.jetstream();
    
    // Create a work queue
    let queue = WorkQueue::<Job, MsgPackCodec>::builder(&jetstream, "jobs")
        .max_messages(10_000)
        .create()
        .await?;
    
    // Push jobs
    queue.push(&Job { id: 1, payload: "do work".into() }).await?;
    
    // Option 1: Use as a Stream (pulls one job at a time)
    let mut queue = queue.into_stream().await?;
    while let Some(result) = queue.next().await {
        let job = result?;
        println!("Processing: {:?}", job.payload);
        job.ack().await?;  // Message removed from queue after ack
    }
    
    // Option 2: Pull a batch of jobs
    // let mut jobs = queue.pull(10).await?;
    // while let Some(result) = jobs.next().await {
    //     let job = result?;
    //     job.ack().await?;
    // }
    
    Ok(())
}
```

### Interest-Based Consumers

```rust
use intercom::{Client, MsgPackCodec, InterestQueue};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Event { id: u64, data: String }

async fn example() -> intercom::Result<()> {
    let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    let jetstream = client.jetstream();
    
    // Create an interest-based queue
    let queue = InterestQueue::<Event, MsgPackCodec>::builder(&jetstream, "events")
        .subject("events.>")
        .create()
        .await?;
    
    // Add multiple consumers - message is removed only when ALL acknowledge
    let consumer1 = queue.add_consumer("service-a").await?;
    let consumer2 = queue.add_consumer("service-b").await?;
    
    // Publish an event
    queue.publish(&Event { id: 1, data: "test".into() }).await?;
    
    Ok(())
}
```

## Message Acknowledgment

JetStream messages support various acknowledgment modes:

```rust
// Positive acknowledgment
msg.ack().await?;

// Double acknowledgment (waits for server confirmation)
msg.double_ack().await?;

// Negative acknowledgment (redelivery)
msg.nak().await?;

// Negative acknowledgment with delay
msg.nak_with_delay(std::time::Duration::from_secs(10)).await?;

// Mark as in progress (extend ack deadline)
msg.in_progress().await?;

// Terminate (message won't be redelivered)
msg.term().await?;
```

## Serialization

Intercom supports pluggable codecs:

- **MsgPackCodec** (default): Efficient binary serialization via rmp-serde
- **JsonCodec** (optional): Human-readable JSON via serde_json

All message types must implement `Serialize` and/or `Deserialize`:

```rust
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct MyMessage {
    id: u64,
    data: Vec<u8>,
    tags: Vec<String>,
}
```

## License

MIT