File tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed
Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ package storage
2+
3+ import (
4+ "container/list"
5+ "net/http"
6+ "sync"
7+ )
8+
9+ type Debouncer struct {
10+ mtx sync.RWMutex
11+ requests * list.List
12+ cache map [string ]* list.Element
13+ capacityMB float64
14+ sizeMB float64
15+ }
16+
17+ type RequestNode struct {
18+ value * http.Request
19+ }
20+
21+ func NewDebouncer (maxSizeMB float64 ) * Debouncer {
22+ if maxSizeMB <= 0 {
23+ maxSizeMB = 50.0
24+ }
25+
26+ return & Debouncer {
27+ capacityMB : maxSizeMB ,
28+ sizeMB : 0.0 ,
29+ requests : list .New (),
30+ cache : make (map [string ]* list.Element ),
31+ }
32+ }
33+
34+ func (debouncer * Debouncer ) Store (key string , value * http.Request ) {
35+ debouncer .mtx .Lock ()
36+ defer debouncer .mtx .Unlock ()
37+
38+ bodySizeMB := debouncer .getSize (* value )
39+
40+ if bodySizeMB < 0 || (bodySizeMB + debouncer .sizeMB > debouncer .capacityMB ) {
41+ return
42+ }
43+
44+ if _ , found := debouncer .cache [key ]; ! found {
45+ element := debouncer .requests .PushFront (& RequestNode {value : value })
46+ debouncer .cache [key ] = element
47+ }
48+ }
49+
50+ func (debouncer * Debouncer ) GetNext () * http.Request {
51+ debouncer .mtx .RLock ()
52+ defer debouncer .mtx .RUnlock ()
53+
54+ return debouncer .requests .Back ().Value .(* RequestNode ).value
55+ }
56+
57+ func (debouncer * Debouncer ) Erase (key string ) bool {
58+ debouncer .mtx .RLock ()
59+ defer debouncer .mtx .RUnlock ()
60+
61+ if val , found := debouncer .cache [key ]; found {
62+ delete (debouncer .cache , key )
63+ debouncer .requests .Remove (val )
64+
65+ return true
66+ }
67+
68+ return false
69+ }
70+
71+ func (debouncer * Debouncer ) getSize (value http.Request ) float64 {
72+ sizeBytes := value .ContentLength
73+
74+ if sizeBytes < 0 {
75+ return - 1.0
76+ }
77+
78+ sizeMB := float64 (sizeBytes ) / (1024 * 1024 )
79+
80+ return sizeMB
81+ }
You can’t perform that action at this time.
0 commit comments