-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathproxy.go
251 lines (222 loc) · 5.97 KB
/
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package natsproxy
import (
"bytes"
"fmt"
"log"
"net/http"
"regexp"
"time"
"github.com/gogo/protobuf/proto"
"github.com/gorilla/websocket"
"github.com/nats-io/nats"
)
var (
// ErrNatsClientNotConnected is returned
// if the natsclient inserted
// in NewNatsProxy is not connected.
ErrNatsClientNotConnected = fmt.Errorf("Client not connected")
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// HookFunc is the function that is
// used to modify response just before its
// transformed to HTTP response
type HookFunc func(*Response)
type webSocketMapper struct {
toNats map[*websocket.Conn]string
fromNats map[string]*websocket.Conn
}
// NatsProxy serves as a proxy
// between gnats and http. It automatically
// translates the HTTP requests to nats
// messages. The url and method of the HTTP request
// serves as the name of the nats channel, where
// the message is sent.
type NatsProxy struct {
conn *nats.Conn
hooks map[string]hookGroup
wsMapper *webSocketMapper
requestPool RequestPool
responsePool ResponsePool
}
type hookGroup struct {
regexp *regexp.Regexp
hooks []HookFunc
}
// NewNatsProxy creates an
// initialized NatsProxy
func NewNatsProxy(conn *nats.Conn) (*NatsProxy, error) {
if err := testConnection(conn); err != nil {
return nil, err
}
return &NatsProxy{
conn,
make(map[string]hookGroup, 0),
&webSocketMapper{
make(map[*websocket.Conn]string, 0),
make(map[string]*websocket.Conn, 0),
},
NewRequestPool(),
NewResponsePool(),
}, nil
}
func (np *NatsProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Transform the HTTP request to
// NATS proxy request.
request := np.requestPool.GetRequest()
defer np.requestPool.Put(request)
err := request.FromHTTP(req)
if err != nil {
http.Error(rw, "Cannot process request", http.StatusInternalServerError)
return
}
// Serialize the request.
reqBytes, err := proto.Marshal(request)
if err != nil {
http.Error(rw, "Cannot process request", http.StatusInternalServerError)
return
}
// Post request to message queue
msg, respErr := np.conn.Request(
URLToNats(req.Method, req.URL.Path),
reqBytes,
10*time.Second)
if respErr != nil {
http.Error(rw, "No response", http.StatusInternalServerError)
return
}
response := np.responsePool.GetResponse()
err = response.ReadFrom(msg.Data)
defer np.responsePool.Put(response)
if err != nil {
log.Println("nats-proxy:" + err.Error())
http.Error(rw, "Cannot deserialize response", http.StatusInternalServerError)
return
}
// Apply hook if regex match
for _, hG := range np.hooks {
if hG.regexp.MatchString(req.URL.Path) {
for _, hook := range hG.hooks {
hook(response)
}
}
}
// If response contains
// the permission to do ws upgrade, the
// proxy side upgrades the connection and
// provides the Web Socket proxiing on
// provided wsID toppic (WS_IN+wsID as receiving
// and WS_OUT+wsID as outcoming)
if request.IsWebSocket() && response.DoUpgrade {
header := http.Header{}
copyHeader(response.Header, header)
if conn, err := upgrader.Upgrade(rw, req, header); err == nil {
np.activateWSProxySubject(conn, request.WebSocketID)
} else {
log.Println("natsproxy error: " + err.Error())
}
} else {
writeResponse(rw, response)
}
}
// AddHook add the hook to modify,
// process response just before
// its transformed to HTTP form.
func (np *NatsProxy) AddHook(urlRegex string, hook HookFunc) error {
hG, ok := np.hooks[urlRegex]
if !ok {
regexp, err := regexp.Compile(urlRegex)
if err != nil {
return err
}
hooks := make([]HookFunc, 1)
hooks[0] = hook
np.hooks[urlRegex] = hookGroup{
regexp,
hooks,
}
} else {
hG.hooks = append(hG.hooks, hook)
}
return nil
}
func (np *NatsProxy) activateWSProxySubject(conn *websocket.Conn, wsID string) {
np.addToWSMapper(conn, wsID)
np.conn.Subscribe("WS_OUT"+wsID, func(m *nats.Msg) {
err := conn.WriteMessage(websocket.TextMessage, m.Data)
if err != nil {
log.Println("Error writing a message", err)
}
})
go func() {
for {
if _, p, err := conn.ReadMessage(); err == nil {
np.conn.Publish("WS_IN"+wsID, p)
} else {
np.removeFromWSMapper(conn, wsID)
conn.Close()
// If websocket is closed normally RFC6455
// code 1000, then no error logged
if !websocket.IsCloseError(err, websocket.CloseNormalClosure) {
logWebsocketError(wsID, err)
}
break
}
}
}()
}
func (np *NatsProxy) addToWSMapper(conn *websocket.Conn, wsID string) {
np.wsMapper.fromNats[wsID] = conn
np.wsMapper.toNats[conn] = wsID
}
func (np *NatsProxy) removeFromWSMapper(conn *websocket.Conn, wsID string) {
delete(np.wsMapper.fromNats, wsID)
delete(np.wsMapper.toNats, conn)
}
func (np *NatsProxy) resetWSMapper() {
np.wsMapper.fromNats = make(map[string]*websocket.Conn, 0)
np.wsMapper.toNats = make(map[*websocket.Conn]string, 0)
}
func (np *NatsProxy) closeAllWebsockets() error {
var outerError error
closed := make([]string, 0)
for key, val := range np.wsMapper.fromNats {
if err := val.Close(); err != nil {
outerError = fmt.Errorf("nats-proxy: closing websocket ID: %s caused error: %s", key, err.Error())
}
closed = append(closed, key)
}
if outerError == nil {
np.resetWSMapper()
} else {
// Remove just closed
for _, val := range closed {
np.removeFromWSMapper(np.wsMapper.fromNats[val], val)
}
}
return outerError
}
func logWebsocketError(wsID string, err error) {
log.Printf("nats-proxy: underlying websocker ID: %s error: %s", wsID, err.Error())
}
func writeResponse(rw http.ResponseWriter, response *Response) {
// Copy headers
// from NATS response.
copyHeader(response.Header, rw.Header())
// Write the response code
rw.WriteHeader(int(response.StatusCode))
// Write the bytes of response
// to a response writer.
// TODO benchmark
bytes.NewBuffer(response.Body).WriteTo(rw)
}
func copyHeader(src map[string]*Values, dst http.Header) {
for key, it := range src {
for _, val := range it.Arr {
dst.Add(key, val)
}
}
}