mockforge-mqtt 0.1.3

MQTT protocol support for MockForge
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
# MockForge MQTT

MQTT protocol support for MockForge with full broker simulation, topic management, and QoS handling.

This crate provides comprehensive MQTT mocking capabilities for IoT applications, pub/sub systems, and message queue testing. Perfect for testing MQTT clients, brokers, and IoT device communication without requiring external MQTT infrastructure.

## Features

- **Full MQTT Broker**: Complete MQTT 3.1.1 and 5.0 protocol support
- **Topic Management**: Hierarchical topic structure with wildcards
- **QoS Levels**: Support for QoS 0, 1, and 2 message delivery
- **Session Management**: Persistent sessions and clean session handling
- **Retained Messages**: Store and deliver retained messages
- **Will Messages**: Last will and testament message handling
- **Authentication**: Configurable client authentication
- **Metrics & Monitoring**: Comprehensive MQTT metrics collection
- **Fixture System**: YAML-based message templates and auto-publishing

## Quick Start

### Basic MQTT Broker

```rust,no_run
use mockforge_mqtt::{MqttBroker, MqttConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create broker configuration
    let config = MqttConfig {
        host: "127.0.0.1".to_string(),
        port: 1883,
        ..Default::default()
    };

    // Initialize broker
    let spec_registry = Arc::new(MqttSpecRegistry::new());
    let broker = MqttBroker::new(config, spec_registry);

    // Start the broker (this would typically run in a separate task)
    // broker.start().await?;

    Ok(())
}
```

### Testing with MQTT Clients

```rust,no_run
use rumqttc::{AsyncClient, MqttOptions, QoS};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to MockForge MQTT broker
    let mut mqtt_options = MqttOptions::new("test-client", "localhost", 1883);
    mqtt_options.set_keep_alive(Duration::from_secs(5));

    let (client, mut eventloop) = AsyncClient::new(mqtt_options, 10);

    // Subscribe to a topic
    client.subscribe("sensors/temperature", QoS::AtMostOnce).await?;

    // Publish a message
    client.publish("sensors/temperature", QoS::AtLeastOnce, false, "23.5").await?;

    // Handle events
    loop {
        match eventloop.poll().await {
            Ok(notification) => {
                println!("Received: {:?}", notification);
            }
            Err(e) => {
                println!("Error: {:?}", e);
                break;
            }
        }
    }

    Ok(())
}
```

## Core Components

### MqttBroker

The main broker implementation handling all MQTT protocol operations:

```rust,no_run
use mockforge_mqtt::{MqttBroker, MqttConfig, MqttSpecRegistry};

let config = MqttConfig {
    host: "0.0.0.0".to_string(),
    port: 1883,
    max_connections: 1000,
    max_packet_size: 1024 * 1024, // 1MB
    keep_alive_secs: 60,
    version: MqttVersion::V5_0,
};

let spec_registry = Arc::new(MqttSpecRegistry::new());
let broker = MqttBroker::new(config, spec_registry);
```

### Topic Management

Hierarchical topic structure with wildcard support:

```rust,no_run
use mockforge_mqtt::topics::TopicTree;

// Create topic tree
let topic_tree = TopicTree::new();

// Topics support wildcards:
// + (single level) and # (multi-level)
topic_tree.subscribe("client/sensor/+/temperature", qos);
topic_tree.subscribe("home/+/status", qos);
topic_tree.subscribe("iot/devices/#", qos);
```

### QoS Handling

Support for all MQTT Quality of Service levels:

```rust,no_run
use mockforge_mqtt::qos::{QoSHandler, MessageState};

// QoS 0: At most once (fire and forget)
let qos_0 = QoSHandler::publish_at_most_once(&message);

// QoS 1: At least once (acknowledged delivery)
let qos_1 = QoSHandler::publish_at_least_once(&message).await?;

// QoS 2: Exactly once (two-phase commit)
let qos_2 = QoSHandler::publish_exactly_once(&message).await?;
```

### Session Management

Persistent sessions for reliable messaging:

```rust,no_run
use mockforge_mqtt::broker::ClientSession;

// Clean session (default)
let clean_session = ClientSession {
    client_id: "client-1".to_string(),
    subscriptions: HashMap::new(),
    clean_session: true,
    connected_at: now,
    last_seen: now,
};

// Persistent session
let persistent_session = ClientSession {
    client_id: "client-2".to_string(),
    subscriptions: HashMap::new(),
    clean_session: false, // Session persists across connections
    connected_at: now,
    last_seen: now,
};
```

## Fixture System

Define message templates and auto-publishing rules using YAML:

