forked from simon-whitehead/relayr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longpoll-transport.go
112 lines (95 loc) · 2.18 KB
/
longpoll-transport.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
package relayr
import (
"bytes"
"encoding/json"
"io"
"net/http"
"sync"
"time"
)
type longPollConnection struct {
e *Exchange
result chan []byte
timeoutChan chan struct{}
t *time.Timer
ConnectionID string
}
type longPollTransport struct {
e *Exchange
connections map[string]longPollConnection
clock *sync.RWMutex
}
func (t *longPollTransport) clientInConnections(cid string) bool {
_, exists := t.connections[cid]
return exists
}
func (t *longPollTransport) addConnection(cid string) longPollConnection {
lp := longPollConnection{
e: t.e,
result: make(chan []byte, 100),
timeoutChan: make(chan struct{}, 10),
ConnectionID: cid,
}
t.connections[cid] = lp
return lp
}
func (t *longPollTransport) withClient(cid string, fn func(c longPollConnection)) {
if t.clientInConnections(cid) {
fn(t.connections[cid])
}
}
func newLongPollTransport(e *Exchange) *longPollTransport {
lp := &longPollTransport{
e: e,
connections: make(map[string]longPollConnection),
clock: &sync.RWMutex{},
}
return lp
}
func (t *longPollTransport) CallClientFunction(relay *Relay, fn string, args ...interface{}) {
buff := &bytes.Buffer{}
encoder := json.NewEncoder(buff)
encoder.Encode(struct {
R string
M string
A []interface{}
}{
relay.Name,
fn,
args,
})
go t.withClient(relay.ConnectionID, func(c longPollConnection) {
// force a timeout if we block on sending too long..
go func() {
<-time.After(time.Second * 30)
c.timeoutChan <- struct{}{}
}()
c.result <- buff.Bytes()
})
}
func (t *longPollTransport) removeConnection(cid string) {
delete(t.connections, cid)
}
func (t *longPollTransport) wait(w http.ResponseWriter, cid string) {
var conn longPollConnection
if !t.clientInConnections(cid) {
conn = t.addConnection(cid)
} else {
conn = t.connections[cid]
}
select {
case m := <-conn.result:
io.Copy(w, bytes.NewBuffer(m))
case <-conn.timeoutChan:
buff := &bytes.Buffer{}
encoder := json.NewEncoder(buff)
encoder.Encode(struct {
Z string
}{
"RECONNECT",
})
io.WriteString(w, buff.String())
t.removeConnection(cid)
t.e.removeFromAllGroups(cid)
}
}