-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprovider.go
215 lines (200 loc) · 6.2 KB
/
provider.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
package persistencepg
import (
"context"
"database/sql"
"errors"
"fmt"
"log/slog"
"strings"
"github.com/asynkron/protoactor-go/persistence"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/oklog/ulid/v2"
"google.golang.org/protobuf/proto"
)
// Provider is the abstraction used for persistence
type Provider struct {
context context.Context
tableSchema Schemaer
snapshotInterval int
db *pgxpool.Pool
logger *slog.Logger
}
// New creates a new pg provider
func New(ctx context.Context, snapshotInterval int, table Schemaer, db *pgxpool.Pool, logger *slog.Logger) (*Provider, error) {
return &Provider{
context: ctx,
tableSchema: table,
snapshotInterval: snapshotInterval,
db: db,
logger: logger,
}, nil
}
// DeleteEvents removes all events from the provider
func (provider *Provider) DeleteEvents(_ string, _ int) {
}
func (provider *Provider) Restart() {
_ = provider.db.Ping(provider.context)
}
func (provider *Provider) GetSnapshotInterval() int {
return provider.snapshotInterval
}
func (provider *Provider) selectColumns() string {
return strings.Join([]string{
provider.tableSchema.ID(),
provider.tableSchema.Payload(),
provider.tableSchema.SequenceNumber(),
provider.tableSchema.ActorName(),
}, ",")
}
// GetEvents retrieves events from the provider
// eventIndexEnd 0 means max
// see https://github.com/asynkron/protoactor-go/blob/dev/persistence/plugin.go#L65
func (provider *Provider) GetEvents(actorName string, eventIndexStart int, eventIndexEnd int, callback func(e interface{})) {
tx, _ := provider.db.BeginTx(provider.context, pgx.TxOptions{IsoLevel: pgx.Serializable})
defer tx.Commit(provider.context)
query := fmt.Sprintf(
"SELECT %s FROM %s WHERE %s = $1 AND %s BETWEEN $2 AND $3 ORDER BY %s ASC",
provider.selectColumns(),
provider.tableSchema.JournalTableName(),
provider.tableSchema.ActorName(),
provider.tableSchema.SequenceNumber(),
provider.tableSchema.SequenceNumber(),
)
args := []interface{}{actorName, eventIndexStart, eventIndexEnd}
if eventIndexEnd == 0 {
query = fmt.Sprintf(
"SELECT %s FROM %s WHERE %s = $1 AND %s >= $2 ORDER BY %s ASC",
provider.selectColumns(),
provider.tableSchema.JournalTableName(),
provider.tableSchema.ActorName(),
provider.tableSchema.SequenceNumber(),
provider.tableSchema.SequenceNumber())
args = []interface{}{actorName, eventIndexStart}
}
rows, err := tx.Query(provider.context, query, args...)
if !errors.Is(err, sql.ErrNoRows) && err != nil {
provider.logger.Error(err.Error(), slog.String("actor_name", actorName))
return
}
for rows.Next() {
env := &envelope{}
if err := rows.Scan(&env.ID, &env.Message, &env.EventIndex, &env.ActorName); err != nil {
return
}
m, err := env.message()
if err != nil {
provider.logger.Error(err.Error(), slog.String("actor_name", actorName))
return
}
callback(m)
}
}
// 'executeTx' is a function that manages the lifecycle of a DB transaction.
// It takes a function 'op' that contains DB transaction operation to be executed.
func (provider *Provider) executeTx(op func(tx pgx.Tx) error) (err error) {
tx, err := provider.db.BeginTx(provider.context, pgx.TxOptions{IsoLevel: pgx.Serializable})
if err != nil {
return err
}
defer tx.Rollback(provider.context)
if err != nil {
return err
}
// Execute operation
err = op(tx)
if err != nil {
return err
}
// Everything went fine
return tx.Commit(provider.context)
}
func (provider *Provider) PersistEvent(actorName string, eventIndex int, snapshot proto.Message) {
envelope, err := newEnvelope(snapshot)
if err != nil {
provider.logger.Error(
fmt.Sprintf("persistence error: %s", err), slog.String("actor_name", actorName))
return
}
err = provider.executeTx(func(tx pgx.Tx) error {
_, err := tx.Exec(
provider.context,
fmt.Sprintf(
"INSERT INTO %s (%s) VALUES ($1, $2, $3, $4)",
provider.tableSchema.JournalTableName(), provider.selectColumns()),
ulid.Make().String(), string(envelope), eventIndex, actorName)
if err != nil {
return err
}
return nil
})
if err != nil {
provider.logger.Error(
fmt.Sprintf("persistence event / sql error: %s", err.Error()),
slog.String("actor_name", actorName))
return
}
}
func (provider *Provider) PersistSnapshot(actorName string, eventIndex int, snapshot proto.Message) {
envelope, err := newEnvelope(snapshot)
if err != nil {
provider.logger.Error(
fmt.Sprintf("persistence error: %s", err), slog.String("actor_name", actorName))
return
}
err = provider.executeTx(func(tx pgx.Tx) error {
_, err := tx.Exec(
provider.context,
fmt.Sprintf(
"INSERT INTO %s (%s) VALUES ($1, $2, $3, $4)",
provider.tableSchema.SnapshotTableName(), provider.selectColumns()),
ulid.Make().String(), string(envelope), eventIndex, actorName)
if err != nil {
return err
}
return nil
})
if err != nil {
provider.logger.Error(
fmt.Sprintf("persistence snapshot / sql error: %s", err.Error()),
slog.String("actor_name", actorName))
return
}
}
func (provider *Provider) GetSnapshot(actorName string) (snapshot interface{}, eventIndex int, ok bool) {
tx, _ := provider.db.BeginTx(provider.context, pgx.TxOptions{IsoLevel: pgx.Serializable})
defer tx.Commit(provider.context)
rows, err := tx.Query(
provider.context,
fmt.Sprintf(
"SELECT %s FROM %s WHERE %s = $1 ORDER BY %s DESC",
provider.selectColumns(),
provider.tableSchema.SnapshotTableName(),
provider.tableSchema.ActorName(),
provider.tableSchema.SequenceNumber(),
),
actorName)
defer rows.Close()
if !errors.Is(err, sql.ErrNoRows) && err != nil {
provider.logger.Error(err.Error(), slog.String("actor_name", actorName))
return nil, 0, false
}
for rows.Next() {
env := envelope{}
if err := rows.Scan(&env.ID, &env.Message, &env.EventIndex, &env.ActorName); err != nil {
return nil, 0, false
}
m, err := env.message()
if err != nil {
provider.logger.Error(err.Error(), slog.String("actor_name", actorName))
return nil, 0, false
}
return m, env.EventIndex, true
}
return nil, 0, false
}
func (provider *Provider) DeleteSnapshots(_ string, _ int) {
}
func (provider *Provider) GetState() persistence.ProviderState {
return provider
}