-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsnapshot_store.go
102 lines (81 loc) · 1.99 KB
/
snapshot_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
package edatpgx
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v4"
"github.com/stackus/edat/core"
"github.com/stackus/edat/es"
"github.com/stackus/edat/log"
)
type SnapshotStore struct {
tableName string
client Client
strategy es.SnapshotStrategy
next es.AggregateRootStore
logger log.Logger
}
var _ es.AggregateRootStore = (*SnapshotStore)(nil)
func NewSnapshotStore(client Client, options ...SnapshotStoreOption) es.AggregateRootStoreMiddleware {
s := &SnapshotStore{
tableName: DefaultSnapshotTableName,
client: client,
strategy: es.DefaultSnapshotStrategy,
}
for _, option := range options {
option(s)
}
return func(next es.AggregateRootStore) es.AggregateRootStore {
s.next = next
return s
}
}
func (s *SnapshotStore) Load(ctx context.Context, root *es.AggregateRoot) error {
var snapshotName string
var data []byte
var version int
name := root.AggregateName()
id := root.AggregateID()
row := s.client.QueryRow(ctx, fmt.Sprintf(loadSnapshotSQL, s.tableName), name, id)
err := row.Scan(&snapshotName, &data, &version)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return s.next.Load(ctx, root)
}
return err
}
snapshot, err := core.DeserializeSnapshot(snapshotName, data)
if err != nil {
return err
}
err = root.LoadSnapshot(snapshot, version)
if err != nil {
return err
}
return s.next.Load(ctx, root)
}
func (s *SnapshotStore) Save(ctx context.Context, root *es.AggregateRoot) error {
err := s.next.Save(ctx, root)
if err != nil {
return err
}
if !s.strategy.ShouldSnapshot(root) {
return nil
}
snapshot, err := root.Aggregate().ToSnapshot()
if err != nil {
return err
}
data, err := core.SerializeSnapshot(snapshot)
if err != nil {
return err
}
name := root.AggregateName()
id := root.AggregateID()
version := root.PendingVersion()
_, err = s.client.Exec(ctx, fmt.Sprintf(saveSnapshotSQL, s.tableName), name, id, snapshot.SnapshotName(), data, version)
if err != nil {
return err
}
return nil
}