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
|
package main
import (
"context"
"flag"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
_ "net/http/pprof"
"github.com/centrifugal/centrifuge"
"github.com/centrifugal/centrifuge/_examples/custom_engine_tarantool/tntengine"
)
var (
port = flag.Int("port", 8000, "Port to bind app to")
sharded = flag.Bool("sharded", false, "Start sharded example")
ha = flag.Bool("ha", false, "Start high availability example")
raft = flag.Bool("raft", false, "Using Raft-based replication")
user = flag.String("user", "guest", "Connection user")
password = flag.String("password", "", "Connection password")
)
func handleLog(e centrifuge.LogEntry) {
log.Printf("[centrifuge] %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()
ctx = centrifuge.SetCredentials(ctx, ¢rifuge.Credentials{
UserID: "42",
Info: []byte(`{"name": "Alexander"}`),
})
r = r.WithContext(ctx)
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
}
func main() {
flag.Parse()
cfg := centrifuge.DefaultConfig
cfg.LogLevel = centrifuge.LogLevelDebug
cfg.LogHandler = handleLog
node, _ := centrifuge.New(cfg)
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())
client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) {
log.Printf("user %s subscribes on %s", client.UserID(), e.Channel)
cb(centrifuge.SubscribeReply{
Options: centrifuge.SubscribeOptions{
Presence: true,
JoinLeave: true,
Recover: true,
},
}, nil)
})
client.OnUnsubscribe(func(e centrifuge.UnsubscribeEvent) {
log.Printf("user %s unsubscribed from %s", client.UserID(), e.Channel)
})
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))
cb(centrifuge.PublishReply{
Options: centrifuge.PublishOptions{
HistorySize: 10,
HistoryTTL: 10 * time.Minute,
},
}, nil)
})
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.OnPresenceStats(func(e centrifuge.PresenceStatsEvent, cb centrifuge.PresenceStatsCallback) {
log.Printf("user %s calls presence stats on %s", client.UserID(), e.Channel)
if !client.IsSubscribed(e.Channel) {
cb(centrifuge.PresenceStatsReply{}, centrifuge.ErrorPermissionDenied)
return
}
cb(centrifuge.PresenceStatsReply{}, nil)
})
client.OnDisconnect(func(e centrifuge.DisconnectEvent) {
log.Printf("user %s disconnected, disconnect: %s", client.UserID(), e.Disconnect)
})
})
// Single Tarantool.
mode := tntengine.ConnectionModeSingleInstance
shardAddresses := [][]string{
{"127.0.0.1:3301"},
}
if *ha {
if *raft {
// Single Tarantool RS with automatic leader election with Raft (Tarantool >= 2.7.0).
shardAddresses = [][]string{
{"127.0.0.1:3301", "127.0.0.1:3302", "127.0.0.1:3303"},
}
mode = tntengine.ConnectionModeLeaderFollowerRaft
} else {
// Single Tarantool RS with automatic leader election (ex. in Cartridge).
shardAddresses = [][]string{
{"127.0.0.1:3301", "127.0.0.1:3302"},
}
mode = tntengine.ConnectionModeLeaderFollower
}
} else if *sharded {
// Client-side sharding between two Tarantool instances (without HA).
shardAddresses = [][]string{
{"127.0.0.1:3301"},
{"127.0.0.1:3302"},
}
}
var shards []*tntengine.Shard
for _, addresses := range shardAddresses {
shard, err := tntengine.NewShard(tntengine.ShardConfig{
Addresses: addresses,
User: *user,
Password: *password,
ConnectionMode: mode,
})
if err != nil {
log.Fatal(err)
}
shards = append(shards, shard)
}
broker, err := tntengine.NewBroker(node, tntengine.BrokerConfig{
UsePolling: false,
Shards: shards,
})
if err != nil {
log.Fatal(err)
}
node.SetBroker(broker)
presenceManager, err := tntengine.NewPresenceManager(node, tntengine.PresenceManagerConfig{
Shards: shards,
})
if err != nil {
log.Fatal(err)
}
node.SetPresenceManager(presenceManager)
if err := node.Run(); err != nil {
log.Fatal(err)
}
http.Handle("/connection/websocket", authMiddleware(centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{})))
http.Handle("/", http.FileServer(http.Dir("./")))
go func() {
if err := http.ListenAndServe(":"+strconv.Itoa(*port), nil); err != nil {
log.Fatal(err)
}
}()
waitExitSignal(node)
log.Println("bye!")
}
|