hexser 0.4.7

Zero-boilerplate hexagonal architecture with graph-based introspection
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
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
# CloudEvents-Compliant Event System for Hexser

## Overview

This document describes hexser's CloudEvents v1.0-compliant event system for transport-agnostic, standardized domain event publishing and consumption. The design integrates seamlessly with hexser's existing `DomainEvent` trait while providing CloudEvents-standard envelope, ports, and adapters for event-driven architectures.

**Revision History**
- 2025-10-09T14:51:00Z @AI: Initial design document for CloudEvents v1.0 compliance.

## Design Principles

1. **Standards Compliance**: Full CloudEvents v1.0 specification compliance
2. **Transport Agnostic**: Events work with HTTP, Kafka, AMQP, and other transports
3. **Separation of Concerns**: Domain events remain pure; transport concerns live in ports/adapters
4. **Backward Compatible**: Existing `DomainEvent` trait unchanged; new functionality is additive
5. **Zero Dependencies**: Native implementation without external CloudEvents crate
6. **Hexagonal Architecture**: Clear boundaries between domain, ports, and adapters

## Architecture

### Layer Responsibilities

**Domain Layer** (`hexser::domain::DomainEvent`)
- Existing trait for domain event semantics
- Provides `event_type()` and `aggregate_id()` methods
- Remains unchanged for backward compatibility

**Ports Layer** (`hexser::ports::events`)
- `CloudEventsEnvelope<T>`: CloudEvents v1.0-compliant wrapper struct
- `EventPublisher`: Port for publishing events
- `EventSubscriber`: Port for consuming events
- `EventCodec`: Port for serialization/deserialization
- `EventRouter`: Port for topic/subject resolution

**Adapters Layer** (`hexser::adapters`)
- `InMemoryEventBus`: Reference implementation for testing
- `JsonEventCodec`: CloudEvents JSON format codec
- Future: HTTP, Kafka, AMQP transport adapters

## CloudEvents v1.0 Specification

### CloudEventsEnvelope<T> Structure

The `CloudEventsEnvelope<T>` struct wraps domain events with CloudEvents v1.0 metadata:

```rust
pub struct CloudEventsEnvelope<T> {
    // REQUIRED attributes (CloudEvents v1.0 spec)
    pub id: std::string::String,
    pub source: std::string::String,
    pub specversion: std::string::String,
    pub r#type: std::string::String,
    
    // OPTIONAL attributes
    pub datacontenttype: std::option::Option<std::string::String>,
    pub dataschema: std::option::Option<std::string::String>,
    pub subject: std::option::Option<std::string::String>,
    pub time: std::option::Option<std::string::String>,
    pub data: std::option::Option<T>,
    
    // Extension attributes
    pub extensions: std::collections::HashMap<std::string::String, std::string::String>,
}
```

### Required Attributes

**id** (String)
- Unique identifier for the event
- MUST be unique within the scope of the producer (source)
- Example: UUID, ULID, or source+timestamp hash
- Constraint: Non-empty string

**source** (String)
- Identifies the context in which the event occurred
- URI-reference format (absolute or relative)
- Examples: `/services/user-service`, `https://example.com/orders`
- Use for multi-tenant isolation: `/tenants/acme/users`

**specversion** (String)
- CloudEvents specification version
- MUST be `"1.0"` for this implementation
- Immutable constant

**type** (String)
- Describes the type of event
- Should be prefixed with reverse-DNS name for collision avoidance
- Examples: `com.example.user.created`, `org.hexser.order.shipped`
- Maps to `DomainEvent::event_type()` output

### Optional Attributes

**datacontenttype** (String)
- Media type of the `data` attribute
- Examples: `application/json`, `application/octet-stream`
- Defaults to `application/json` if data is JSON-serializable

**dataschema** (String)
- URI identifying the schema that `data` adheres to
- Examples: `https://example.com/schemas/user.json`, JSON Schema URI

**subject** (String)
- Describes the subject of the event in the context of the source
- Examples: user ID, order ID, resource path
- Can map to `DomainEvent::aggregate_id()`

**time** (String)
- Timestamp when the event occurred
- MUST use RFC3339 format: `2025-10-09T14:51:00Z`
- If omitted, consumer may use receipt time

**data** (Generic T)
- The actual domain event payload
- Type T typically implements `DomainEvent` trait
- Can be any serializable type

### Extension Attributes

Extension attributes allow vendor-specific or application-specific metadata:
- Stored in `extensions` HashMap
- Keys MUST NOT start with `ce-` (reserved for CloudEvents)
- Examples: `traceparent`, `correlationid`, `tenantid`

