forked from skynetservices/skydns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleinflight.go
94 lines (78 loc) · 1.54 KB
/
singleinflight.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
// Copyright (c) 2013 Erik St. Martin, Brian Ketelsen. All rights reserved.
// Use of this source code is governed by The MIT License (MIT) that can be
// found in the LICENSE file.
package main
import (
"sync"
"github.com/coreos/go-etcd/etcd"
"github.com/miekg/dns"
)
var (
inflight = new(single)
etcdInflight = new(etcdSingle)
)
// Adapted from singleinflight.go from the original Go Code. Copyright 2013 The Go Authors.
type call struct {
wg sync.WaitGroup
val *dns.RRSIG
err error
dups int
}
type single struct {
sync.Mutex
m map[string]*call
}
func (g *single) Do(key string, fn func() (*dns.RRSIG, error)) (*dns.RRSIG, error, bool) {
g.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
c.dups++
g.Unlock()
c.wg.Wait()
return c.val, c.err, true
}
c := new(call)
c.wg.Add(1)
g.m[key] = c
g.Unlock()
c.val, c.err = fn()
c.wg.Done()
g.Lock()
delete(g.m, key)
g.Unlock()
return c.val, c.err, c.dups > 0
}
type etcdCall struct {
wg sync.WaitGroup
val *etcd.Response
err error
dups int
}
type etcdSingle struct {
sync.Mutex
m map[string]*etcdCall
}
func (g *etcdSingle) Do(key string, fn func() (*etcd.Response, error)) (*etcd.Response, error, bool) {
g.Lock()
if g.m == nil {
g.m = make(map[string]*etcdCall)
}
if c, ok := g.m[key]; ok {
c.dups++
g.Unlock()
c.wg.Wait()
return c.val, c.err, true
}
c := new(etcdCall)
c.wg.Add(1)
g.m[key] = c
g.Unlock()
c.val, c.err = fn()
c.wg.Done()
g.Lock()
delete(g.m, key)
g.Unlock()
return c.val, c.err, c.dups > 0
}