-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
main.go
256 lines (213 loc) · 6.2 KB
/
main.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
252
253
254
255
256
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"runtime"
"sync"
"syscall"
"time"
_ "net/http/pprof"
"github.com/centrifugal/centrifuge"
"github.com/centrifugal/protocol"
"nhooyr.io/websocket"
)
func handleLog(e centrifuge.LogEntry) {
log.Printf("%s: %v", e.Message, e.Fields)
}
func waitExitSignal(n *centrifuge.Node) {
sigCh := make(chan os.Signal, 1)
done := make(chan bool, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigCh
_ = n.Shutdown(context.Background())
done <- true
}()
<-done
}
type customWebsocketHandler struct {
node *centrifuge.Node
}
func newWebsocketHandler(node *centrifuge.Node) http.Handler {
return &customWebsocketHandler{node}
}
const websocketTransportName = "websocket"
type customWebsocketTransport struct {
mu sync.RWMutex
closed bool
closeCh chan struct{}
conn *websocket.Conn
protoType centrifuge.ProtocolType
}
func newWebsocketTransport(conn *websocket.Conn, protoType centrifuge.ProtocolType) *customWebsocketTransport {
return &customWebsocketTransport{
conn: conn,
protoType: protoType,
closeCh: make(chan struct{}),
}
}
// Name ...
func (t *customWebsocketTransport) Name() string {
return websocketTransportName
}
// Protocol ...
func (t *customWebsocketTransport) Protocol() centrifuge.ProtocolType {
return t.protoType
}
func (t *customWebsocketTransport) ProtocolVersion() centrifuge.ProtocolVersion {
return centrifuge.ProtocolVersion2
}
// Unidirectional returns whether transport is unidirectional.
func (t *customWebsocketTransport) Unidirectional() bool {
return false
}
// Emulation ...
func (t *customWebsocketTransport) Emulation() bool {
return false
}
// DisabledPushFlags ...
func (t *customWebsocketTransport) DisabledPushFlags() uint64 {
return centrifuge.PushFlagDisconnect
}
// PingPongConfig ...
func (t *customWebsocketTransport) PingPongConfig() centrifuge.PingPongConfig {
return centrifuge.PingPongConfig{
PingInterval: 25 * time.Second,
PongTimeout: 8 * time.Second,
}
}
// Write ...
func (t *customWebsocketTransport) Write(message []byte) error {
select {
case <-t.closeCh:
return nil
default:
var messageType = websocket.MessageText
protoType := protocol.TypeJSON
if t.Protocol() == centrifuge.ProtocolTypeProtobuf {
messageType = websocket.MessageBinary
protoType = protocol.TypeProtobuf
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
encoder := protocol.GetDataEncoder(protoType)
defer protocol.PutDataEncoder(protoType, encoder)
_ = encoder.Encode(message)
return t.conn.Write(ctx, messageType, encoder.Finish())
}
}
// WriteMany ...
func (t *customWebsocketTransport) WriteMany(messages ...[]byte) error {
select {
case <-t.closeCh:
return nil
default:
var messageType = websocket.MessageText
protoType := protocol.TypeJSON
if t.Protocol() == centrifuge.ProtocolTypeProtobuf {
messageType = websocket.MessageBinary
protoType = protocol.TypeProtobuf
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
encoder := protocol.GetDataEncoder(protoType)
defer protocol.PutDataEncoder(protoType, encoder)
for i := range messages {
_ = encoder.Encode(messages[i])
}
return t.conn.Write(ctx, messageType, encoder.Finish())
}
}
// Close ...
func (t *customWebsocketTransport) Close(disconnect centrifuge.Disconnect) error {
t.mu.Lock()
if t.closed {
t.mu.Unlock()
return nil
}
t.closed = true
close(t.closeCh)
t.mu.Unlock()
if disconnect != centrifuge.DisconnectConnectionClosed {
return t.conn.Close(websocket.StatusCode(disconnect.Code), disconnect.Reason)
}
return t.conn.Close(websocket.StatusNormalClosure, "")
}
func (s *customWebsocketHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(rw, r, &websocket.AcceptOptions{
Subprotocols: []string{"centrifuge-protobuf"},
})
if err != nil {
s.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "websocket upgrade error", map[string]any{"error": err.Error()}))
return
}
var protoType = centrifuge.ProtocolTypeJSON
if conn.Subprotocol() == "centrifuge-protobuf" {
protoType = centrifuge.ProtocolTypeProtobuf
}
transport := newWebsocketTransport(conn, protoType)
select {
case <-s.node.NotifyShutdown():
_ = transport.Close(centrifuge.DisconnectShutdown)
return
default:
}
c, closeFn, err := centrifuge.NewClient(r.Context(), s.node, transport)
if err != nil {
s.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error creating client", map[string]any{"transport": websocketTransportName}))
return
}
defer func() { _ = closeFn() }()
if s.node.LogEnabled(centrifuge.LogLevelDebug) {
s.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "client connection established", map[string]any{"client": c.ID(), "transport": websocketTransportName}))
defer func(started time.Time) {
s.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "client connection completed", map[string]any{"client": c.ID(), "transport": websocketTransportName, "duration": time.Since(started)}))
}(time.Now())
}
for {
_, r, err := conn.Reader(context.Background())
if err != nil {
return
}
ok := centrifuge.HandleReadFrame(c, r)
if !ok {
return
}
}
}
func main() {
log.Printf("NumCPU: %d", runtime.NumCPU())
node, _ := centrifuge.New(centrifuge.Config{
LogLevel: centrifuge.LogLevelError,
LogHandler: handleLog,
})
node.OnConnecting(func(ctx context.Context, e centrifuge.ConnectEvent) (centrifuge.ConnectReply, error) {
return centrifuge.ConnectReply{
Credentials: ¢rifuge.Credentials{
UserID: "bench",
},
}, nil
})
node.OnConnect(func(client *centrifuge.Client) {
client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) {
cb(centrifuge.SubscribeReply{}, nil)
})
client.OnPublish(func(e centrifuge.PublishEvent, cb centrifuge.PublishCallback) {
cb(centrifuge.PublishReply{}, nil)
})
})
if err := node.Run(); err != nil {
log.Fatal(err)
}
http.Handle("/connection/websocket", newWebsocketHandler(node))
go func() {
if err := http.ListenAndServe(":8000", nil); err != nil {
log.Fatal(err)
}
}()
waitExitSignal(node)
log.Println("bye!")
}