## Integration with Existing DomainEvent Trait

The CloudEvents system integrates with the existing `DomainEvent` trait through the envelope pattern:

```rust
// Existing domain event (unchanged)
struct UserCreated {
    user_id: std::string::String,
    email: std::string::String,
    timestamp: u64,
}

impl hexser::domain::DomainEvent for UserCreated {
    fn event_type(&self) -> &str {
        "com.example.user.created"
    }
    
    fn aggregate_id(&self) -> std::string::String {
        self.user_id.clone()
    }
}

// Wrap in CloudEvents envelope for transport
let event = UserCreated {
    user_id: std::string::String::from("user-123"),
    email: std::string::String::from("user@example.com"),
    timestamp: 1696867860,
};

let envelope = hexser::ports::events::CloudEventsEnvelope {
    id: std::string::String::from("evt-001"),
    source: std::string::String::from("/services/user-service"),
    specversion: std::string::String::from("1.0"),
    r#type: event.event_type().to_string(),
    subject: std::option::Option::Some(event.aggregate_id()),
    time: std::option::Option::Some(std::string::String::from("2025-10-09T14:51:00Z")),
    data: std::option::Option::Some(event),
    datacontenttype: std::option::Option::Some(std::string::String::from("application/json")),
    dataschema: std::option::Option::None,
    extensions: std::collections::HashMap::new(),
};
```

## Port Definitions

### EventPublisher

Publishes CloudEvents-wrapped domain events to a transport:

```rust
pub trait EventPublisher<T> {
    fn publish(
        &self,
        envelope: &hexser::ports::events::CloudEventsEnvelope<T>,
    ) -> hexser::HexResult<()>;
    
    fn publish_batch(
        &self,
        envelopes: &[hexser::ports::events::CloudEventsEnvelope<T>],
    ) -> hexser::HexResult<()>;
}
```

### EventSubscriber

Consumes CloudEvents from a transport with back-pressure support:

```rust
pub trait EventSubscriber<T> {
    fn subscribe(
        &mut self,
        topic: &str,
        handler: Box<dyn Fn(hexser::ports::events::CloudEventsEnvelope<T>) -> hexser::HexResult<()>>,
    ) -> hexser::HexResult<()>;
    
    fn poll(&mut self) -> hexser::HexResult<std::option::Option<hexser::ports::events::CloudEventsEnvelope<T>>>;
}
```

### EventCodec

Serializes and deserializes CloudEvents envelopes:

```rust
pub trait EventCodec<T> {
    fn encode(
        &self,
        envelope: &hexser::ports::events::CloudEventsEnvelope<T>,
    ) -> hexser::HexResult<std::vec::Vec<u8>>;
    
    fn decode(
        &self,
        bytes: &[u8],
    ) -> hexser::HexResult<hexser::ports::events::CloudEventsEnvelope<T>>;
}
```

### EventRouter

Resolves topics and subjects for routing events:

```rust
pub trait EventRouter {
    fn resolve_topic(&self, event_type: &str) -> hexser::HexResult<std::string::String>;
    
    fn resolve_subject(&self, aggregate_id: &str) -> std::option::Option<std::string::String>;
}
```

## Transport Bindings

### HTTP Binary Content Mode

In binary mode, CloudEvents attributes are mapped to HTTP headers with `ce-` prefix:

**Request:**
```
POST /events HTTP/1.1
Host: example.com
Content-Type: application/json
ce-specversion: 1.0
ce-type: com.example.user.created
ce-source: /services/user-service
ce-id: evt-001
ce-time: 2025-10-09T14:51:00Z
ce-subject: user-123

{"user_id":"user-123","email":"user@example.com","timestamp":1696867860}
```

**Mapping:**
- `data` → HTTP body
- `datacontenttype` → `Content-Type` header
- All other attributes → `ce-{attribute}` headers
- Extension attributes → `ce-{extension-name}` headers

### HTTP Structured Content Mode

In structured mode, the entire CloudEvent is in the HTTP body:

**Request:**
```
POST /events HTTP/1.1
Host: example.com
Content-Type: application/cloudevents+json

{
  "specversion": "1.0",
  "type": "com.example.user.created",
  "source": "/services/user-service",
  "id": "evt-001",
  "time": "2025-10-09T14:51:00Z",
  "subject": "user-123",
  "datacontenttype": "application/json",
  "data": {
    "user_id": "user-123",
    "email": "user@example.com",
    "timestamp": 1696867860
  }
}
```

