forked from infiotinc/gqlgenc
/
response_proxy.go
99 lines (80 loc) · 1.42 KB
/
response_proxy.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
package transport
import (
"sync"
"sync/atomic"
)
type proxyTarget SendResponse
type ProxyResponse struct {
proxyTarget
binds []Response
m sync.RWMutex
inFlight int32
}
func (p *ProxyResponse) Bound(res Response) bool {
p.m.RLock()
defer p.m.RUnlock()
for _, b := range p.binds {
if b == res {
return true
}
}
return false
}
func (p *ProxyResponse) Bind(res Response, onOpres func(response OperationResponse, send func())) {
atomic.AddInt32(&p.inFlight, 1)
if onOpres == nil {
onOpres = func(_ OperationResponse, send func()) {
send()
}
}
p.m.Lock()
p.binds = append(p.binds, res)
p.m.Unlock()
go func() {
go func() {
select {
case <-res.Done():
case <-p.Done():
res.Close()
}
}()
for res.Next() {
opres := res.Get()
onOpres(opres, func() {
if p.Bound(res) {
p.Send(opres)
}
})
if !p.Bound(res) {
break
}
}
if p.Bound(res) {
if err := res.Err(); err != nil {
p.CloseWithError(err)
}
}
atomic.AddInt32(&p.inFlight, -1)
p.Unbind(res)
}()
}
func (p *ProxyResponse) Unbind(res Response) {
p.m.Lock()
binds := make([]Response, 0)
for _, b := range p.binds {
if b == res {
continue
}
binds = append(binds, b)
}
p.binds = binds
p.m.Unlock()
if atomic.LoadInt32(&p.inFlight) == 0 {
p.Close()
}
}
func NewProxyResponse() *ProxyResponse {
return &ProxyResponse{
proxyTarget: NewChanResponse(nil),
}
}