-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventstore.go
88 lines (73 loc) · 1.92 KB
/
eventstore.go
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
package GoEventBus
import (
"fmt"
"log"
"sync"
)
// EventStore handles publishing and dispatching events
type EventStore struct {
Mutex sync.Mutex
Dispatcher *Dispatcher
Events *sync.Pool
}
// NewEventStore initializes an EventStore with a dispatcher and an event pool
func NewEventStore(dispatcher *Dispatcher) *EventStore {
return &EventStore{
Mutex: sync.Mutex{},
Dispatcher: dispatcher,
Events: &sync.Pool{
New: func() interface{} {
return &Event{} // Return a new, non-nil Event instance
},
},
}
}
// Publish adds an event to the event pool
func (eventstore *EventStore) Publish(event *Event) {
eventstore.Events.Put(event)
}
// Commit retrieves and processes an event from the pool
func (eventstore *EventStore) Commit() error {
curr := eventstore.Events.Get()
if curr == nil {
return fmt.Errorf("no events to process")
}
event, ok := curr.(*Event)
if !ok || event == nil {
return fmt.Errorf("invalid event type")
}
if eventstore.Dispatcher == nil {
return fmt.Errorf("dispatcher is nil")
}
// Check if the dispatcher has a handler for this event
handler, exists := (*eventstore.Dispatcher)[event.Projection]
if !exists {
return fmt.Errorf("no handler for event projection: %s", event.Projection)
}
// Execute the handler
_, err := handler(event.Args)
if err != nil {
return fmt.Errorf("error handling event: %w", err)
}
log.Printf("Event id: %s was successfully published", event.Id)
return nil
}
// Broadcast locks the store and processes each event in the pool
func (eventstore *EventStore) Broadcast() error {
eventstore.Mutex.Lock()
defer eventstore.Mutex.Unlock()
var lastErr error
// Try to commit an event
for {
err := eventstore.Commit()
if err != nil {
// If there are no more events to process, break the loop
if err.Error() != "" {
break
}
// Capture the last error if something else goes wrong
lastErr = err
}
}
return lastErr
}