avx-events 0.1.0

Event-driven architecture for Avila Experience Fabric - Pub/sub, event bus, and message patterns
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
# avx-events

**Event-driven architecture for Avila Experience Fabric**

[![Crates.io](https://img.shields.io/crates/v/avx-events.svg)](https://crates.io/crates/avx-events)
[![Documentation](https://docs.rs/avx-events/badge.svg)](https://docs.rs/avx-events)
[![License](https://img.shields.io/crates/l/avx-events.svg)](https://github.com/avilaops/arxis#license)

Pub/sub event bus, event sourcing, and message-driven patterns for building distributed AVX (Avila Experience) platform applications.

## Features

- **Event Bus**: In-memory and distributed pub/sub
- **Event Sourcing**: Append-only event store with replay
- **CQRS Support**: Command/Query separation patterns
- **Message Patterns**: Request/reply, fire-and-forget, broadcast
- **Dead Letter Queue**: Failed event handling
- **Event Replay**: Time-travel debugging and audit trails
- **Async/Await**: Built on Tokio for high concurrency
- **Type-Safe**: Strongly typed events with serde

## Installation

```toml
[dependencies]
avx-events = "0.1"
tokio = { version = "1", features = ["full"] }
```

## Quick Start

### Define Events

```rust
use avx_events::{Event, EventMetadata};
use serde::{Deserialize, Serialize};
use chrono::Utc;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserCreated {
    pub user_id: String,
    pub email: String,
    pub name: String,
}

impl Event for UserCreated {
    fn event_type(&self) -> &'static str {
        "user.created"
    }

    fn aggregate_id(&self) -> String {
        self.user_id.clone()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderPlaced {
    pub order_id: String,
    pub user_id: String,
    pub total: f64,
}

impl Event for OrderPlaced {
    fn event_type(&self) -> &'static str {
        "order.placed"
    }

    fn aggregate_id(&self) -> String {
        self.order_id.clone()
    }
}
```

### Create Event Bus

```rust
use avx_events::EventBus;

#[tokio::main]
async fn main() {
    let bus = EventBus::new();

    // Subscribe to events
    let mut subscriber = bus.subscribe::<UserCreated>().await;

    // Publish event
    bus.publish(UserCreated {
        user_id: "123".into(),
        email: "user@example.com".into(),
        name: "John Doe".into(),
    }).await.unwrap();

    // Receive event
    if let Some(event) = subscriber.recv().await {
        println!("Received: {:?}", event);
    }
}
```

### Multiple Subscribers

```rust
use avx_events::EventBus;

#[tokio::main]
async fn main() {
    let bus = EventBus::new();

    // Service 1: Send email
    let mut email_sub = bus.subscribe::<UserCreated>().await;
    tokio::spawn(async move {
        while let Some(event) = email_sub.recv().await {
            send_welcome_email(&event.email).await;
        }
    });

    // Service 2: Create profile
    let mut profile_sub = bus.subscribe::<UserCreated>().await;
    tokio::spawn(async move {
        while let Some(event) = profile_sub.recv().await {
            create_user_profile(&event.user_id).await;
        }
    });

    // Service 3: Analytics
    let mut analytics_sub = bus.subscribe::<UserCreated>().await;
    tokio::spawn(async move {
        while let Some(event) = analytics_sub.recv().await {
            track_signup_event(&event).await;
        }
    });

    // Publish event - all subscribers receive it
    bus.publish(UserCreated {
        user_id: "456".into(),
        email: "jane@example.com".into(),
        name: "Jane Smith".into(),
    }).await.unwrap();
}
```

### Event Sourcing

```rust
use avx_events::{EventStore, AggregateRoot};

// Define aggregate
pub struct UserAggregate {
    pub id: String,
    pub email: String,
    pub name: String,
    pub version: u64,
}

impl AggregateRoot for UserAggregate {
    type Event = UserEvent;

    fn apply(&mut self, event: Self::Event) {
        match event {
            UserEvent::Created(e) => {
                self.id = e.user_id;
                self.email = e.email;
                self.name = e.name;
            },
            UserEvent::EmailChanged(e) => {
                self.email = e.new_email;
            },
        }
        self.version += 1;
    }
}

// Use event store
#[tokio::main]
async fn main() {
    let store = EventStore::new();

    // Save events
    store.append("user-123", vec![
        UserEvent::Created(UserCreated { /* ... */ }),
        UserEvent::EmailChanged(EmailChanged { /* ... */ }),
    ]).await.unwrap();

    // Replay events to rebuild state
    let events = store.get_events("user-123", 0).await.unwrap();
    let mut user = UserAggregate::default();
    for event in events {
        user.apply(event);
    }

    println!("User state: {:?}", user);
}
```

### CQRS Pattern

```rust
use avx_events::{CommandHandler, QueryHandler};

// Commands (write side)
pub struct CreateUserCommand {
    pub email: String,
    pub name: String,
}

pub struct CreateUserHandler {
    event_bus: EventBus,
}

impl CommandHandler<CreateUserCommand> for CreateUserHandler {
    type Result = String; // user_id

    async fn handle(&self, cmd: CreateUserCommand) -> Result<Self::Result, Error> {
        let user_id = uuid::Uuid::new_v4().to_string();

        // Validate
        if cmd.email.is_empty() {
            return Err(Error::validation("Email required"));
        }

        // Publish event
        self.event_bus.publish(UserCreated {
            user_id: user_id.clone(),
            email: cmd.email,
            name: cmd.name,
        }).await?;

        Ok(user_id)
    }
}

// Queries (read side)
pub struct GetUserQuery {
    pub user_id: String,
}

pub struct GetUserHandler {
    read_model: UserReadModel,
}

impl QueryHandler<GetUserQuery> for GetUserHandler {
    type Result = UserView;

    async fn handle(&self, query: GetUserQuery) -> Result<Self::Result, Error> {
        self.read_model.find_by_id(&query.user_id).await
    }
}
```

### Topic-based Routing

```rust
use avx_events::TopicBus;

#[tokio::main]
async fn main() {
    let bus = TopicBus::new();

    // Subscribe to specific topics
    let mut user_sub = bus.subscribe("users.*").await;
    let mut order_sub = bus.subscribe("orders.*").await;
    let mut all_sub = bus.subscribe("*").await; // All events

    // Publish to topics
    bus.publish_to("users.created", UserCreated { /* ... */ }).await;
    bus.publish_to("orders.placed", OrderPlaced { /* ... */ }).await;

    // user_sub receives UserCreated only
    // order_sub receives OrderPlaced only
    // all_sub receives both
}
```

### Dead Letter Queue

```rust
use avx_events::{EventBus, DeadLetterQueue};

#[tokio::main]
async fn main() {
    let bus = EventBus::with_dlq(DeadLetterQueue::new());

    let mut subscriber = bus.subscribe::<UserCreated>().await;

    tokio::spawn(async move {
        while let Some(event) = subscriber.recv().await {
            if let Err(e) = process_event(event).await {
                // Event automatically goes to DLQ after retries
                eprintln!("Failed to process: {}", e);
            }
        }
    });

    // View DLQ
    let dlq_events = bus.dead_letter_queue().list().await;
    println!("Failed events: {}", dlq_events.len());

    // Retry from DLQ
    for event in dlq_events {
        bus.republish(event).await;
    }
}
```

### Request/Reply Pattern

```rust
use avx_events::RequestReplyBus;

#[tokio::main]
async fn main() {
    let bus = RequestReplyBus::new();

    // Responder
    tokio::spawn(async move {
        let mut requests = bus.listen::<GetUserRequest>().await;
        while let Some((req, reply)) = requests.recv().await {
            let user = fetch_user(&req.user_id).await;
            reply.send(user).await;
        }
    });

    // Requester
    let response = bus.request(GetUserRequest {
        user_id: "123".into(),
    }).await.unwrap();

    println!("User: {:?}", response);
}
```

## Distributed Event Bus

Use with Redis, NATS, or Kafka:

```rust
use avx_events::distributed::RedisEventBus;

#[tokio::main]
async fn main() {
    let bus = RedisEventBus::connect("redis://localhost:6379")
        .await
        .unwrap();

    // Now events are distributed across services
    bus.publish(UserCreated { /* ... */ }).await;
}
```

## Event Metadata

All events carry metadata:

```rust
pub struct EventEnvelope<T> {
    pub event: T,
    pub metadata: EventMetadata,
}

pub struct EventMetadata {
    pub event_id: String,
    pub event_type: String,
    pub aggregate_id: String,
    pub timestamp: i64,
    pub correlation_id: Option<String>,
    pub causation_id: Option<String>,
    pub user_id: Option<String>,
}
```

## Integration with AVX Ecosystem

```rust
use avx_events::EventBus;
use avx_telemetry::init_tracing;
use tracing::info;

#[tokio::main]
async fn main() {
    init_tracing();

    let bus = EventBus::new();

    let mut subscriber = bus.subscribe::<UserCreated>().await;
    tokio::spawn(async move {
        while let Some(event) = subscriber.recv().await {
            info!(
                user_id = %event.user_id,
                email = %event.email,
                "User created event received"
            );
        }
    });
}
```

## Testing

```rust
use avx_events::testing::MockEventBus;

#[tokio::test]
async fn test_user_service() {
    let bus = MockEventBus::new();
    let service = UserService::new(bus.clone());

    service.create_user("user@example.com", "User").await.unwrap();

    // Assert event was published
    let events = bus.published_events::<UserCreated>().await;
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].email, "user@example.com");
}
```

## Part of AVX Ecosystem

`avx-events` enables event-driven microservices:

- **avx-gateway**: Event-driven request processing
- **avx-telemetry**: Event logging and tracing
- **avx-api-core**: Domain events from business logic

## Examples

```bash
cargo run --example basic_pubsub
cargo run --example event_sourcing
cargo run --example cqrs
cargo run --example request_reply
cargo run --example distributed
```

## Performance

- **In-memory**: 100,000+ events/sec
- **Redis**: 10,000+ events/sec
- **Overhead**: < 1ms per event

## License

MIT OR Apache-2.0

See [LICENSE-MIT](../LICENSE-MIT) and [LICENSE-APACHE](../LICENSE-APACHE) for details.

## Links

- **Repository**: https://github.com/avilaops/arxis
- **Documentation**: https://docs.rs/avx-events
- **Crates.io**: https://crates.io/crates/avx-events
- **AVX Platform**: https://avilaops.com