**Mapping:**
- `Content-Type` → `application/cloudevents+json`
- Entire envelope serialized as JSON in body

### Kafka Binary Content Mode

In Kafka binary mode, CloudEvents attributes are mapped to message headers with `ce_` prefix:

**Message:**
```
Headers:
  ce_specversion: 1.0
  ce_type: com.example.user.created
  ce_source: /services/user-service
  ce_id: evt-001
  ce_time: 2025-10-09T14:51:00Z
  ce_subject: user-123
  content-type: application/json

Value:
  {"user_id":"user-123","email":"user@example.com","timestamp":1696867860}
```

**Mapping:**
- `data` → Kafka message value
- `datacontenttype` → `content-type` header
- All other attributes → `ce_{attribute}` headers (UTF-8 encoded)
- Extension attributes → `ce_{extension-name}` headers

### Kafka Structured Content Mode

In Kafka structured mode, the entire CloudEvent is in the message value:

**Message:**
```
Headers:
  content-type: application/cloudevents+json

Value:
  {
    "specversion": "1.0",
    "type": "com.example.user.created",
    "source": "/services/user-service",
    "id": "evt-001",
    "time": "2025-10-09T14:51:00Z",
    "subject": "user-123",
    "datacontenttype": "application/json",
    "data": {
      "user_id": "user-123",
      "email": "user@example.com",
      "timestamp": 1696867860
    }
  }
```

### AMQP Bindings (Future)

AMQP bindings use `cloudEvents_` prefix for message application-properties:
- Binary mode: `data` in body, attributes as `cloudEvents_{attribute}` properties
- Structured mode: entire event in body with `content-type: application/cloudevents+json`

## CloudEvents JSON Format

The mandatory JSON format for CloudEvents uses media type `application/cloudevents+json`:

### JSON Encoding Rules

1. **Required attributes**: Always present in JSON object
2. **Optional attributes**: Included only if non-None
3. **Extension attributes**: Included as top-level keys (not nested)
4. **Data encoding**:
   - JSON data: Direct inclusion in `data` field
   - Binary data: Base64-encoded in `data_base64` field
   - Other types: String representation in `data` field

### Example JSON Representation

```json
{
  "specversion": "1.0",
  "type": "com.example.user.created",
  "source": "/services/user-service",
  "id": "evt-001",
  "time": "2025-10-09T14:51:00Z",
  "subject": "user-123",
  "datacontenttype": "application/json",
  "dataschema": "https://example.com/schemas/user.json",
  "data": {
    "user_id": "user-123",
    "email": "user@example.com",
    "timestamp": 1696867860
  },
  "traceparent": "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
}
```

## CQRS Integration

### Emitting Events from Directives (Write Side)

Directives (commands) emit domain events wrapped in CloudEvents envelopes:

```rust
// Directive handler emits event after state change
struct CreateUserDirective {
    email: std::string::String,
}

impl hexser::DirectiveHandler for CreateUserDirective {
    type Output = std::string::String;
    
    fn handle(&self, context: &mut Context) -> hexser::HexResult<Self::Output> {
        // 1. Execute domain logic
        let user_id = context.user_repository.create_user(&self.email)?;
        
        // 2. Create domain event
        let event = UserCreated {
            user_id: user_id.clone(),
            email: self.email.clone(),
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs(),
        };
        
        // 3. Wrap in CloudEvents envelope
        let envelope = hexser::ports::events::CloudEventsEnvelope {
            id: uuid::Uuid::new_v4().to_string(),
            source: std::string::String::from("/services/user-service"),
            specversion: std::string::String::from("1.0"),
            r#type: event.event_type().to_string(),
            subject: std::option::Option::Some(event.aggregate_id()),
            time: std::option::Option::Some(format_rfc3339(std::time::SystemTime::now())),
            data: std::option::Option::Some(event),
            datacontenttype: std::option::Option::Some(std::string::String::from("application/json")),
            dataschema: std::option::Option::None,
            extensions: std::collections::HashMap::new(),
        };
        
        // 4. Publish event
        context.event_publisher.publish(&envelope)?;
        
        std::result::Result::Ok(user_id)
    }
}
```

### Consuming Events for Queries (Read Side)

Query models subscribe to events and update projections:

