-
Notifications
You must be signed in to change notification settings - Fork 6
/
statestore.go
281 lines (257 loc) · 6.82 KB
/
statestore.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
package kinesumer
import (
"context"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/guregu/dynamo"
"github.com/pkg/errors"
)
//go:generate mockgen -source=statestore.go -destination=statestore_mock.go -package=kinesumer StateStore
// Error codes.
var (
ErrNoShardCache = errors.New("kinesumer: shard cache not found")
ErrEmptyShardIDs = errors.New("kinesumer: empty shard ids given")
)
type (
// StateStore is a distributed key-value store for managing states.
StateStore interface {
GetShards(ctx context.Context, stream string) (Shards, error)
UpdateShards(ctx context.Context, stream string, shards Shards) error
ListAllAliveClientIDs(ctx context.Context) ([]string, error)
RegisterClient(ctx context.Context, clientID string) error
DeregisterClient(ctx context.Context, clientID string) error
PingClientAliveness(ctx context.Context, clientID string) error
PruneClients(ctx context.Context) error
ListCheckPoints(ctx context.Context, stream string, shardIDs []string) (map[string]string, error)
UpdateCheckPoints(ctx context.Context, checkpoints []*ShardCheckPoint) error
}
db struct {
client *dynamo.DB
table *dynamo.Table
}
// stateStore implements the StateStore with AWS DynamoDB. (default)
stateStore struct {
app string
db *db
}
)
// newStateStore initializes the state store.
func newStateStore(cfg *Config) (StateStore, error) {
awsCfg := aws.NewConfig()
awsCfg.WithRegion(cfg.DynamoDBRegion)
if cfg.DynamoDBEndpoint != "" {
awsCfg.WithEndpoint(cfg.DynamoDBEndpoint)
}
sess, err := session.NewSession(awsCfg)
if err != nil {
return nil, errors.Wrap(err, "kinesumer: failed to create an aws session")
}
// Ping-like request to check if client can reach to DynamoDB.
client := dynamo.New(sess)
table := client.Table(cfg.DynamoDBTable)
if _, err := table.Describe().Run(); err != nil {
return nil, errors.Wrap(err, "kinesumer: client can't access to dynamodb")
}
return &stateStore{
app: cfg.App,
db: &db{
client: client,
table: &table,
},
}, nil
}
// GetShards fetches a cached shard list.
func (s *stateStore) GetShards(
ctx context.Context, stream string,
) (Shards, error) {
var (
key = buildShardCacheKey(s.app)
cache *stateShardCache
)
err := s.db.table.
Get("pk", key).
Range("sk", dynamo.Equal, stream).
Consistent(true).
OneWithContext(ctx, &cache)
if errors.Is(err, dynamo.ErrNotFound) {
return nil, errors.WithStack(ErrNoShardCache)
} else if err != nil {
return nil, errors.WithStack(err)
}
return cache.Shards, nil
}
// UpdateShards updates a shard list cache.
func (s *stateStore) UpdateShards(
ctx context.Context, stream string, shards Shards,
) error {
key := buildShardCacheKey(s.app)
err := s.db.table.
Update("pk", key).
Range("sk", stream).
Set("shards", shards).
RunWithContext(ctx)
if err != nil {
return errors.WithStack(err)
}
return nil
}
// ListAllAliveClientIDs fetches an id list of all alive clients.
func (s *stateStore) ListAllAliveClientIDs(ctx context.Context) ([]string, error) {
var (
key = buildClientKey(s.app)
now = time.Now()
clients []*stateClient
)
err := s.db.table.
Get("pk", key).
Range("sk", dynamo.Greater, " ").
Filter("last_update > ?", now.Add(-outdatedGap)).
Order(dynamo.Ascending).
AllWithContext(ctx, &clients)
if err != nil {
return nil, errors.WithStack(err)
}
var ids []string
for _, client := range clients {
ids = append(ids, client.ClientID)
}
return ids, nil
}
// RegisterClient registers a client to state store.
func (s *stateStore) RegisterClient(
ctx context.Context, clientID string,
) error {
var (
key = buildClientKey(s.app)
now = time.Now()
)
client := stateClient{
ClientKey: key,
ClientID: clientID,
LastUpdate: now,
}
if err := s.db.table.Put(client).RunWithContext(ctx); err != nil {
return errors.WithStack(err)
}
return nil
}
// DeregisterClient de-registers a client from the state store.
func (s *stateStore) DeregisterClient(
ctx context.Context, clientID string,
) error {
key := buildClientKey(s.app)
err := s.db.table.
Delete("pk", key).
Range("sk", clientID).
RunWithContext(ctx)
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (s *stateStore) PingClientAliveness(
ctx context.Context, clientID string,
) error {
var (
key = buildClientKey(s.app)
now = time.Now()
)
err := s.db.table.
Update("pk", key).
Range("sk", clientID).
Set("last_update", now).
RunWithContext(ctx)
if err != nil {
return errors.WithStack(err)
}
return nil
}
// PruneClients prune clients that have been inactive for a certain amount of time.
func (s *stateStore) PruneClients(ctx context.Context) error {
var (
key = buildClientKey(s.app)
now = time.Now()
)
var outdated []*stateClient
err := s.db.table.
Get("pk", key).
Range("last_update", dynamo.Less, now.Add(-outdatedGap)).
Index("index-client-key-last-update").
AllWithContext(ctx, &outdated)
if err != nil {
return errors.WithStack(err)
}
if len(outdated) == 0 {
return nil
}
var keys []dynamo.Keyed
for _, client := range outdated {
keys = append(
keys, dynamo.Keys{client.ClientKey, client.ClientID},
)
}
_, err = s.db.table.
Batch("pk", "sk").
Write().
Delete(keys...).
RunWithContext(ctx)
if err != nil {
return errors.WithStack(err)
}
return nil
}
// ListCheckPoints fetches check point sequence numbers for multiple shards.
func (s *stateStore) ListCheckPoints(
ctx context.Context, stream string, shardIDs []string,
) (map[string]string, error) {
if len(shardIDs) == 0 {
return nil, ErrEmptyShardIDs
}
var (
keys []dynamo.Keyed
seqMap = make(map[string]string)
)
for _, id := range shardIDs {
keys = append(
keys,
dynamo.Keys{buildCheckPointKey(s.app, stream), id},
)
}
var checkPoints []*stateCheckPoint
err := s.db.table.
Batch("pk", "sk").
Get(keys...).
AllWithContext(ctx, &checkPoints)
if errors.Is(err, dynamo.ErrNotFound) {
return seqMap, nil
} else if err != nil {
return nil, errors.WithStack(err)
}
for _, checkPoint := range checkPoints {
seqMap[checkPoint.ShardID] = checkPoint.SequenceNumber
}
return seqMap, nil
}
// UpdateCheckPoints updates the check point sequence numbers for multiple shards.
func (s *stateStore) UpdateCheckPoints(ctx context.Context, checkpoints []*ShardCheckPoint) error {
stateCheckPoints := make([]interface{}, len(checkpoints))
for i, checkpoint := range checkpoints {
stateCheckPoints[i] = stateCheckPoint{
StreamKey: buildCheckPointKey(s.app, checkpoint.Stream),
ShardID: checkpoint.ShardID,
SequenceNumber: checkpoint.SequenceNumber,
LastUpdate: checkpoint.UpdatedAt,
}
}
// TODO(proost): check written bytes
_, err := s.db.table.
Batch("pk", "sk").
Write().
Put(stateCheckPoints...).
RunWithContext(ctx)
if err != nil {
return errors.WithStack(err)
}
return nil
}