forked from looplab/eventhorizon
/
eventstore.go
281 lines (237 loc) · 7.21 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
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
// Copyright (c) 2014 - The Event Horizon authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package memory
import (
"context"
"errors"
"fmt"
"sync"
"time"
eh "github.com/looplab/eventhorizon"
)
// ErrCouldNotSaveAggregate is when an aggregate could not be saved.
var ErrCouldNotSaveAggregate = errors.New("could not save aggregate")
// EventStore implements EventStore as an in memory structure.
type EventStore struct {
// The outer map is with namespace as key, the inner with aggregate ID.
db map[string]map[eh.UUID]aggregateRecord
dbMu sync.RWMutex
}
// NewEventStore creates a new EventStore using memory as storage.
func NewEventStore() *EventStore {
s := &EventStore{
db: map[string]map[eh.UUID]aggregateRecord{},
}
return s
}
// Save implements the Save method of the eventhorizon.EventStore interface.
func (s *EventStore) Save(ctx context.Context, events []eh.Event, originalVersion int) error {
if len(events) == 0 {
return eh.EventStoreError{
Err: eh.ErrNoEventsToAppend,
Namespace: eh.NamespaceFromContext(ctx),
}
}
// Build all event records, with incrementing versions starting from the
// original aggregate version.
dbEvents := make([]dbEvent, len(events))
aggregateID := events[0].AggregateID()
version := originalVersion
for i, event := range events {
// Only accept events belonging to the same aggregate.
if event.AggregateID() != aggregateID {
return eh.EventStoreError{
Err: eh.ErrInvalidEvent,
Namespace: eh.NamespaceFromContext(ctx),
}
}
// Only accept events that apply to the correct aggregate version.
if event.Version() != version+1 {
return eh.EventStoreError{
Err: eh.ErrIncorrectEventVersion,
Namespace: eh.NamespaceFromContext(ctx),
}
}
// Create the event record with timestamp.
dbEvents[i] = newDBEvent(event)
version++
}
ns := s.namespace(ctx)
s.dbMu.Lock()
defer s.dbMu.Unlock()
// Either insert a new aggregate or append to an existing.
if originalVersion == 0 {
aggregate := aggregateRecord{
AggregateID: aggregateID,
Version: len(dbEvents),
Events: dbEvents,
}
s.db[ns][aggregateID] = aggregate
} else {
// Increment aggregate version on insert of new event record, and
// only insert if version of aggregate is matching (ie not changed
// since loading the aggregate).
if aggregate, ok := s.db[ns][aggregateID]; ok {
if aggregate.Version != originalVersion {
return eh.EventStoreError{
Err: ErrCouldNotSaveAggregate,
Namespace: eh.NamespaceFromContext(ctx),
}
}
aggregate.Version += len(dbEvents)
aggregate.Events = append(aggregate.Events, dbEvents...)
s.db[ns][aggregateID] = aggregate
}
}
return nil
}
// Load implements the Load method of the eventhorizon.EventStore interface.
func (s *EventStore) Load(ctx context.Context, id eh.UUID) ([]eh.Event, error) {
s.dbMu.RLock()
defer s.dbMu.RUnlock()
// Ensure that the namespace exists.
s.dbMu.RUnlock()
ns := s.namespace(ctx)
s.dbMu.RLock()
aggregate, ok := s.db[ns][id]
if !ok {
return []eh.Event{}, nil
}
events := make([]eh.Event, len(aggregate.Events))
for i, dbEvent := range aggregate.Events {
events[i] = event{dbEvent: dbEvent}
}
return events, nil
}
// Replace implements the Replace method of the eventhorizon.EventStore interface.
func (s *EventStore) Replace(ctx context.Context, event eh.Event) error {
// Ensure that the namespace exists.
ns := s.namespace(ctx)
s.dbMu.RLock()
aggregate, ok := s.db[ns][event.AggregateID()]
if !ok {
s.dbMu.RUnlock()
return eh.ErrAggregateNotFound
}
s.dbMu.RUnlock()
// Find the event to replace.
idx := -1
for i, e := range aggregate.Events {
if e.Version == event.Version() {
idx = i
break
}
}
if idx == -1 {
return eh.ErrInvalidEvent
}
// Replace event.
s.dbMu.Lock()
defer s.dbMu.Unlock()
aggregate.Events[idx] = newDBEvent(event)
return nil
}
// RenameEvent implements the RenameEvent method of the eventhorizon.EventStore interface.
func (s *EventStore) RenameEvent(ctx context.Context, from, to eh.EventType) error {
// Ensure that the namespace exists.
ns := s.namespace(ctx)
s.dbMu.Lock()
defer s.dbMu.Unlock()
updated := map[eh.UUID]aggregateRecord{}
for id, aggregate := range s.db[ns] {
events := make([]dbEvent, len(aggregate.Events))
for i, e := range aggregate.Events {
if e.EventType == from {
// Rename any matching event.
e.EventType = to
}
events[i] = e
}
aggregate.Events = events
updated[id] = aggregate
}
for id, aggregate := range updated {
s.db[ns][id] = aggregate
}
return nil
}
// Helper to get the namespace and ensure that its data exists.
func (s *EventStore) namespace(ctx context.Context) string {
s.dbMu.Lock()
defer s.dbMu.Unlock()
ns := eh.NamespaceFromContext(ctx)
if _, ok := s.db[ns]; !ok {
s.db[ns] = map[eh.UUID]aggregateRecord{}
}
return ns
}
type aggregateRecord struct {
AggregateID eh.UUID
Version int
Events []dbEvent
// Snapshot eh.Aggregate
}
// dbEvent is the internal event record for the memory event store.
type dbEvent struct {
EventType eh.EventType
Data eh.EventData
Timestamp time.Time
AggregateType eh.AggregateType
AggregateID eh.UUID
Version int
}
// newDBEvent returns a new dbEvent for an event.
func newDBEvent(event eh.Event) dbEvent {
return dbEvent{
EventType: event.EventType(),
Data: event.Data(),
Timestamp: event.Timestamp(),
AggregateType: event.AggregateType(),
AggregateID: event.AggregateID(),
Version: event.Version(),
}
}
// event is the private implementation of the eventhorizon.Event interface
// for a memory event store.
type event struct {
dbEvent
}
// EventType implements the EventType method of the eventhorizon.Event interface.
func (e event) EventType() eh.EventType {
return e.dbEvent.EventType
}
// Data implements the Data method of the eventhorizon.Event interface.
func (e event) Data() eh.EventData {
return e.dbEvent.Data
}
// Timestamp implements the Timestamp method of the eventhorizon.Event interface.
func (e event) Timestamp() time.Time {
return e.dbEvent.Timestamp
}
// AggregateType implements the AggregateType method of the eventhorizon.Event interface.
func (e event) AggregateType() eh.AggregateType {
return e.dbEvent.AggregateType
}
// AggrgateID implements the AggrgateID method of the eventhorizon.Event interface.
func (e event) AggregateID() eh.UUID {
return e.dbEvent.AggregateID
}
// Version implements the Version method of the eventhorizon.Event interface.
func (e event) Version() int {
return e.dbEvent.Version
}
// String implements the String method of the eventhorizon.Event interface.
func (e event) String() string {
return fmt.Sprintf("%s@%d", e.dbEvent.EventType, e.dbEvent.Version)
}