```rust
// Query model subscriber updates read model
struct UserQueryProjection {
    users: std::collections::HashMap<std::string::String, UserView>,
}

impl UserQueryProjection {
    fn handle_user_created(
        &mut self,
        envelope: hexser::ports::events::CloudEventsEnvelope<UserCreated>,
    ) -> hexser::HexResult<()> {
        if let std::option::Option::Some(event) = envelope.data {
            let view = UserView {
                id: event.user_id.clone(),
                email: event.email.clone(),
                created_at: envelope.time.unwrap_or_default(),
            };
            self.users.insert(event.user_id, view);
        }
        std::result::Result::Ok(())
    }
}

// Subscribe to events
let mut subscriber = InMemoryEventBus::new();
subscriber.subscribe(
    "user.events",
    std::boxed::Box::new(|envelope| {
        projection.handle_user_created(envelope)
    }),
)?;
```

## Security and Reliability

### Idempotency

Use the `id` attribute for idempotency:
- Generate deterministic IDs: `{source}:{aggregate_id}:{sequence}`
- Consumer tracks processed event IDs to prevent duplicate processing
- Store ID + checksum for verification

### Retry Policy

Recommended retry strategy:
1. Exponential backoff: 1s, 2s, 4s, 8s, 16s
2. Maximum retry count: 5 attempts
3. Dead letter queue after max retries
4. Use `id` for deduplication across retries

### Message Size Limits

- Recommended max event size: 1MB
- For larger payloads:
  - Store data externally (S3, blob storage)
  - Include reference URI in `dataschema` or extension attribute
  - Set `data` to metadata/summary only

### Signing and Encryption

CloudEvents supports signing and encryption via extensions:
- **Signing**: Use `signature` extension with JWS format
- **Encryption**: Use structured mode with encrypted `data` field
- Implement at codec layer or transport adapter level

### Multi-Tenant Isolation

Use `source` URI for tenant isolation:
- Format: `/tenants/{tenant-id}/{service}`
- Example: `/tenants/acme/user-service`
- Router can enforce tenant-specific routing rules

## Reference Implementations

### InMemoryEventBus

Simple in-memory event bus for testing:
- Implements `EventPublisher<T>` and `EventSubscriber<T>`
- Synchronous delivery (no concurrency)
- Topic-based routing
- No persistence (events lost on restart)

### JsonEventCodec

CloudEvents JSON format codec:
- Implements `EventCodec<T>` where T: serde::Serialize + serde::Deserialize
- Media type: `application/cloudevents+json`
- Handles all CloudEvents v1.0 attributes
- Supports extension attributes

## Testing Strategy

### Unit Tests

1. **CloudEventsEnvelope validation**:
   - Required attributes must be non-empty
   - `specversion` must be "1.0"
   - `time` must be valid RFC3339 format
   - Extension keys must not start with "ce-"

2. **Codec round-trip**:
   - Encode envelope to JSON
   - Decode JSON back to envelope
   - Assert equality (data preservation)

3. **Attribute mapping**:
   - `type` maps to `DomainEvent::event_type()`
   - `subject` maps to `DomainEvent::aggregate_id()`

### Integration Tests

1. **Publish/Subscribe flow**:
   - Publisher emits CloudEvents envelope
   - Subscriber receives and processes envelope
   - Verify event data integrity

2. **Transport binding simulation**:
   - Encode to HTTP headers/body
   - Decode from HTTP headers/body
   - Verify CloudEvents compliance

### Doc Tests

All port traits and structs include doc tests demonstrating usage without `use` statements.

## Future Enhancements

### Phase 2: HTTP Transport Adapters
- `HttpEventPublisher` (binary and structured modes)
- `HttpEventSubscriber` (webhook receiver)

### Phase 3: Kafka Transport Adapters
- `KafkaEventPublisher` (binary and structured modes)
- `KafkaEventSubscriber` (consumer group support)

### Phase 4: Advanced Features
- Event sourcing integration
- CQRS event store adapter
- CloudEvents discovery API
- Batch processing optimizations
- Distributed tracing integration (OpenTelemetry)

## References

- [CloudEvents v1.0 Specification]https://github.com/cloudevents/spec/blob/v1.0/spec.md
- [CloudEvents HTTP Protocol Binding]https://github.com/cloudevents/spec/blob/v1.0/http-protocol-binding.md
- [CloudEvents Kafka Protocol Binding]https://github.com/cloudevents/spec/blob/v1.0/kafka-protocol-binding.md
- [CloudEvents JSON Event Format]https://github.com/cloudevents/spec/blob/v1.0/json-format.md
- [RFC3339 Date and Time Format]https://tools.ietf.org/html/rfc3339