-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingle_flight.go
More file actions
42 lines (32 loc) · 1014 Bytes
/
single_flight.go
File metadata and controls
42 lines (32 loc) · 1014 Bytes
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
package generics
import (
"context"
"golang.org/x/sync/singleflight"
)
// NewTypedSingleflight is a wrapper that provides a typed single-flight function, ensuring only
// one request for the same key occurs concurrently, and that the result is shared.
func NewTypedSingleflight[K SingleFlightKey, V any](fn func(ctx context.Context, key K) (V, error)) func(ctx context.Context, key K) (V, error) {
sf := &TypedGroup[K, V]{
fn: fn,
}
return sf.Execute
}
// SingleFlightKey is an interface that implements the requirements of a singleflight group, namely
// to covner to a key
type SingleFlightKey interface {
String() string
}
type TypedGroup[K SingleFlightKey, V any] struct {
g singleflight.Group
fn func(ctx context.Context, key K) (V, error)
}
func (tg *TypedGroup[K, V]) Execute(ctx context.Context, key K) (V, error) {
var blank V
v, err, _ := tg.g.Do(key.String(), func() (interface{}, error) {
return tg.fn(ctx, key)
})
if err != nil {
return blank, err
}
return v.(V), nil
}