-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
114 lines (93 loc) · 1.97 KB
/
cache.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
package requests_cache
import (
"context"
"fmt"
"net/http"
"sync"
"sync/atomic"
"time"
)
const (
statusInProgress uint32 = 1
statusDone uint32 = 0
)
var (
maxCacheSize = 1000
cacheTTL = 5 * time.Second
)
var once sync.Once
var rc *requestCache
type cache struct {
tStart time.Time
ctx context.Context
progressStatus *uint32
count *uint32
waited *uint32
data *http.Response
err error
}
func (c *cache) inProgress() bool {
return statusInProgress == atomic.LoadUint32(c.progressStatus)
}
type requestCache struct {
m sync.RWMutex
cache map[string]*cache
}
func (r *requestCache) scheduling() {
ticker := time.NewTicker(cacheTTL)
for range ticker.C {
newCache := make(map[string]*cache, maxCacheSize)
r.m.Lock()
for key, val := range r.cache {
if val.tStart.After(time.Now().Add(cacheTTL)) {
newCache[key] = val
}
}
r.m.Unlock()
r.m.Lock()
r.cache = newCache
r.m.Unlock()
}
}
func (r *requestCache) do(req *http.Request, client http.Client) (*http.Response, error) {
var val *cache
var ok bool
r.m.RLock()
val, ok = r.cache[req.URL.String()]
r.m.RUnlock()
if ok && !val.inProgress() {
return val.data, val.err
}
if !ok {
ctx, cancel := context.WithCancel(context.Background())
progressStatus := statusInProgress
var count uint32 = 1
var waited uint32 = 1
r.m.Lock()
r.cache[req.URL.String()] = &cache{
ctx: ctx,
progressStatus: &progressStatus,
count: &count,
waited: &waited,
}
r.m.Unlock()
response, err := client.Do(req)
newProgressStatus := statusDone
r.m.Lock()
r.cache[req.URL.String()] = &cache{
tStart: time.Now(),
progressStatus: &newProgressStatus,
data: response,
err: err,
}
r.m.Unlock()
cancel()
return response, err
}
<-val.ctx.Done()
val, ok = r.cache[req.URL.String()]
if ok {
return val.data, val.err
}
return nil, fmt.Errorf("fatal logical error")
}