This repository has been archived by the owner on May 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
372 lines (297 loc) · 8.95 KB
/
store.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
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
package mutantdb
import (
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/google/uuid"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
"golang.org/x/net/context"
)
var ErrNotFound = errors.New("not found")
type ErrConflict struct {
CurrentMutationID, ExpectedMutationID string
}
func (e *ErrConflict) Error() string {
return "conflict detected"
}
type Conn interface {
Begin(context.Context) (pgx.Tx, error)
Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
QueryRow(context.Context, string, ...any) pgx.Row
Query(context.Context, string, ...any) (pgx.Rows, error)
}
type Projection[T any] struct {
ID string `json:"entity_id"`
Data T `json:"entity_data"`
MutationID string `json:"mutation_id"`
DateCreated time.Time `json:"date_created"`
DateUpdated time.Time `json:"date_updated"`
}
type mutatorMap[T any] struct {
data map[string]Mutator[T]
mu sync.RWMutex
}
func (mm *mutatorMap[T]) Add(m Mutator[T]) {
mm.mu.Lock()
defer mm.mu.Unlock()
if mm.data == nil {
mm.data = make(map[string]Mutator[T])
}
mm.data[m.Name()] = m
}
func (mm *mutatorMap[T]) Get(name string) Mutator[T] {
mm.mu.RLock()
defer mm.mu.RUnlock()
if m, ok := mm.data[name]; ok {
return m
}
return nil
}
type store[T any] struct {
conn Conn
entityType *Type[T]
idGenerator func() (string, error)
mutators *mutatorMap[T]
}
type Store[T any] struct {
store[T]
}
func NewStore[T any](conn Conn, t *Type[T]) *Store[T] {
return &Store[T]{store[T]{
conn: conn,
entityType: t,
idGenerator: generateUUID,
mutators: &mutatorMap[T]{},
}}
}
func (s *Store[T]) WithIDGenerator(fn func() (string, error)) *Store[T] {
s.idGenerator = fn
return s
}
func (s *Store[T]) WithMutators(mutators ...Mutator[T]) *Store[T] {
for _, m := range mutators {
s.mutators.Add(m)
}
return s
}
func (s *store[T]) Conn() Conn {
return s.conn
}
func (s *store[T]) Tx(tx pgx.Tx) *store[T] {
return &store[T]{
conn: tx,
entityType: s.entityType,
idGenerator: s.idGenerator,
mutators: s.mutators,
}
}
func (s *store[T]) AppendAfter(ctx context.Context, entityID, mutationID string, mutations ...Mutation[T]) (Projection[T], error) {
return s.append(ctx, entityID, mutationID, mutations)
}
func (s *store[T]) Append(ctx context.Context, entityID string, mutations ...Mutation[T]) (Projection[T], error) {
return s.append(ctx, entityID, "", mutations)
}
func (s *store[T]) Get(ctx context.Context, id string) (Projection[T], error) {
var (
p Projection[T]
rawData json.RawMessage
)
p.ID = id
sql := `select mutation_id, entity_data, date_created, date_updated
from projections
where entity_id = $1 and entity_type = $2
limit 1`
err := s.conn.
QueryRow(ctx, sql, id, s.entityType.Name()).
Scan(&p.MutationID, &rawData, &p.DateCreated, &p.DateUpdated)
if errors.Is(err, pgx.ErrNoRows) {
return p, ErrNotFound
} else if err != nil {
return p, fmt.Errorf("mutantdb: failed to scan projection: %w", err)
}
if err = json.Unmarshal(rawData, &p.Data); err != nil {
return p, fmt.Errorf("mutantdb: failed to deserialize entity data: %w", err)
}
return p, nil
}
func (s *store[T]) GetAt(ctx context.Context, id, mutationID string) (Projection[T], error) {
p := Projection[T]{
ID: id,
MutationID: mutationID,
Data: s.entityType.New(),
}
sql := `select mutation_name, mutation_data, date_created
from mutations
where entity_id = $1 and entity_type = $2 and
seq <= (select seq from mutations where entity_id = $1 and entity_type = $2 and mutation_id = $3)`
rows, err := s.conn.Query(ctx, sql, id, s.entityType.Name(), mutationID)
if err != nil {
return p, fmt.Errorf("mutantdb: failed to query mutations: %w", err)
}
defer rows.Close()
for rows.Next() {
var (
err error
name string
mutData json.RawMessage
dateCreated time.Time
)
if err = rows.Scan(&name, &mutData, &dateCreated); err != nil {
return p, fmt.Errorf("mutantdb: failed to scan mutation: %w", err)
}
if p.DateCreated.IsZero() {
p.DateCreated = dateCreated
}
p.DateUpdated = dateCreated
m := s.mutators.Get(name)
if m == nil {
return p, fmt.Errorf("mutantdb: mutator %s %s not found", s.entityType.Name(), name)
}
p.Data, err = m.Apply(p.Data, mutData)
if err != nil {
return p, err
}
}
if err := rows.Err(); err != nil {
return p, fmt.Errorf("mutantdb: %w", err)
}
return p, nil
}
func (s *store[T]) GetAll(ctx context.Context) (Cursor[T], error) {
sql := `select entity_id, mutation_id, entity_data, date_created, date_updated
from projections
where entity_type = $1`
var (
c Cursor[T]
err error
)
c.rows, err = s.conn.Query(ctx, sql, s.entityType.Name())
if err != nil {
return c, fmt.Errorf("mutantdb: failed to query projections: %w", err)
}
return c, nil
}
func (s *store[T]) append(ctx context.Context, entityID, expectedMutID string, mutations []Mutation[T]) (Projection[T], error) {
//--- projection to return
p := Projection[T]{
ID: entityID,
}
//--- check args
if len(mutations) == 0 {
return p, fmt.Errorf("mutantdb: no mutations to append")
}
//--- start tx
tx, err := s.conn.Begin(ctx)
if err != nil {
return p, fmt.Errorf("mutantdb: failed to begin transaction: %w", err)
}
defer tx.Rollback(ctx)
//--- tmp vars
var (
newEntity bool
rawEntityData json.RawMessage
entityData T
firstMutDateCreated time.Time
lastMutID string
lastMutDateCreated time.Time
)
//--- get current projection data
err = tx.QueryRow(ctx,
`select mutation_id, entity_data, date_created from projections where entity_id = $1 and entity_type = $2 limit 1`,
entityID, s.entityType.Name(),
).Scan(&lastMutID, &rawEntityData, &firstMutDateCreated)
if err == pgx.ErrNoRows {
newEntity = true
entityData = s.entityType.New()
} else if err != nil {
return p, fmt.Errorf("mutantdb: failed to get projection: %w", err)
} else {
if err := json.Unmarshal(rawEntityData, &entityData); err != nil {
return p, fmt.Errorf("mutantdb: failed to deserialize entity data: %w", err)
}
}
//--- detect conflicts
if expectedMutID != "" && expectedMutID != lastMutID {
return p, &ErrConflict{
CurrentMutationID: lastMutID,
ExpectedMutationID: expectedMutID,
}
}
//--- apply mutations
for _, mut := range mutations {
if entityData, err = mut.Apply(entityData); err != nil {
return p, fmt.Errorf("mutantdb: failed to apply mutation %s: %w", mut.Name(), err)
}
}
//--- validate entity data
if err := s.entityType.Validate(entityData); err != nil {
return p, fmt.Errorf("mutantdb: invalid entity data: %w", err)
}
//--- insert mutations
for _, mut := range mutations {
var rawMutData, rawMutMeta json.RawMessage
if mut.Data() != nil {
if rawMutData, err = json.Marshal(mut.Data()); err != nil {
return p, fmt.Errorf("mutantdb: failed to serialize mutation data: %w", err)
}
}
if mut.Meta() != nil {
if rawMutMeta, err = json.Marshal(mut.Meta()); err != nil {
return p, fmt.Errorf("mutantdb: failed to serialize mutation meta: %w", err)
}
}
// generate mutation id
lastMutID, err = s.idGenerator()
if err != nil {
return p, fmt.Errorf("mutantdb: failed to generate id: %w", err)
}
// TODO insert all mutations in one statement
if err = tx.QueryRow(ctx,
`insert into mutations (mutation_id, entity_id, entity_type, mutation_name, mutation_data, mutation_meta)
values ($1, $2, $3, $4, $5, $6)
returning date_created`,
lastMutID, entityID, s.entityType.Name(), mut.Name(), rawMutData, rawMutMeta,
).Scan(&lastMutDateCreated); err != nil {
return p, fmt.Errorf("mutantdb: failed to insert mutation: %w", err)
}
}
//--- upsert projection
rawEntityData, err = json.Marshal(entityData)
if err != nil {
return p, fmt.Errorf("mutantdb: failed to serialize projection data: %w", err)
}
if newEntity {
sql := `insert into projections (entity_id, entity_type, mutation_id, entity_data, date_created, date_updated)
values ($1, $2, $3, $4, $5, $6)`
if _, err = tx.Exec(ctx, sql, entityID, s.entityType.Name(), lastMutID, rawEntityData,
lastMutDateCreated, lastMutDateCreated); err != nil {
return p, fmt.Errorf("mutantdb: failed to insert projection: %w", err)
}
} else {
sql := `update projections set mutation_id = $1, entity_data = $2, date_updated = $3 where entity_id = $4 and entity_type = $5`
if _, err = tx.Exec(ctx, sql, lastMutID, rawEntityData, lastMutDateCreated,
entityID, s.entityType.Name()); err != nil {
return p, fmt.Errorf("mutantdb: failed to update projection: %w", err)
}
}
//--- commit tx
if err = tx.Commit(ctx); err != nil {
return p, fmt.Errorf("mutantdb: failed to commit transaction: %w", err)
}
//--- return projection
p.Data = entityData
p.MutationID = lastMutID
p.DateCreated = firstMutDateCreated
p.DateUpdated = lastMutDateCreated
return p, nil
}
func generateUUID() (string, error) {
id, err := uuid.NewRandom()
if err != nil {
return "", err
}
return id.String(), nil
}