-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
store.go
338 lines (280 loc) · 9.39 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
package upkeepstate
import (
"context"
"fmt"
"io"
"math/big"
"sync"
"time"
"github.com/smartcontractkit/chainlink-common/pkg/sqlutil"
ocr2keepers "github.com/smartcontractkit/chainlink-common/pkg/types/automation"
"github.com/smartcontractkit/chainlink-common/pkg/services"
ubig "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core"
"github.com/smartcontractkit/chainlink/v2/core/utils"
)
const (
UpkeepStateStoreServiceName = "UpkeepStateStore"
// CacheExpiration is the amount of time that we keep a record in the cache.
CacheExpiration = 24 * time.Hour
// GCInterval is the amount of time between cache cleanups.
GCInterval = 2 * time.Hour
// flushCadence is the amount of time between flushes to the DB.
flushCadence = 30 * time.Second
concurrentBatchCalls = 10
)
type ORM interface {
BatchInsertRecords(context.Context, []persistedStateRecord) error
SelectStatesByWorkIDs(context.Context, []string) ([]persistedStateRecord, error)
DeleteExpired(context.Context, time.Time) error
}
// UpkeepStateStore is the interface for managing upkeeps final state in a local store.
type UpkeepStateStore interface {
ocr2keepers.UpkeepStateUpdater
core.UpkeepStateReader
Start(context.Context) error
io.Closer
}
var (
_ UpkeepStateStore = &upkeepStateStore{}
newTickerFn = time.NewTicker
batchSize = 1000
)
// upkeepStateRecord is a record that we save in a local cache.
type upkeepStateRecord struct {
workID string
state ocr2keepers.UpkeepState
addedAt time.Time
}
// upkeepStateStore implements UpkeepStateStore.
// It stores the state of ineligible upkeeps in a local, in-memory cache.
// In addition, performed events are fetched by the scanner on demand.
type upkeepStateStore struct {
services.StateMachine
threadCtrl utils.ThreadControl
orm ORM
lggr logger.Logger
scanner PerformedLogsScanner
retention time.Duration
cleanCadence time.Duration
mu sync.RWMutex
cache map[string]*upkeepStateRecord
pendingRecords []persistedStateRecord
sem chan struct{}
batchSize int
}
// NewUpkeepStateStore creates a new state store
func NewUpkeepStateStore(orm ORM, lggr logger.Logger, scanner PerformedLogsScanner) *upkeepStateStore {
return &upkeepStateStore{
orm: orm,
lggr: lggr.Named(UpkeepStateStoreServiceName),
cache: map[string]*upkeepStateRecord{},
scanner: scanner,
retention: CacheExpiration,
cleanCadence: GCInterval,
threadCtrl: utils.NewThreadControl(),
pendingRecords: []persistedStateRecord{},
sem: make(chan struct{}, concurrentBatchCalls),
batchSize: batchSize,
}
}
// Start starts the upkeep state store.
// it does background cleanup of the cache every GCInterval,
// and flush records to DB every flushCadence.
func (u *upkeepStateStore) Start(pctx context.Context) error {
return u.StartOnce(UpkeepStateStoreServiceName, func() error {
if err := u.scanner.Start(pctx); err != nil {
return fmt.Errorf("failed to start scanner")
}
u.lggr.Debug("Starting upkeep state store")
u.threadCtrl.Go(func(ctx context.Context) {
ticker := time.NewTicker(utils.WithJitter(u.cleanCadence))
defer ticker.Stop()
flushTicker := newTickerFn(utils.WithJitter(flushCadence))
defer flushTicker.Stop()
for {
select {
case <-ticker.C:
if err := u.cleanup(ctx); err != nil {
u.lggr.Errorw("unable to clean old state values", "err", err)
}
ticker.Reset(utils.WithJitter(u.cleanCadence))
case <-flushTicker.C:
u.flush(ctx)
flushTicker.Reset(utils.WithJitter(flushCadence))
case <-ctx.Done():
u.flush(ctx)
return
}
}
})
return nil
})
}
func (u *upkeepStateStore) flush(ctx context.Context) {
u.mu.Lock()
cloneRecords := make([]persistedStateRecord, len(u.pendingRecords))
copy(cloneRecords, u.pendingRecords)
u.pendingRecords = []persistedStateRecord{}
u.mu.Unlock()
for i := 0; i < len(cloneRecords); i += u.batchSize {
end := i + u.batchSize
if end > len(cloneRecords) {
end = len(cloneRecords)
}
batch := cloneRecords[i:end]
u.sem <- struct{}{}
go func() {
if err := u.orm.BatchInsertRecords(ctx, batch); err != nil {
u.lggr.Errorw("error inserting records", "err", err)
}
<-u.sem
}()
}
}
// Close stops the service of pruning stale data; implements io.Closer
func (u *upkeepStateStore) Close() error {
return u.StopOnce(UpkeepStateStoreServiceName, func() error {
u.threadCtrl.Close()
return nil
})
}
func (u *upkeepStateStore) HealthReport() map[string]error {
return map[string]error{UpkeepStateStoreServiceName: u.Healthy()}
}
// SelectByWorkIDs returns the current state of the upkeep for the provided ids.
// If an id is not found, the state is returned as StateUnknown.
// We first check the cache, and if any ids are missing, we fetch them from the scanner and DB.
func (u *upkeepStateStore) SelectByWorkIDs(ctx context.Context, workIDs ...string) ([]ocr2keepers.UpkeepState, error) {
states, missing := u.selectFromCache(workIDs...)
if len(missing) == 0 {
// all ids were found in the cache
return states, nil
}
if err := u.fetchPerformed(ctx, missing...); err != nil {
return nil, err
}
if err := u.fetchFromDB(ctx, missing...); err != nil {
return nil, err
}
// at this point all values should be in the cache. if values are missing
// their state is indicated as unknown
states, _ = u.selectFromCache(workIDs...)
return states, nil
}
// SetUpkeepState updates the state of the upkeep.
// Currently we only store the state if the upkeep is ineligible.
// Performed events will be fetched on demand.
func (u *upkeepStateStore) SetUpkeepState(ctx context.Context, result ocr2keepers.CheckResult, _ ocr2keepers.UpkeepState) error {
if result.Eligible {
return nil
}
return u.upsertStateRecord(ctx, result.WorkID, ocr2keepers.Ineligible, uint64(result.Trigger.BlockNumber), result.UpkeepID.BigInt(), result.IneligibilityReason)
}
// upsertStateRecord inserts or updates a record for the provided
// check result. If an item already exists in the data store, the state and
// block are updated.
func (u *upkeepStateStore) upsertStateRecord(ctx context.Context, workID string, s ocr2keepers.UpkeepState, b uint64, upkeepID *big.Int, reason uint8) error {
u.mu.Lock()
defer u.mu.Unlock()
record, ok := u.cache[workID]
if !ok {
record = &upkeepStateRecord{
workID: workID,
addedAt: time.Now(),
}
}
record.state = s
u.cache[workID] = record
u.pendingRecords = append(u.pendingRecords, persistedStateRecord{
UpkeepID: ubig.New(upkeepID),
WorkID: record.workID,
CompletionState: uint8(record.state),
IneligibilityReason: reason,
InsertedAt: record.addedAt,
})
return nil
}
// fetchPerformed fetches all performed logs from the scanner to populate the cache.
func (u *upkeepStateStore) fetchPerformed(ctx context.Context, workIDs ...string) error {
performed, err := u.scanner.ScanWorkIDs(ctx, workIDs...)
if err != nil {
return err
}
if len(performed) > 0 {
u.lggr.Debugw("Fetched performed logs", "performed", len(performed))
}
u.mu.Lock()
defer u.mu.Unlock()
for _, workID := range performed {
if _, ok := u.cache[workID]; !ok {
s := &upkeepStateRecord{
workID: workID,
state: ocr2keepers.Performed,
addedAt: time.Now(),
}
u.cache[workID] = s
}
}
return nil
}
// fetchFromDB fetches all upkeeps indicated as ineligible from the db to
// populate the cache.
func (u *upkeepStateStore) fetchFromDB(ctx context.Context, workIDs ...string) error {
states, err := u.orm.SelectStatesByWorkIDs(ctx, workIDs)
if err != nil {
return err
}
u.mu.Lock()
defer u.mu.Unlock()
for _, state := range states {
if _, ok := u.cache[state.WorkID]; !ok {
u.cache[state.WorkID] = &upkeepStateRecord{
workID: state.WorkID,
state: ocr2keepers.UpkeepState(state.CompletionState),
addedAt: state.InsertedAt,
}
}
}
return nil
}
// selectFromCache returns all saved state values for the provided ids,
// returning stateNotFound for any ids that are not found.
// the second return value is true if all ids were found in the cache.
func (u *upkeepStateStore) selectFromCache(workIDs ...string) ([]ocr2keepers.UpkeepState, []string) {
u.mu.RLock()
defer u.mu.RUnlock()
var missing []string
states := make([]ocr2keepers.UpkeepState, len(workIDs))
for i, workID := range workIDs {
if state, ok := u.cache[workID]; ok {
states[i] = state.state
} else {
missing = append(missing, workID)
}
}
return states, missing
}
// cleanup removes any records that are older than the TTL from both cache and DB.
func (u *upkeepStateStore) cleanup(ctx context.Context) error {
u.cleanCache()
return u.cleanDB(ctx)
}
// cleanDB cleans up records in the DB that are older than the TTL.
func (u *upkeepStateStore) cleanDB(ctx context.Context) error {
tm := time.Now().Add(-1 * u.retention)
ctx, cancel := context.WithTimeout(sqlutil.WithoutDefaultTimeout(ctx), time.Minute)
defer cancel()
return u.orm.DeleteExpired(ctx, tm)
}
// cleanupCache removes any records from the cache that are older than the TTL.
func (u *upkeepStateStore) cleanCache() {
u.mu.Lock()
defer u.mu.Unlock()
for id, state := range u.cache {
if time.Since(state.addedAt) > u.retention {
delete(u.cache, id)
}
}
}