```yaml
# mqtt-fixture.yaml
topics:
  - name: "sensors/temperature"
    retained: false
  - name: "devices/status"
    retained: true

fixtures:
  - topic: "sensors/temperature"
    payload: '{"sensor_id": "temp-001", "value": 23.5, "unit": "celsius"}'
    qos: 1
    retain: false

  - topic: "devices/status"
    payload: '{"device_id": "dev-001", "status": "online", "battery": 85}'
    qos: 0
    retain: true

auto_publish:
  - topic: "sensors/temperature"
    payload_template: '{"sensor_id": "temp-{{sensor_id}}", "value": {{temperature}}, "timestamp": "{{now}}"}'
    qos: 1
    interval_seconds: 30
    duration_seconds: 300
    variables:
      sensor_id: "001"
      temperature: "22.5"

  - topic: "iot/heartbeat"
    payload_template: '{"service": "{{service_name}}", "status": "alive", "uptime": {{uptime}}}'
    qos: 0
    interval_seconds: 60
    variables:
      service_name: "mockforge-mqtt"
      uptime: 3600
```

### Loading Fixtures

```rust,no_run
use mockforge_mqtt::{MqttBroker, MqttSpecRegistry};

// Create broker with fixture support
let spec_registry = Arc::new(MqttSpecRegistry::new());
let broker = MqttBroker::new(config, spec_registry);

// Load fixtures from file
broker.load_fixtures_from_file("mqtt-fixture.yaml").await?;

// Or create fixtures programmatically
use mockforge_mqtt::fixtures::{MqttFixture, AutoPublishConfig};

let fixture = MqttFixture {
    topics: vec![/* ... */],
    fixtures: vec![/* ... */],
    auto_publish: vec![/* ... */],
};

broker.add_fixture(fixture).await?;
```

## Supported MQTT Features

### Protocol Versions
- **MQTT 3.1.1**: Legacy protocol support
- **MQTT 5.0**: Latest protocol with enhanced features

### Message Types
- **CONNECT**: Client connection establishment
- **CONNACK**: Connection acknowledgment
- **PUBLISH**: Message publication
- **PUBACK/PUBREC/PUBREL/PUBCOMP**: QoS flow control
- **SUBSCRIBE**: Topic subscription
- **SUBACK**: Subscription acknowledgment
- **UNSUBSCRIBE**: Topic unsubscription
- **UNSUBACK**: Unsubscription acknowledgment
- **PINGREQ/PINGRESP**: Keep-alive handling
- **DISCONNECT**: Clean disconnection

### Advanced Features
- **Will Messages**: Last will and testament
- **Retained Messages**: Persistent topic messages
- **Topic Aliases**: Bandwidth optimization (MQTT 5.0)
- **Subscription Identifiers**: Subscription tracking (MQTT 5.0)
- **User Properties**: Custom metadata (MQTT 5.0)

## Configuration

### MqttConfig

```rust,no_run
use mockforge_mqtt::{MqttConfig, MqttVersion};

let config = MqttConfig {
    host: "0.0.0.0".to_string(),
    port: 1883,
    max_connections: 1000,
    max_packet_size: 1024 * 1024, // 1MB
    keep_alive_secs: 60,
    version: MqttVersion::V5_0,
};
```

### Environment Variables

```bash
# Server configuration
export MQTT_HOST=0.0.0.0
export MQTT_PORT=1883

# Connection limits
export MQTT_MAX_CONNECTIONS=1000
export MQTT_MAX_PACKET_SIZE=1048576

# Protocol settings
export MQTT_KEEP_ALIVE_SECS=60
export MQTT_VERSION=v5
```

## Testing Examples

### Publisher Testing

```rust,no_run
use rumqttc::{AsyncClient, MqttOptions, QoS};
use std::time::Duration;

#[tokio::test]
async fn test_mqtt_publisher() {
    // Start MockForge MQTT broker in background
    let broker = MqttBroker::new(MqttConfig::default(), Arc::new(MqttSpecRegistry::new()));
    tokio::spawn(async move { broker.start().await.unwrap() });

    // Give broker time to start
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Test publisher
    let mut mqtt_options = MqttOptions::new("test-publisher", "localhost", 1883);
    let (client, mut eventloop) = AsyncClient::new(mqtt_options, 10);

    // Publish test message
    client
        .publish("test/topic", QoS::AtLeastOnce, false, "Hello MQTT!")
        .await
        .unwrap();

    // Verify message was published (check broker state)
    // ... verification logic ...
}
```

### Subscriber Testing

