2023-05-24 15:59:58 +09:00
|
|
|
package wshandler
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"encoding/hex"
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
"net/http"
|
|
|
|
|
"strings"
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
|
|
|
"repositories.action2quare.com/ayo/gocommon"
|
2023-06-21 14:13:30 +09:00
|
|
|
"repositories.action2quare.com/ayo/gocommon/flagx"
|
2023-05-24 15:59:58 +09:00
|
|
|
"repositories.action2quare.com/ayo/gocommon/logger"
|
|
|
|
|
|
|
|
|
|
"github.com/go-redis/redis/v8"
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
|
)
|
|
|
|
|
|
2023-06-21 14:13:30 +09:00
|
|
|
var noSessionFlag = flagx.Bool("nosession", false, "nosession=[true|false]")
|
|
|
|
|
|
2023-07-05 22:26:57 +09:00
|
|
|
type wsconn struct {
|
2023-05-24 15:59:58 +09:00
|
|
|
*websocket.Conn
|
2023-07-05 22:26:57 +09:00
|
|
|
alias string
|
|
|
|
|
accid primitive.ObjectID
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
type UpstreamMessage struct {
|
|
|
|
|
Alias string
|
|
|
|
|
Accid primitive.ObjectID
|
|
|
|
|
Target string
|
|
|
|
|
Body []byte
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
type DownstreamMessage struct {
|
|
|
|
|
Alias string
|
|
|
|
|
Body string
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
type CommandType string
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
const (
|
2023-07-05 22:26:57 +09:00
|
|
|
CommandType_JoinRoom = CommandType("join_room")
|
|
|
|
|
CommandType_LeaveRoom = CommandType("leave_room")
|
2023-07-05 11:27:44 +09:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type CommandMessage struct {
|
|
|
|
|
Cmd CommandType
|
|
|
|
|
Args []string
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-06 12:35:39 +09:00
|
|
|
type WebSocketMessageType int
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
TextMessage = WebSocketMessageType(websocket.TextMessage)
|
|
|
|
|
BinaryMessage = WebSocketMessageType(websocket.BinaryMessage)
|
|
|
|
|
CloseMessage = WebSocketMessageType(websocket.CloseMessage)
|
|
|
|
|
PingMessage = WebSocketMessageType(websocket.PingMessage)
|
|
|
|
|
PongMessage = WebSocketMessageType(websocket.PongMessage)
|
|
|
|
|
Connected = WebSocketMessageType(100)
|
|
|
|
|
Disconnected = WebSocketMessageType(101)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type WebSocketMessageReceiver func(accid primitive.ObjectID, alias string, messageType WebSocketMessageType, body io.Reader)
|
|
|
|
|
|
2023-05-24 15:59:58 +09:00
|
|
|
type subhandler struct {
|
2023-07-06 00:01:45 +09:00
|
|
|
name string
|
2023-07-05 11:27:44 +09:00
|
|
|
authCache *gocommon.AuthCollection
|
|
|
|
|
redisMsgChanName string
|
|
|
|
|
redisCmdChanName string
|
|
|
|
|
redisSync *redis.Client
|
2023-07-05 22:26:57 +09:00
|
|
|
connInOutChan chan *wsconn
|
2023-07-05 11:27:44 +09:00
|
|
|
deliveryChan chan any
|
2023-07-06 12:35:39 +09:00
|
|
|
callReceiver WebSocketMessageReceiver
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// WebsocketHandler :
|
|
|
|
|
type WebsocketHandler struct {
|
|
|
|
|
authCaches map[string]*subhandler
|
|
|
|
|
RedisSync *redis.Client
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type wsConfig struct {
|
|
|
|
|
SyncPipeline string `json:"ws_sync_pipeline"`
|
|
|
|
|
}
|
|
|
|
|
|
2023-07-06 12:35:39 +09:00
|
|
|
func NewWebsocketHandler(authglobal gocommon.AuthCollectionGlobal, receiver WebSocketMessageReceiver) (wsh *WebsocketHandler) {
|
2023-07-05 11:27:44 +09:00
|
|
|
var config wsConfig
|
|
|
|
|
gocommon.LoadConfig(&config)
|
|
|
|
|
|
|
|
|
|
redisSync, err := gocommon.NewRedisClient(config.SyncPipeline, 0)
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
|
|
|
|
|
2023-07-06 12:35:39 +09:00
|
|
|
// decoder := func(r io.Reader) *T {
|
|
|
|
|
// if r == nil {
|
|
|
|
|
// // 접속이 끊겼을 때.
|
|
|
|
|
// return nil
|
|
|
|
|
// }
|
|
|
|
|
// var m T
|
|
|
|
|
// dec := json.NewDecoder(r)
|
|
|
|
|
// if err := dec.Decode(&m); err != nil {
|
|
|
|
|
// logger.Println(err)
|
|
|
|
|
// }
|
|
|
|
|
|
|
|
|
|
// // decoding 실패하더라도 빈 *T를 내보냄
|
|
|
|
|
// return &m
|
|
|
|
|
// }
|
2023-07-05 22:26:57 +09:00
|
|
|
|
2023-05-24 15:59:58 +09:00
|
|
|
authCaches := make(map[string]*subhandler)
|
|
|
|
|
for _, region := range authglobal.Regions() {
|
|
|
|
|
sh := &subhandler{
|
2023-07-06 00:01:45 +09:00
|
|
|
name: region,
|
2023-07-05 11:27:44 +09:00
|
|
|
authCache: authglobal.Get(region),
|
|
|
|
|
redisMsgChanName: fmt.Sprintf("_wsh_msg_%s", region),
|
|
|
|
|
redisCmdChanName: fmt.Sprintf("_wsh_cmd_%s", region),
|
|
|
|
|
redisSync: redisSync,
|
2023-07-05 22:26:57 +09:00
|
|
|
connInOutChan: make(chan *wsconn),
|
2023-07-05 11:27:44 +09:00
|
|
|
deliveryChan: make(chan any, 1000),
|
2023-07-06 12:35:39 +09:00
|
|
|
callReceiver: receiver,
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
authCaches[region] = sh
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &WebsocketHandler{
|
|
|
|
|
authCaches: authCaches,
|
|
|
|
|
RedisSync: redisSync,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (ws *WebsocketHandler) Destructor() {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (ws *WebsocketHandler) RegisterHandlers(ctx context.Context, serveMux *http.ServeMux, prefix string) error {
|
|
|
|
|
for region, sh := range ws.authCaches {
|
|
|
|
|
if region == "default" {
|
|
|
|
|
region = ""
|
|
|
|
|
}
|
2023-07-05 11:27:44 +09:00
|
|
|
url := gocommon.MakeHttpHandlerPattern(prefix, region, "ws")
|
2023-06-21 14:13:30 +09:00
|
|
|
if *noSessionFlag {
|
2023-07-05 11:27:44 +09:00
|
|
|
serveMux.HandleFunc(url, sh.upgrade_nosession)
|
2023-05-24 15:59:58 +09:00
|
|
|
} else {
|
2023-07-05 11:27:44 +09:00
|
|
|
serveMux.HandleFunc(url, sh.upgrade)
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
go sh.mainLoop(ctx)
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
return nil
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-06 00:01:45 +09:00
|
|
|
func (ws *WebsocketHandler) GetState(region string, accid primitive.ObjectID) string {
|
|
|
|
|
state, err := ws.RedisSync.HGet(context.Background(), region, accid.Hex()).Result()
|
|
|
|
|
if err == redis.Nil {
|
|
|
|
|
return ""
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
2023-07-06 00:01:45 +09:00
|
|
|
return state
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
func (sh *subhandler) mainLoop(ctx context.Context) {
|
|
|
|
|
defer func() {
|
|
|
|
|
s := recover()
|
|
|
|
|
if s != nil {
|
|
|
|
|
logger.Error(s)
|
|
|
|
|
}
|
|
|
|
|
}()
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 22:26:57 +09:00
|
|
|
// redis channel에서 유저가 보낸 메시지를 읽는 go rountine
|
2023-07-05 11:27:44 +09:00
|
|
|
go func() {
|
|
|
|
|
var pubsub *redis.PubSub
|
|
|
|
|
for {
|
|
|
|
|
if pubsub == nil {
|
|
|
|
|
pubsub = sh.redisSync.Subscribe(ctx, sh.redisMsgChanName, sh.redisCmdChanName)
|
|
|
|
|
}
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
raw, err := pubsub.ReceiveMessage(ctx)
|
|
|
|
|
if err == nil {
|
|
|
|
|
if raw.Channel == sh.redisMsgChanName {
|
|
|
|
|
var msg UpstreamMessage
|
|
|
|
|
if err := json.Unmarshal([]byte(raw.Payload), &msg); err == nil {
|
|
|
|
|
sh.deliveryChan <- &msg
|
|
|
|
|
} else {
|
|
|
|
|
logger.Println("decode UpstreamMessage failed :", err)
|
|
|
|
|
}
|
|
|
|
|
} else if raw.Channel == sh.redisCmdChanName {
|
|
|
|
|
var cmd CommandMessage
|
|
|
|
|
if err := json.Unmarshal([]byte(raw.Payload), &cmd); err == nil {
|
|
|
|
|
sh.deliveryChan <- &cmd
|
|
|
|
|
} else {
|
|
|
|
|
logger.Println("decode UpstreamMessage failed :", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
logger.Println("pubsub.ReceiveMessage failed :", err)
|
|
|
|
|
pubsub.Close()
|
|
|
|
|
pubsub = nil
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
if ctx.Err() != nil {
|
|
|
|
|
break
|
|
|
|
|
}
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
2023-07-05 11:27:44 +09:00
|
|
|
}
|
|
|
|
|
}()
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 22:26:57 +09:00
|
|
|
entireConns := make(map[string]*wsconn)
|
2023-07-05 11:27:44 +09:00
|
|
|
rooms := make(map[string]*room)
|
|
|
|
|
findRoom := func(name string, create bool) *room {
|
|
|
|
|
room := rooms[name]
|
|
|
|
|
if room == nil && create {
|
|
|
|
|
room = makeRoom(name)
|
|
|
|
|
rooms[name] = room
|
|
|
|
|
room.start(ctx)
|
|
|
|
|
}
|
|
|
|
|
return room
|
|
|
|
|
}
|
|
|
|
|
|
2023-07-05 22:26:57 +09:00
|
|
|
// 유저에게서 온 메세지, 소켓 연결/해체 처리
|
2023-07-05 11:27:44 +09:00
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case usermsg := <-sh.deliveryChan:
|
|
|
|
|
switch usermsg := usermsg.(type) {
|
|
|
|
|
case *UpstreamMessage:
|
|
|
|
|
target := usermsg.Target
|
|
|
|
|
if target[0] == '#' {
|
|
|
|
|
// 룸에 브로드캐스팅
|
|
|
|
|
roomName := target[1:]
|
|
|
|
|
if room := findRoom(roomName, false); room != nil {
|
|
|
|
|
room.broadcast(usermsg)
|
|
|
|
|
}
|
|
|
|
|
} else if target[0] == '@' {
|
|
|
|
|
// TODO : 특정 유저에게만
|
|
|
|
|
}
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
case *CommandMessage:
|
2023-07-05 22:26:57 +09:00
|
|
|
if usermsg.Cmd == CommandType_JoinRoom && len(usermsg.Args) == 2 {
|
2023-07-05 11:27:44 +09:00
|
|
|
alias := usermsg.Args[0]
|
|
|
|
|
roomName := usermsg.Args[1]
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
conn := entireConns[alias]
|
|
|
|
|
if conn != nil {
|
|
|
|
|
findRoom(roomName, true).in(conn)
|
|
|
|
|
}
|
2023-07-05 22:26:57 +09:00
|
|
|
} else if usermsg.Cmd == CommandType_JoinRoom && len(usermsg.Args) == 2 {
|
2023-07-05 11:27:44 +09:00
|
|
|
alias := usermsg.Args[0]
|
|
|
|
|
roomName := usermsg.Args[1]
|
|
|
|
|
|
|
|
|
|
conn := entireConns[alias]
|
|
|
|
|
if conn != nil {
|
|
|
|
|
if room := findRoom(roomName, false); room != nil {
|
|
|
|
|
room.out(conn)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
default:
|
|
|
|
|
logger.Println("usermsg is unknown type")
|
|
|
|
|
}
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
case c := <-sh.connInOutChan:
|
|
|
|
|
if c.Conn == nil {
|
|
|
|
|
delete(entireConns, c.alias)
|
|
|
|
|
for _, room := range rooms {
|
|
|
|
|
room.out(c)
|
|
|
|
|
}
|
2023-07-06 12:35:39 +09:00
|
|
|
sh.callReceiver(c.accid, c.alias, Connected, nil)
|
2023-07-05 11:27:44 +09:00
|
|
|
} else {
|
|
|
|
|
entireConns[c.alias] = c
|
|
|
|
|
}
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
func upgrade_core(sh *subhandler, conn *websocket.Conn, accid primitive.ObjectID, alias string) {
|
2023-07-05 22:26:57 +09:00
|
|
|
newconn := &wsconn{
|
|
|
|
|
Conn: conn,
|
|
|
|
|
alias: alias,
|
|
|
|
|
accid: accid,
|
|
|
|
|
}
|
2023-07-05 11:27:44 +09:00
|
|
|
sh.connInOutChan <- newconn
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 22:26:57 +09:00
|
|
|
go func(c *wsconn, accid primitive.ObjectID, deliveryChan chan<- any) {
|
2023-07-06 00:01:45 +09:00
|
|
|
sh.redisSync.HSet(context.Background(), sh.name, accid.Hex(), "online")
|
2023-05-24 15:59:58 +09:00
|
|
|
for {
|
2023-07-05 11:27:44 +09:00
|
|
|
messageType, r, err := c.NextReader()
|
2023-05-24 15:59:58 +09:00
|
|
|
if err != nil {
|
|
|
|
|
c.Close()
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
if messageType == websocket.CloseMessage {
|
|
|
|
|
break
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
2023-07-05 22:26:57 +09:00
|
|
|
|
|
|
|
|
if messageType == websocket.TextMessage {
|
|
|
|
|
// 유저가 직접 보낸 메시지
|
2023-07-06 12:35:39 +09:00
|
|
|
sh.callReceiver(accid, c.alias, TextMessage, r)
|
|
|
|
|
} else if messageType == websocket.BinaryMessage {
|
|
|
|
|
sh.callReceiver(accid, c.alias, BinaryMessage, r)
|
2023-07-05 22:26:57 +09:00
|
|
|
}
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
2023-07-06 00:01:45 +09:00
|
|
|
sh.redisSync.HDel(context.Background(), sh.name, accid.Hex())
|
2023-05-24 15:59:58 +09:00
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
c.Conn = nil
|
|
|
|
|
sh.connInOutChan <- c
|
2023-05-24 15:59:58 +09:00
|
|
|
}(newconn, accid, sh.deliveryChan)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (sh *subhandler) upgrade_nosession(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
// 클라이언트 접속
|
|
|
|
|
defer func() {
|
|
|
|
|
s := recover()
|
|
|
|
|
if s != nil {
|
|
|
|
|
logger.Error(s)
|
|
|
|
|
}
|
|
|
|
|
io.Copy(io.Discard, r.Body)
|
|
|
|
|
r.Body.Close()
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
auth := strings.Split(r.Header.Get("Authorization"), " ")
|
|
|
|
|
if len(auth) != 2 {
|
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if auth[0] != "Editor" {
|
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
temp, err := hex.DecodeString(auth[1])
|
|
|
|
|
if err != nil {
|
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(temp) != len(primitive.NilObjectID) {
|
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
raw := (*[12]byte)(temp)
|
|
|
|
|
accid := primitive.ObjectID(*raw)
|
|
|
|
|
|
|
|
|
|
var upgrader = websocket.Upgrader{} // use default options
|
|
|
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
var alias string
|
2023-05-24 15:59:58 +09:00
|
|
|
if v := r.Header.Get("AS-X-ALIAS"); len(v) > 0 {
|
2023-07-05 11:27:44 +09:00
|
|
|
alias = v
|
|
|
|
|
} else {
|
|
|
|
|
alias = accid.Hex()
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
upgrade_core(sh, conn, accid, alias)
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (sh *subhandler) upgrade(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
// 클라이언트 접속
|
|
|
|
|
defer func() {
|
|
|
|
|
s := recover()
|
|
|
|
|
if s != nil {
|
|
|
|
|
logger.Error(s)
|
|
|
|
|
}
|
|
|
|
|
io.Copy(io.Discard, r.Body)
|
|
|
|
|
r.Body.Close()
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
sk := r.Header.Get("AS-X-SESSION")
|
|
|
|
|
auth := strings.Split(r.Header.Get("Authorization"), " ")
|
|
|
|
|
if len(auth) != 2 {
|
|
|
|
|
//TODO : 클라이언트는 BadRequest를 받으면 로그인 화면으로 돌아가야 한다.
|
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
authtoken := auth[1]
|
|
|
|
|
|
|
|
|
|
accid, success := sh.authCache.IsValid(sk, authtoken)
|
|
|
|
|
if !success {
|
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var upgrader = websocket.Upgrader{} // use default options
|
|
|
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
var alias string
|
2023-05-24 15:59:58 +09:00
|
|
|
if v := r.Header.Get("AS-X-ALIAS"); len(v) > 0 {
|
2023-07-05 11:27:44 +09:00
|
|
|
alias = v
|
|
|
|
|
} else {
|
|
|
|
|
alias = accid.Hex()
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|
|
|
|
|
|
2023-07-05 11:27:44 +09:00
|
|
|
upgrade_core(sh, conn, accid, alias)
|
2023-05-24 15:59:58 +09:00
|
|
|
}
|