-
Notifications
You must be signed in to change notification settings - Fork 53
/
stream.go
341 lines (284 loc) · 9.62 KB
/
stream.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
// Package stream provide a generic stream function.
package stream
import (
"context"
"sync"
"time"
"github.com/omni-network/omni/lib/errors"
"github.com/omni-network/omni/lib/log"
"go.opentelemetry.io/otel/trace"
)
type Callback[E any] func(ctx context.Context, elem E) error
type Deps[E any] struct {
// Dependency functions
// FetchBatch fetches the next batch of elements from the provided height (inclusive).
// The elements must be sequential, since the internal height cursors is incremented for each element returned.
FetchBatch func(ctx context.Context, chainID uint64, height uint64) ([]E, error)
// Backoff returns a backoff function. See expbackoff package for the implementation.
Backoff func(ctx context.Context) func()
// Verify is a sanity check function, it ensures each element is valid.
Verify func(ctx context.Context, elem E, height uint64) error
// Height returns the height of an element.
Height func(elem E) uint64
// Config
FetchWorkers uint64
ElemLabel string
RetryCallback bool
// Metrics
IncFetchErr func()
IncCallbackErr func()
SetStreamHeight func(uint64)
SetCallbackLatency func(time.Duration)
StartTrace func(ctx context.Context, height uint64, spanName string) (context.Context, trace.Span)
}
// Stream streams elements from the provided height (inclusive) of a specific chain.
// It fetches the batches of elements from the current height, and
// calls the callback function for each element in strictly-sequential order.
//
// It supports concurrent fetching of single-element-batches only.
// It retries forever on fetch errors.
// It can either retry or return callback errors.
// It returns (nil) when the context is canceled.
//
func Stream[E any](ctx context.Context, deps Deps[E], srcChainID uint64, startHeight uint64, callback Callback[E]) error {
if deps.FetchWorkers == 0 {
return errors.New("invalid zero fetch worker count")
}
// Define a robust fetch function that fetches a batch of elements from a height (inclusive).
// It only returns an empty list if the context is canceled.
// It retries forever on error or if no elements found.
fetchFunc := func(ctx context.Context, height uint64) []E {
backoff := deps.Backoff(ctx) // Note that backoff returns immediately on ctx cancel.
for {
if ctx.Err() != nil {
return nil
}
fetchCtx, span := deps.StartTrace(ctx, height, "fetch")
elems, err := deps.FetchBatch(fetchCtx, srcChainID, height)
span.End()
if ctx.Err() != nil {
return nil
} else if err != nil {
log.Warn(ctx, "Failed fetching "+deps.ElemLabel+" (will retry)", err, "height", height)
deps.IncFetchErr()
backoff()
continue
} else if len(elems) == 0 {
// We reached the head of the chain, wait for new blocks.
backoff()
continue
}
heightsOK := true
for i, elem := range elems {
if h := deps.Height(elem); h != height+uint64(i) {
log.Error(ctx, "Invalid "+deps.ElemLabel+" height [BUG]", nil,
"expect", height,
"actual", h,
)
heightsOK = false
}
}
if !heightsOK { // Can't return invalid elements, just retry fetching for now.
backoff()
continue
}
return elems
}
}
// Define a robust callback function that retries on error.
callbackFunc := func(ctx context.Context, elem E) error {
height := deps.Height(elem)
ctx, span := deps.StartTrace(ctx, height, "callback")
defer span.End()
ctx = log.WithCtx(ctx, "height", height)
backoff := deps.Backoff(ctx)
if err := deps.Verify(ctx, elem, height); err != nil {
return errors.Wrap(err, "verify")
}
// Retry callback on error
for {
if ctx.Err() != nil {
return nil // Don't backoff or log on ctx cancel, just return nil.
}
t0 := time.Now()
err := callback(ctx, elem)
deps.SetCallbackLatency(time.Since(t0))
if ctx.Err() != nil {
return nil // Don't backoff or log on ctx cancel, just return nil.
} else if err != nil && !deps.RetryCallback {
deps.IncCallbackErr()
return errors.Wrap(err, "callback")
} else if err != nil {
log.Warn(ctx, "Failed processing "+deps.ElemLabel+" (will retry)", err)
deps.IncCallbackErr()
backoff()
continue
}
deps.SetStreamHeight(height)
return nil
}
}
// Sorting buffer connects the concurrent fetch workers to the callback
sorter := newSortingBuffer(startHeight, deps, callbackFunc)
// Start fetching workers
startFetchWorkers(ctx, deps, fetchFunc, sorter, startHeight)
// Sort fetch results and call callback
return sorter.Process(ctx)
}
// startFetchWorkers starts <deps.FetchWorkers> worker goroutines
// that fetch all batches concurrently from the provided <startHeight>.
//
// Concurrent fetching is only supported for single-element-batches, since
// each worker fetches: startHeight + Ith-iteration + Nth-worker.
//
// For multi-element-batches, only a single worker is supported.
func startFetchWorkers[E any](
ctx context.Context,
deps Deps[E],
work func(ctx context.Context, height uint64) []E,
sorter *sortingBuffer[E],
startHeight uint64,
) {
for i := uint64(0); i < deps.FetchWorkers; i++ {
go func(workerID int, height uint64) {
for {
// Work function MUST be robust, always returning a non-empty strictly-sequential batch
// or nil if the context was canceled.
batch := work(ctx, height)
if ctx.Err() != nil {
return
} else if len(batch) == 0 {
log.Error(ctx, "Work function returned an empty batch [BUG]", nil)
return
} else if len(batch) > 1 && deps.FetchWorkers > 1 {
log.Error(ctx, "Concurrent fetching only supported for single element batches [BUG]", nil)
return
}
var last uint64
for i, e := range batch {
last = deps.Height(e)
if last != height+uint64(i) {
log.Error(ctx, "Invalid batch [BUG]", nil)
return
}
}
sorter.Add(ctx, workerID, batch)
// Calculate next height to fetch
height = last + deps.FetchWorkers
}
}(int(i), startHeight+i) // Initialize a height to fetch per worker
}
}
// sortingBuffer buffers unordered batches of elements (one batch per worker),
// providing elements to the callback in strictly-sequential sorted order.
type sortingBuffer[E any] struct {
deps Deps[E]
callback func(ctx context.Context, elem E) error
startHeight uint64
mu sync.Mutex
buffer map[uint64]workerElem[E] // Worker elements by height
counts map[int]int // Count of elements per worker
signals map[int]chan struct{} // Processes <> Worker comms
}
const processorID = -1
func newSortingBuffer[E any](
startHeight uint64,
deps Deps[E],
callback func(ctx context.Context, elem E) error,
) *sortingBuffer[E] {
signals := make(map[int]chan struct{})
signals[processorID] = make(chan struct{}, 1)
for i := 0; i < int(deps.FetchWorkers); i++ {
signals[i] = make(chan struct{}, 1)
}
return &sortingBuffer[E]{
startHeight: startHeight,
deps: deps,
callback: callback,
buffer: make(map[uint64]workerElem[E]),
counts: make(map[int]int),
signals: signals,
}
}
// signal signals the ID to wakeup.
func (m *sortingBuffer[E]) signal(signalID int) {
select {
case m.signals[signalID] <- struct{}{}:
default:
}
}
// retryLock repeatedly obtains the lock and calls the callback while it returns false.
// It returns once the callback returns true or an error.
func (m *sortingBuffer[E]) retryLock(ctx context.Context, signalID int, fn func(ctx context.Context) (bool, error)) error {
timer := time.NewTicker(time.Nanosecond) // Initial timer is instant
defer timer.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-m.signals[signalID]:
case <-timer.C:
}
m.mu.Lock()
done, err := fn(ctx)
m.mu.Unlock()
if err != nil {
return err
} else if done {
return nil
}
// Not done, so retry again, much later
timer.Reset(time.Second)
}
}
func (m *sortingBuffer[E]) Add(ctx context.Context, workerID int, batch []E) {
_ = m.retryLock(ctx, workerID, func(_ context.Context) (bool, error) {
// Wait for any previous batch this worker added to be processed before adding this batch.
// This results in backpressure to workers, basically only buffering a single batch per worker.
if m.counts[workerID] > 0 {
return false, nil // Previous batch still in buffer, retry a bit later
}
// Add the batch
for _, e := range batch {
height := m.deps.Height(e)
// Invariant check (error handling in workerFunc)
if _, ok := m.buffer[height]; ok {
return false, errors.New("duplicate element [BUG]")
}
m.buffer[height] = workerElem[E]{WorkerID: workerID, E: e}
}
m.counts[workerID] = len(batch)
m.signal(processorID) // Signal the processor
return true, nil // Don't retry lock again, we are done.
})
}
// Process calls the callback function in strictly-sequential order from <height> (inclusive)
// as elements become available in the buffer.
func (m *sortingBuffer[E]) Process(ctx context.Context) error {
next := m.startHeight
return m.retryLock(ctx, processorID, func(ctx context.Context) (bool, error) {
elem, ok := m.buffer[next]
if !ok {
return false, nil // Next height not in buffer, retry a bit later
}
delete(m.buffer, next)
err := m.callback(ctx, elem.E)
if err != nil {
return false, err // Don't retry again
}
m.counts[elem.WorkerID]--
if m.counts[elem.WorkerID] == 0 {
m.signal(elem.WorkerID) // Signal the worker that it can add another batch
}
next++
if _, ok := m.buffer[next]; ok {
m.signal(processorID) // Signal ourselves if next elements already in buffer.
}
return false, nil // Retry again with next height
})
}
// workerElem represents an element processed by a worker.
type workerElem[E any] struct {
WorkerID int
E E
}