-
Notifications
You must be signed in to change notification settings - Fork 568
/
work_deduper.go
51 lines (43 loc) · 1.13 KB
/
work_deduper.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
package miscutil
import (
"context"
"sync"
"github.com/pachyderm/pachyderm/v2/src/internal/errors"
)
type WorkDeduper[K comparable] struct {
futures sync.Map
}
// Concurrent calls to Do will block until cb has been completed by one of them, then the others will run, possibly concurrently.
// The motivating use case is to eliminate network round trips when populating a cache.
// Callers should check and populate the cache inside cb.
func (wd *WorkDeduper[K]) Do(ctx context.Context, k K, cb func() error) error {
fut, created := wd.getOrCreateFuture(k)
if created {
defer wd.removeFuture(k)
fut.err = cb()
close(fut.done)
}
return fut.await(ctx)
}
func (wd *WorkDeduper[K]) getOrCreateFuture(key K) (*future, bool) {
fut := &future{
done: make(chan struct{}),
}
x, loaded := wd.futures.LoadOrStore(key, fut)
return x.(*future), !loaded
}
func (wd *WorkDeduper[K]) removeFuture(k K) {
wd.futures.Delete(k)
}
type future struct {
done chan struct{}
err error
}
func (f future) await(ctx context.Context) error {
select {
case <-f.done:
return f.err
case <-ctx.Done():
return errors.EnsureStack(context.Cause(ctx))
}
}