-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoperators.go
383 lines (350 loc) · 8.58 KB
/
operators.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package stream
import (
"context"
"time"
"golang.org/x/time/rate"
)
//
// Operators transform the observable stream.
//
// Map applies a function onto values of an observable and emits the resulting values.
//
// Map(Range(1,4), func(x int) int { return x * 2})
// => [2,4,6]
func Map[A, B any](src Observable[A], apply func(A) B) Observable[B] {
return FuncObservable[B](
func(ctx context.Context, next func(B), complete func(error)) {
src.Observe(
ctx,
func(a A) { next(apply(a)) },
complete)
})
}
// Filter only emits the values for which the provided predicate returns true.
//
// Filter(Range(1,4), func(x int) int { return x%2 == 0 })
// => [2]
func Filter[T any](src Observable[T], pred func(T) bool) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T), complete func(error)) {
src.Observe(
ctx,
func(x T) {
if pred(x) {
next(x)
}
},
complete)
})
}
// Reduce takes an initial state, and a function 'reduce' that is called on each element
// along with a state and returns an observable with a single item: the state produced
// by the last call to 'reduce'.
//
// Reduce(Range(1,4), 0, func(sum, item int) int { return sum + item })
// => [(0+1+2+3)] => [6]
func Reduce[Item, Result any](src Observable[Item], init Result, reduce func(Result, Item) Result) Observable[Result] {
result := init
return FuncObservable[Result](
func(ctx context.Context, next func(Result), complete func(error)) {
src.Observe(
ctx,
func(x Item) {
result = reduce(result, x)
},
func(err error) {
if err == nil {
next(result)
}
complete(err)
})
})
}
// Concat takes one or more observable of the same type and emits the items from each of
// them in order.
func Concat[T any](srcs ...Observable[T]) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T), complete func(error)) {
go func() {
for _, src := range srcs {
errs := make(chan error, 1)
src.Observe(
ctx,
next,
func(err error) {
if err != nil {
errs <- err
}
close(errs)
},
)
if err, ok := <-errs; ok {
complete(err)
return
}
}
complete(nil)
}()
})
}
// FlatMap applies a function that returns an observable of Bs to the source observable of As.
// The observable from the 'apply' function is flattened to produce a flat stream of Bs.
func FlatMap[A, B any](src Observable[A], apply func(A) Observable[B]) Observable[B] {
return FuncObservable[B](
func(ctx context.Context, next func(B), complete func(error)) {
ctx, cancel := context.WithCancel(ctx)
innerErrs := make(chan error, 1)
src.Observe(
ctx,
func(a A) {
done := make(chan struct{})
apply(a).Observe(
ctx,
next,
func(err error) {
if err != nil {
select {
case innerErrs <- err:
default:
}
cancel()
}
close(done)
},
)
<-done
},
func(err error) {
defer close(innerErrs)
select {
case innerErr := <-innerErrs:
complete(innerErr)
default:
complete(err)
}
},
)
})
}
// Distinct skips adjacent equal values.
//
// Distinct(FromSlice([]int{1,1,2,2,3})
// => [1,2,3]
func Distinct[T comparable](src Observable[T]) Observable[T] {
var prev T
first := true
return Filter(src, func(item T) bool {
if first {
first = false
prev = item
return true
}
eq := prev == item
prev = item
return !eq
})
}
// RetryFunc decides whether the processing should be retried given the error
type RetryFunc func(err error) bool
// Retry resubscribes to the observable if it completes with an error.
func Retry[T any](src Observable[T], shouldRetry RetryFunc) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T), complete func(error)) {
var observe func()
observe = func() {
src.Observe(
ctx,
next,
func(err error) {
if err != nil && shouldRetry(err) {
observe()
} else {
complete(err)
}
})
}
observe()
})
}
// AlwaysRetry always asks for a retry regardless of the error.
func AlwaysRetry(err error) bool {
return true
}
// BackoffRetry retries with an exponential backoff.
func BackoffRetry(shouldRetry RetryFunc, minBackoff, maxBackoff time.Duration) RetryFunc {
backoff := minBackoff
return func(err error) bool {
time.Sleep(backoff)
backoff *= 2
if backoff > maxBackoff {
backoff = maxBackoff
}
return shouldRetry(err)
}
}
// LimitRetries limits the number of retries with the given retry method.
// e.g. LimitRetries(BackoffRetry(time.Millisecond, time.Second), 5)
func LimitRetries(shouldRetry RetryFunc, numRetries int) RetryFunc {
return func(err error) bool {
if numRetries <= 0 {
return false
}
numRetries--
return shouldRetry(err)
}
}
// ToMulticast makes 'src' a multicast observable, e.g. each observer will observe
// the same sequence. Useful for fanning out items to multiple observers from a source
// that is consumed by the act of observing.
//
// mcast, connect := ToMulticast(FromChannel(values))
// a := ToSlice(mcast)
// b := ToSlice(mcast)
// connect(ctx) // start!
// => a == b
func ToMulticast[T any](src Observable[T], opts ...MulticastOpt) (mcast Observable[T], connect func(context.Context)) {
mcast, next, complete := Multicast[T](opts...)
connect = func(ctx context.Context) {
src.Observe(ctx, next, complete)
}
return mcast, connect
}
// Throttle limits the rate at which items are emitted.
func Throttle[T any](src Observable[T], ratePerSecond float64, burst int) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T), complete func(error)) {
limiter := rate.NewLimiter(rate.Limit(ratePerSecond), burst)
var limiterErr error
subCtx, cancel := context.WithCancel(ctx)
src.Observe(
subCtx,
func(item T) {
limiterErr = limiter.Wait(ctx)
if limiterErr != nil {
cancel()
return
}
next(item)
},
func(err error) {
if limiterErr != nil {
complete(limiterErr)
} else {
complete(err)
}
},
)
})
}
// Debounce emits an item only after the specified duration has lapsed since
// the previous item was emitted. Only the latest item is emitted.
//
// In: a b c d e |->
// Out: a d e |->
func Debounce[T any](src Observable[T], duration time.Duration) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T), complete func(error)) {
errs := make(chan error, 1)
items := ToChannel(ctx, src, WithErrorChan(errs))
go func() {
defer close(errs)
timer := time.NewTimer(duration)
defer timer.Stop()
timerElapsed := true // Do not delay the first item.
var latest *T
for {
select {
case err := <-errs:
complete(err)
return
case item, ok := <-items:
if !ok {
items = nil
latest = nil
continue
}
if timerElapsed {
next(item)
timerElapsed = false
latest = nil
timer.Reset(duration)
} else {
latest = &item
}
case <-timer.C:
if latest != nil {
next(*latest)
latest = nil
timer.Reset(duration)
} else {
timerElapsed = true
}
}
}
}()
})
}
// Buffer collects items into a buffer using the given buffering function and
// emits the buffer when 'waitTime' has elapsed. Buffer does not emit empty
// buffers.
//
// In: a b c |->
// Out: [a,b] [c] |->
func Buffer[Buf any, T any](
src Observable[T],
bufferSize int,
waitTime time.Duration,
bufferItem func(Buf, T) Buf) Observable[Buf] {
return FuncObservable[Buf](
func(ctx context.Context, next func(Buf), complete func(error)) {
items := make(chan T, bufferSize)
errs := make(chan error, 1)
src.Observe(
ctx,
func(item T) {
items <- item
},
func(err error) {
close(items)
errs <- err
close(errs)
})
go func() {
ticker := time.NewTicker(waitTime)
defer ticker.Stop()
var (
emptyBuf Buf
buf Buf
)
n := 0
loop:
for {
select {
case <-ticker.C:
if n > 0 {
next(buf)
buf = emptyBuf
n = 0
}
case item, ok := <-items:
if !ok {
break loop
}
buf = bufferItem(buf, item)
n++
if n >= bufferSize {
next(buf)
buf = emptyBuf
n = 0
}
}
}
if n > 0 {
next(buf)
}
complete(<-errs)
}()
})
}