-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
main.go
276 lines (240 loc) · 7.35 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package main
import (
"context"
"encoding/json"
"flag"
"io"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
_ "net/http/pprof"
"github.com/centrifugal/centrifuge"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
port = flag.Int("port", 8000, "Port to bind app to")
)
type clientMessage struct {
Timestamp int64 `json:"timestamp"`
Input string `json:"input"`
}
func handleLog(e centrifuge.LogEntry) {
log.Printf("%s: %v", e.Message, e.Fields)
}
func authMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
newCtx := centrifuge.SetCredentials(ctx, ¢rifuge.Credentials{
UserID: "42",
ExpireAt: time.Now().Unix() + 60,
Info: []byte(`{"name": "Alexander"}`),
})
r = r.WithContext(newCtx)
h.ServeHTTP(w, r)
})
}
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
}
var exampleChannels = []string{
"chat:index",
"tokenized",
}
// Check whether channel is allowed for subscribing. In real case permission
// check will probably be more complex than in this example.
func channelSubscribeAllowed(channel string) bool {
for _, ch := range exampleChannels {
if ch == channel {
return true
}
}
return false
}
func main() {
flag.Parse()
node, _ := centrifuge.New(centrifuge.Config{
LogLevel: centrifuge.LogLevelInfo,
LogHandler: handleLog,
})
redisShardConfigs := []centrifuge.RedisShardConfig{
{Address: "localhost:6379"},
}
var redisShards []*centrifuge.RedisShard
for _, redisConf := range redisShardConfigs {
redisShard, err := centrifuge.NewRedisShard(node, redisConf)
if err != nil {
log.Fatal(err)
}
redisShards = append(redisShards, redisShard)
}
broker, err := centrifuge.NewRedisBroker(node, centrifuge.RedisBrokerConfig{
// And configure a couple of shards to use.
Shards: redisShards,
})
if err != nil {
log.Fatal(err)
}
node.SetBroker(broker)
presenceManager, err := centrifuge.NewRedisPresenceManager(node, centrifuge.RedisPresenceManagerConfig{
Shards: redisShards,
})
if err != nil {
log.Fatal(err)
}
node.SetPresenceManager(presenceManager)
node.OnConnecting(func(ctx context.Context, e centrifuge.ConnectEvent) (centrifuge.ConnectReply, error) {
cred, _ := centrifuge.GetCredentials(ctx)
return centrifuge.ConnectReply{
Data: []byte(`{}`),
// Subscribe to personal several server-side channel.
Subscriptions: map[string]centrifuge.SubscribeOptions{
"#" + cred.UserID: {EnableRecovery: true, EmitPresence: true, EmitJoinLeave: true, PushJoinLeave: true},
},
}, nil
})
node.OnConnect(func(client *centrifuge.Client) {
transport := client.Transport()
log.Printf("user %s connected via %s with protocol: %s", client.UserID(), transport.Name(), transport.Protocol())
// Event handler should not block, so start separate goroutine to
// periodically send messages to client.
go func() {
for {
select {
case <-client.Context().Done():
return
case <-time.After(5 * time.Second):
err := client.Send([]byte(`{"time": "` + strconv.FormatInt(time.Now().Unix(), 10) + `"}`))
if err != nil {
if err == io.EOF {
return
}
log.Printf("error sending message: %s", err)
}
}
}
}()
client.OnAlive(func() {
log.Printf("user %s connection is still active", client.UserID())
})
client.OnRefresh(func(e centrifuge.RefreshEvent, cb centrifuge.RefreshCallback) {
log.Printf("user %s connection is going to expire, refreshing", client.UserID())
cb(centrifuge.RefreshReply{
ExpireAt: time.Now().Unix() + 60,
}, nil)
})
client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) {
log.Printf("user %s subscribes on %s", client.UserID(), e.Channel)
if !channelSubscribeAllowed(e.Channel) {
cb(centrifuge.SubscribeReply{}, centrifuge.ErrorPermissionDenied)
return
}
cb(centrifuge.SubscribeReply{
Options: centrifuge.SubscribeOptions{
EnablePositioning: e.Positioned,
EnableRecovery: e.Recoverable,
EmitPresence: true,
EmitJoinLeave: true,
PushJoinLeave: e.JoinLeave,
Data: []byte(`{"msg": "welcome"}`),
},
}, nil)
})
client.OnUnsubscribe(func(e centrifuge.UnsubscribeEvent) {
log.Printf("user %s unsubscribed from %s (%s)", client.UserID(), e.Channel, e.Reason)
})
client.OnPublish(func(e centrifuge.PublishEvent, cb centrifuge.PublishCallback) {
log.Printf("user %s publishes into channel %s: %s", client.UserID(), e.Channel, string(e.Data))
if !client.IsSubscribed(e.Channel) {
cb(centrifuge.PublishReply{}, centrifuge.ErrorPermissionDenied)
return
}
var msg clientMessage
err := json.Unmarshal(e.Data, &msg)
if err != nil {
cb(centrifuge.PublishReply{}, centrifuge.ErrorBadRequest)
return
}
msg.Timestamp = time.Now().Unix()
data, _ := json.Marshal(msg)
result, err := node.Publish(
e.Channel, data,
centrifuge.WithHistory(300, time.Minute),
centrifuge.WithClientInfo(e.ClientInfo),
)
cb(centrifuge.PublishReply{Result: &result}, err)
})
client.OnRPC(func(e centrifuge.RPCEvent, cb centrifuge.RPCCallback) {
log.Printf("[user %s] sent RPC, data: %s, method: %s", client.UserID(), string(e.Data), e.Method)
switch e.Method {
case "getCurrentYear":
cb(centrifuge.RPCReply{Data: []byte(`{"year": "2020"}`)}, nil)
default:
cb(centrifuge.RPCReply{}, centrifuge.ErrorMethodNotFound)
}
})
client.OnPresence(func(e centrifuge.PresenceEvent, cb centrifuge.PresenceCallback) {
log.Printf("user %s calls presence on %s", client.UserID(), e.Channel)
if !client.IsSubscribed(e.Channel) {
cb(centrifuge.PresenceReply{}, centrifuge.ErrorPermissionDenied)
return
}
cb(centrifuge.PresenceReply{}, nil)
})
client.OnDisconnect(func(e centrifuge.DisconnectEvent) {
log.Printf("user %s disconnected (%s)", client.UserID(), e.Reason)
})
})
go func() {
// Publish to channel periodically.
i := 1
for {
_, err := node.Publish(
"chat:index",
[]byte(`{"input": "Publish from server `+strconv.Itoa(i)+`"}`),
centrifuge.WithHistory(300, time.Minute),
)
if err != nil {
log.Printf("error publishing to channel: %s", err)
}
i++
time.Sleep(10000 * time.Millisecond)
}
}()
if err := node.Run(); err != nil {
log.Fatal(err)
}
mux := http.DefaultServeMux
mux.Handle("/connection/websocket", authMiddleware(
centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{}),
))
mux.Handle("/connection/http_stream", authMiddleware(centrifuge.NewHTTPStreamHandler(node, centrifuge.HTTPStreamConfig{})))
mux.Handle("/connection/sse", authMiddleware(centrifuge.NewSSEHandler(node, centrifuge.SSEConfig{})))
mux.Handle("/emulation", centrifuge.NewEmulationHandler(node, centrifuge.EmulationConfig{}))
mux.Handle("/metrics", promhttp.Handler())
mux.Handle("/", http.FileServer(http.Dir("./")))
server := &http.Server{
Handler: mux,
Addr: ":" + strconv.Itoa(*port),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
go func() {
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}()
waitExitSignal(node)
log.Println("bye!")
}