```rust,no_run
use rumqttc::{AsyncClient, MqttOptions, QoS, Event};
use futures::StreamExt;

#[tokio::test]
async fn test_mqtt_subscriber() {
    // Start broker and publish test message
    // ... setup code ...

    // Create subscriber
    let mut mqtt_options = MqttOptions::new("test-subscriber", "localhost", 1883);
    let (client, mut eventloop) = AsyncClient::new(mqtt_options, 10);

    // Subscribe to topic
    client.subscribe("test/topic", QoS::AtMostOnce).await.unwrap();

    // Publish a message
    client.publish("test/topic", QoS::AtLeastOnce, false, "test message").await.unwrap();

    // Receive message
    let event = eventloop.next().await.unwrap().unwrap();
    match event {
        Event::Incoming(incoming) => {
            if let rumqttc::Packet::Publish(publish) = incoming {
                let payload = std::str::from_utf8(&publish.payload).unwrap();
                assert_eq!(payload, "test message");
            }
        }
        _ => panic!("Expected publish event"),
    }
}
```

### QoS Testing

```rust,no_run
use rumqttc::{AsyncClient, MqttOptions, QoS};

#[tokio::test]
async fn test_mqtt_qos_levels() {
    // Test QoS 0 (At most once)
    let (client, mut eventloop) = AsyncClient::new(MqttOptions::new("qos-test", "localhost", 1883), 10);
    client.subscribe("qos/test", QoS::AtMostOnce).await.unwrap();
    client.publish("qos/test", QoS::AtMostOnce, false, "QoS 0 message").await.unwrap();

    // Test QoS 1 (At least once)
    client.publish("qos/test", QoS::AtLeastOnce, false, "QoS 1 message").await.unwrap();

    // Test QoS 2 (Exactly once)
    client.publish("qos/test", QoS::ExactlyOnce, false, "QoS 2 message").await.unwrap();

    // Verify messages are received (broker should handle QoS flows)
}
```

### Retained Messages

```rust,no_run
use rumqttc::{AsyncClient, MqttOptions, QoS};

#[tokio::test]
async fn test_retained_messages() {
    // Publish retained message
    let (publisher, _) = AsyncClient::new(MqttOptions::new("publisher", "localhost", 1883), 10);
    publisher
        .publish("retained/topic", QoS::AtLeastOnce, true, "retained message")
        .await
        .unwrap();

    // New subscriber should receive retained message immediately
    let (subscriber, mut eventloop) = AsyncClient::new(MqttOptions::new("subscriber", "localhost", 1883), 10);
    subscriber.subscribe("retained/topic", QoS::AtMostOnce).await.unwrap();

    // Should receive retained message
    let event = eventloop.next().await.unwrap().unwrap();
    match event {
        Event::Incoming(incoming) => {
            if let rumqttc::Packet::Publish(publish) = incoming {
                assert!(publish.retain);
                let payload = std::str::from_utf8(&publish.payload).unwrap();
                assert_eq!(payload, "retained message");
            }
        }
        _ => panic!("Expected retained publish event"),
    }
}
```

## Performance

MockForge MQTT is optimized for testing scenarios:

- **In-Memory Operations**: Fast message routing without persistence
- **Concurrent Connections**: Handle multiple simultaneous MQTT clients
- **Low Latency**: Minimal overhead for message operations
- **Scalable**: Support for high-throughput IoT testing scenarios
- **Resource Efficient**: Configurable connection limits and cleanup

## Integration with MockForge

MockForge MQTT integrates seamlessly with the MockForge ecosystem:

- **MockForge Core**: Shared configuration and logging
- **MockForge CLI**: Command-line MQTT broker management
- **MockForge Data**: Enhanced message generation with templates
- **MockForge Observability**: Metrics and tracing integration

## Troubleshooting

### Common Issues

**Connection refused:**
- Ensure broker is started and listening on correct port
- Check firewall settings and port availability
- Verify client connection parameters

**Messages not received:**
- Check topic subscription patterns and wildcards
- Verify QoS levels match between publisher and subscriber
- Check retained message settings

**QoS issues:**
- Ensure broker supports requested QoS level
- Check network reliability for higher QoS levels
- Verify client acknowledgment handling

**Session persistence:**
- Check clean session flag settings
- Verify client ID consistency across connections
- Check session expiry settings

## Examples

See the [examples directory](https://github.com/SaaSy-Solutions/mockforge/tree/main/examples) for complete working examples including:

- Basic MQTT broker setup
- Publisher/subscriber testing patterns
- QoS level verification
- Retained message scenarios
- IoT device simulation
- Load testing with multiple clients

## Related Crates

- [`mockforge-core`]https://docs.rs/mockforge-core: Core mocking functionality
- [`rumqttc`]https://docs.rs/rumqttc: MQTT client library for testing
- [`rumqttd`]https://docs.rs/rumqttd: Underlying MQTT broker implementation

## License

Licensed under MIT OR Apache-2.0