-
Notifications
You must be signed in to change notification settings - Fork 39
/
repository.go
228 lines (190 loc) · 5.52 KB
/
repository.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
package eventsource
import (
"context"
"errors"
"fmt"
"io"
"reflect"
"strings"
"time"
)
// Aggregate represents the aggregate root in the domain driven design sense.
// It represents the current state of the domain object and can be thought of
// as a left fold over events.
type Aggregate interface {
// On will be called for each event; returns err if the event could not be
// applied
On(event Event) error
}
// Repository provides the primary abstraction to saving and loading events
type Repository struct {
prototype reflect.Type
store Store
serializer Serializer
observers []func(Event)
writer io.Writer
debug bool
}
// Option provides functional configuration for a *Repository
type Option func(*Repository)
// WithDebug will generate additional logging useful for debugging
func WithDebug(w io.Writer) Option {
return func(r *Repository) {
r.writer = w
r.debug = true
}
}
// WithStore allows the underlying store to be specified; by default the repository
// uses an in-memory store suitable for testing only
func WithStore(store Store) Option {
return func(r *Repository) {
r.store = store
}
}
// WithSerializer specifies the serializer to be used
func WithSerializer(serializer Serializer) Option {
return func(r *Repository) {
r.serializer = serializer
}
}
// WithObservers allows observers to watch the saved events; Observers should invoke very short lived operations as
// calls will block until the observer is finished
func WithObservers(observers ...func(event Event)) Option {
return func(r *Repository) {
r.observers = append(r.observers, observers...)
}
}
// New creates a new Repository using the JSONSerializer and MemoryStore
func New(prototype Aggregate, opts ...Option) *Repository {
t := reflect.TypeOf(prototype)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
r := &Repository{
prototype: t,
store: newMemoryStore(),
serializer: NewJSONSerializer(),
}
for _, opt := range opts {
opt(r)
}
return r
}
func (r *Repository) logf(format string, args ...interface{}) {
if !r.debug {
return
}
now := time.Now().Format(time.StampMilli)
io.WriteString(r.writer, now)
io.WriteString(r.writer, " ")
fmt.Fprintf(r.writer, format, args...)
if !strings.HasSuffix(format, "\n") {
io.WriteString(r.writer, "\n")
}
}
// New returns a new instance of the aggregate
func (r *Repository) New() Aggregate {
return reflect.New(r.prototype).Interface().(Aggregate)
}
// Save persists the events into the underlying Store
func (r *Repository) Save(ctx context.Context, events ...Event) error {
if len(events) == 0 {
return nil
}
aggregateID := events[0].AggregateID()
history := make(History, 0, len(events))
for _, event := range events {
record, err := r.serializer.MarshalEvent(event)
if err != nil {
return err
}
history = append(history, record)
}
return r.store.Save(ctx, aggregateID, history...)
}
// Load retrieves the specified aggregate from the underlying store
func (r *Repository) Load(ctx context.Context, aggregateID string) (Aggregate, error) {
v, _, err := r.loadVersion(ctx, aggregateID)
return v, err
}
// loadVersion loads the specified aggregate from the store and returns both the Aggregate and the
// current version number of the aggregate
func (r *Repository) loadVersion(ctx context.Context, aggregateID string) (Aggregate, int, error) {
history, err := r.store.Load(ctx, aggregateID, 0, 0)
if err != nil {
return nil, 0, err
}
entryCount := len(history)
if entryCount == 0 {
return nil, 0, NewError(nil, ErrAggregateNotFound, "unable to load %v, %v", r.New(), aggregateID)
}
r.logf("Loaded %v event(s) for aggregate id, %v", entryCount, aggregateID)
aggregate := r.New()
version := 0
for _, record := range history {
event, err := r.serializer.UnmarshalEvent(record)
if err != nil {
return nil, 0, err
}
err = aggregate.On(event)
if err != nil {
eventType, _ := EventType(event)
return nil, 0, NewError(err, ErrUnhandledEvent, "aggregate was unable to handle event, %v", eventType)
}
version = event.EventVersion()
}
return aggregate, version, nil
}
// Dispatch executes the command specified
//
// Deprecated: Use Apply instead
func (r *Repository) Dispatch(ctx context.Context, command Command) error {
_, err := r.Apply(ctx, command)
return err
}
// Apply executes the command specified and returns the current version of the aggregate
func (r *Repository) Apply(ctx context.Context, command Command) (int, error) {
if command == nil {
return 0, errors.New("Command provided to Repository.Dispatch may not be nil")
}
aggregateID := command.AggregateID()
if aggregateID == "" {
return 0, errors.New("Command provided to Repository.Dispatch may not contain a blank AggregateID")
}
aggregate, version, err := r.loadVersion(ctx, aggregateID)
if err != nil {
aggregate = r.New()
}
h, ok := aggregate.(CommandHandler)
if !ok {
return 0, fmt.Errorf("Aggregate, %v, does not implement CommandHandler", aggregate)
}
events, err := h.Apply(ctx, command)
if err != nil {
return 0, err
}
err = r.Save(ctx, events...)
if err != nil {
return 0, err
}
if v := len(events); v > 0 {
version = events[v-1].EventVersion()
}
// publish events to observers
if r.observers != nil {
for _, event := range events {
for _, observer := range r.observers {
observer(event)
}
}
}
return version, nil
}
// Store returns the underlying Store
func (r *Repository) Store() Store {
return r.store
}
// Serializer returns the underlying serializer
func (r *Repository) Serializer() Serializer {
return r.serializer
}