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
//! Domain events and event store abstractions for event sourcing.
//!
//! ## Overview
//!
//! This module provides the core abstractions for working with domain events in an event sourcing
//! system. Domain events represent significant business occurrences that have happened in your
//! domain and serve as the source of truth for aggregate state.
//!
//! ## Key Concepts
//!
//! ### Domain Events
//!
//! Domain events are immutable records of business-relevant facts that have occurred. They are:
//!
//! - **Immutable** - Once created, events never change
//! - **Uniquely identifiable** - Each event has a unique ID for idempotency
//! - **Business-focused** - Express what happened in domain terms
//! - **Complete** - Contain all necessary information about the occurrence
//!
//! ### Event Store Events
//!
//! [`EventStoreEvent`] wraps domain events with additional metadata needed for persistence:
//!
//! - **Version** - Enables optimistic concurrency control
//! - **ID** - Extracted from the domain event for quick access
//! - **Domain Event** - The actual business event
//!
//! ## Eventastic Workflow
//!
//! Once you have domain events (created by your business logic), they flow through
//! the eventastic system in a well-defined lifecycle:
//!
//! ### **1. Event Creation**
//! Your business logic creates domain events representing what happened:
//! ```rust,ignore
//! // Your application code creates events
//! let event = AccountEvent::MoneyWithdrawn {
//! event_id: Uuid::new_v4(),
//! amount: 100
//! };
//! ```
//!
//! ### **2. Event Recording**
//! Events are recorded in [`Context<T>`](crate::aggregate::Context), which applies them to
//! the aggregate state and queues them for persistence:
//! ```rust,ignore
//! context.record_that(event)?; // Applies event and adds to uncommitted events
//! ```
//!
//! ### **3. Event Persistence**
//! The repository wraps events in [`EventStoreEvent`] and stores them transactionally:
//! ```rust,ignore
//! transaction.store(&mut context).await?; // Persists all uncommitted events
//! transaction.commit().await?;
//! ```
//!
//! ### **4. Event Replay**
//! Stored events are replayed to reconstruct aggregate state during loading:
//! ```rust,ignore
//! let aggregate = repository.load(&aggregate_id).await?; // Replays all events
//! ```
//!
//! This workflow ensures **exactly-once processing**, **ACID compliance**, and **full auditability**
//! of all business operations.
//!
//! **Note**: Command processing (validating commands and deciding which events to create)
//! is handled by your application code, not by this library.
//!
//! ## Idempotency
//!
//! Event IDs are crucial for idempotency - attempting to store the same event ID twice will either
//! succeed (if content is identical) or fail with an idempotency error (if content differs).
//! This ensures exactly-once processing of business events.
//!
//! ## Examples
//!
//! For complete examples showing events in context, see:
//! - The [banking example](https://github.com/jdon/eventastic/tree/main/examples/bank) for production patterns
//! - [`crate::aggregate`] module documentation for how events are applied to aggregates
//! - [`crate::repository`] module documentation for event persistence patterns
use Debug;
/// A [`DomainEvent`] that has been wrapped with metadata for persistence.
///
/// This struct represents a domain event along with the metadata needed for storing
/// and retrieving it from the event store. It's used internally by the eventastic
/// framework to manage event persistence and concurrency control.
///
/// ## Fields
///
/// - **`id`** - The unique identifier extracted from the domain event, used for idempotency checking
/// - **`version`** - The version number of this event within the aggregate's event stream
/// - **`event`** - The actual domain event containing the business data
///
/// ## Versioning and Concurrency
///
/// The `version` field enables optimistic concurrency control. When multiple transactions
/// try to modify the same aggregate simultaneously, version conflicts are detected and
/// one transaction will fail with an [`OptimisticConcurrency`](crate::aggregate::SaveError::OptimisticConcurrency) error.
///
/// ## Usage
///
/// `EventStoreEvent` is typically created automatically when you call
/// [`Context::record_that()`](crate::aggregate::Context::record_that) or retrieved
/// when replaying events to reconstruct aggregate state.
///
/// ```rust
/// use eventastic::event::{DomainEvent, EventStoreEvent};
///
/// #[derive(Clone, PartialEq, Eq, Debug)]
/// enum MyEvent {
/// Created { event_id: String, value: i32 },
/// }
///
/// impl DomainEvent for MyEvent {
/// type EventId = String;
/// fn id(&self) -> &Self::EventId {
/// match self {
/// MyEvent::Created { event_id, .. } => event_id,
/// }
/// }
/// }
///
/// let domain_event = MyEvent::Created {
/// event_id: "evt-123".to_string(),
/// value: 42,
/// };
///
/// let store_event = EventStoreEvent::new(
/// "evt-123".to_string(),
/// 1, // version
/// domain_event,
/// );
///
/// assert_eq!(store_event.id(), "evt-123");
/// assert_eq!(store_event.version(), 1);
/// ```
/// A domain event represents something significant that happened in your domain.
///
/// Domain events are the building blocks of event sourcing. They capture
/// business-relevant facts that have occurred and are used to reconstruct
/// aggregate state through event replay.
///
/// ## Design Principles
///
/// When designing domain events, follow these principles:
///
/// - **Past tense naming** - Events describe what happened ("OrderCreated", not "CreateOrder")
/// - **Immutable** - Events should never change after creation
/// - **Complete** - Include all data needed to apply the change
/// - **Unique IDs** - Each event instance must have a unique identifier
/// - **Business-focused** - Express domain concepts, not technical details
///
/// ## Relationship to Aggregates
///
/// Domain events are closely tied to [`Aggregate`](crate::aggregate::Aggregate)s:
///
/// - Created by your business logic methods
/// - Recorded in [`Context<T>`](crate::aggregate::Context) via `record_that()`
/// - Automatically applied to aggregate state during recording
/// - Used to reconstruct aggregate state through event replay
///
/// ## Idempotency and Event IDs
///
/// Event IDs are crucial for ensuring exactly-once processing. The eventastic framework
/// uses these IDs to detect duplicate events and maintain system consistency.
///
/// ## String ID Example
///
/// ```rust
/// use eventastic::event::DomainEvent;
///
/// #[derive(Clone, PartialEq, Eq, Debug)]
/// enum OrderEvent {
/// Created { event_id: String, order_id: String, customer_id: String },
/// ItemAdded { event_id: String, item_id: String, quantity: u32 },
/// Shipped { event_id: String, tracking_number: String },
/// }
///
/// impl DomainEvent for OrderEvent {
/// type EventId = String;
///
/// fn id(&self) -> &Self::EventId {
/// match self {
/// OrderEvent::Created { event_id, .. } => event_id,
/// OrderEvent::ItemAdded { event_id, .. } => event_id,
/// OrderEvent::Shipped { event_id, .. } => event_id,
/// }
/// }
/// }
///
/// // Create some events
/// let created_event = OrderEvent::Created {
/// event_id: "evt-1".to_string(),
/// order_id: "order-123".to_string(),
/// customer_id: "customer-456".to_string(),
/// };
///
/// let item_added_event = OrderEvent::ItemAdded {
/// event_id: "evt-2".to_string(),
/// item_id: "item-789".to_string(),
/// quantity: 2,
/// };
///
/// // Access event IDs
/// assert_eq!(created_event.id(), "evt-1");
/// assert_eq!(item_added_event.id(), "evt-2");
///
/// // Events can be compared for equality
/// let created_event_copy = created_event.clone();
/// assert_eq!(created_event, created_event_copy);
/// ```
///
/// ## Using Different ID Types
///
/// Domain events can use different types for their IDs:
///
/// ```rust
/// use eventastic::event::DomainEvent;
///
/// // Using numeric IDs
/// #[derive(Clone, PartialEq, Eq, Debug)]
/// enum UserEvent {
/// Registered { event_id: u64, user_id: u64, email: String },
/// EmailChanged { event_id: u64, new_email: String },
/// }
///
/// impl DomainEvent for UserEvent {
/// type EventId = u64;
///
/// fn id(&self) -> &Self::EventId {
/// match self {
/// UserEvent::Registered { event_id, .. } => event_id,
/// UserEvent::EmailChanged { event_id, .. } => event_id,
/// }
/// }
/// }
///
/// // Create an event with numeric ID
/// let user_event = UserEvent::Registered {
/// event_id: 12345,
/// user_id: 67890,
/// email: "user@example.com".to_string(),
/// };
///
/// assert_eq!(*user_event.id(), 12345);
/// ```