init
This commit is contained in:
1 parent
48eaf48797
commit
e32e55df15
20 files changed
+369
-117
No files matched your search
Generated
+9
-15
@@ -57,31 +57,25 @@
|
||||
version = "v1.3.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:6b7e9b1e2f944a0c84f29943f705954d2d8cfbf6477c37a10d0c80acdbc2445f"
|
||||
digest = "1:324591cd9122f94cc39a87bd44ec71153672c239e2cff5743bfad96b60be3749"
|
||||
name = "github.com/googollee/go-engine.io"
|
||||
packages = [
|
||||
".",
|
||||
"base",
|
||||
"packet",
|
||||
"payload",
|
||||
"message",
|
||||
"parser",
|
||||
"polling",
|
||||
"transport",
|
||||
"transport/polling",
|
||||
"transport/websocket",
|
||||
"websocket",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "cc5b8c07e074e97f6bc6f4c6dbc03cf06267e6e0"
|
||||
version = "v1.4.1"
|
||||
revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:25fa43cb2f30c0ab54aaabf05167c56c7e385635b3651015c5726ecb737a905e"
|
||||
digest = "1:3eb026ba34d6dd12b45bb6abd63b4e917ebca8d8f3022a139c0881d900ad1bee"
|
||||
name = "github.com/googollee/go-socket.io"
|
||||
packages = [
|
||||
".",
|
||||
"parser",
|
||||
]
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "96da97a7c8f269421388fbb0dca12aa3c0699088"
|
||||
version = "v1.4.1"
|
||||
revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:7b5c6e2eeaa9ae5907c391a91c132abfd5c9e8a784a341b5625e750c67e6825d"
|
||||
|
||||
@@ -36,3 +36,11 @@
|
||||
name = "github.com/valyala/fasthttp"
|
||||
branch = "master"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/googollee/go-socket.io"
|
||||
revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/googollee/go-engine.io"
|
||||
revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509"
|
||||
|
||||
+21
-1
@@ -11,6 +11,7 @@ import (
|
||||
var (
|
||||
ErrNoLeader = errors.New("no leader in cluster")
|
||||
ErrLeaderClientNotInitialized = errors.New("leader client not initialized")
|
||||
ErrNotLeader = errors.New("node is not a leader")
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -27,12 +28,20 @@ type ClusterClient struct {
|
||||
}
|
||||
|
||||
func (client *ClusterClient) Shutdown() error {
|
||||
client.leaderMu.Lock()
|
||||
defer client.leaderMu.Unlock()
|
||||
|
||||
if client.leaderClient != nil {
|
||||
client.leaderClient.Close()
|
||||
client.leaderClient = nil
|
||||
}
|
||||
|
||||
return client.r.GracefulShutdown()
|
||||
}
|
||||
|
||||
func (client *ClusterClient) SyncApply(command []byte) (interface{}, error) {
|
||||
client.leaderMu.RLock()
|
||||
defer client.leaderMu.Unlock()
|
||||
defer client.leaderMu.RUnlock()
|
||||
|
||||
if !client.leaderState.leaderElected {
|
||||
return nil, ErrNoLeader
|
||||
@@ -48,6 +57,17 @@ func (client *ClusterClient) SyncApply(command []byte) (interface{}, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (client *ClusterClient) SyncApplyOnLeader(command []byte) (interface{}, error) {
|
||||
client.leaderMu.RLock()
|
||||
defer client.leaderMu.RUnlock()
|
||||
|
||||
if !client.leaderState.isLeader {
|
||||
return nil, ErrNotLeader
|
||||
}
|
||||
|
||||
return client.r.SyncApply(command)
|
||||
}
|
||||
|
||||
func (client *ClusterClient) listenLeader() {
|
||||
for n := range client.r.LeaderCh() {
|
||||
logger.Debug(n)
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type CommandType int
|
||||
|
||||
const (
|
||||
UpdateModule CommandType = iota
|
||||
DeleteModule
|
||||
UpdateConfiguration
|
||||
DeleteConfiguration
|
||||
UpdateSchema
|
||||
DeleteSchema
|
||||
)
|
||||
|
||||
type Command interface {
|
||||
Apply(s State) State
|
||||
}
|
||||
|
||||
type UpdateModuleCommand struct {
|
||||
Module entity.Module
|
||||
}
|
||||
|
||||
type operation struct {
|
||||
Command CommandType
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
func UnmarshalCommand(data []byte) (Command, error) {
|
||||
op := operation{}
|
||||
if err := json.Unmarshal(data, &op); err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal operation")
|
||||
}
|
||||
|
||||
switch op.Command {
|
||||
case UpdateModule:
|
||||
|
||||
case DeleteModule:
|
||||
case UpdateConfiguration:
|
||||
case DeleteConfiguration:
|
||||
case UpdateSchema:
|
||||
case DeleteSchema:
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
+4
-1
@@ -1,5 +1,8 @@
|
||||
package cluster
|
||||
|
||||
const (
|
||||
applyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND"
|
||||
ApplyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND"
|
||||
|
||||
TokenParam = "token"
|
||||
ClusterParam = "cluster"
|
||||
)
|
||||
@@ -3,9 +3,7 @@ package cluster
|
||||
import (
|
||||
"github.com/cenkalti/backoff"
|
||||
gosocketio "github.com/integration-system/golang-socketio"
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
"github.com/integration-system/isp-lib/logger"
|
||||
"isp-config-service/conf"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
@@ -15,7 +13,7 @@ type SocketLeaderClient struct {
|
||||
}
|
||||
|
||||
func (c *SocketLeaderClient) Send(data []byte, timeout time.Duration) (string, error) {
|
||||
return c.c.Ack(applyCommandEvent, data, timeout)
|
||||
return c.c.Ack(ApplyCommandEvent, data, timeout)
|
||||
}
|
||||
|
||||
func (c *SocketLeaderClient) Dial(timeout time.Duration) error {
|
||||
@@ -29,7 +27,7 @@ func (c *SocketLeaderClient) Close() {
|
||||
}
|
||||
|
||||
func NewSocketLeaderClient(address string) *SocketLeaderClient {
|
||||
socketIoAddress := getSocketIoAddress(address)
|
||||
socketIoAddress := getSocketIoUrl(address)
|
||||
client := gosocketio.NewClientBuilder().
|
||||
EnableReconnection().
|
||||
ReconnectionTimeout(1 * time.Second).
|
||||
@@ -42,12 +40,20 @@ func NewSocketLeaderClient(address string) *SocketLeaderClient {
|
||||
}
|
||||
}
|
||||
|
||||
func getSocketIoAddress(address string) string {
|
||||
func getSocketIoUrl(address string) string {
|
||||
addr, err := net.ResolveTCPAddr("tcp", address)
|
||||
if err != nil {
|
||||
panic(err) //must never occured
|
||||
}
|
||||
|
||||
cfg := config.Get().(*conf.Configuration)
|
||||
return net.JoinHostPort(addr.IP.String(), cfg.WS.Rest.Port)
|
||||
/*cfg := config.Get().(*conf.Configuration)
|
||||
port, err := strconv.Atoi(cfg.WS.Rest.Port)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}*/
|
||||
|
||||
return gosocketio.GetUrl(addr.IP.String(), 9001, false, map[string]string{
|
||||
ClusterParam: "true",
|
||||
}) //TODO for test
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package cluster
|
||||
|
||||
import "isp-config-service/entity"
|
||||
|
||||
type State struct {
|
||||
Configurations map[int64]entity.Config
|
||||
Modules map[int32]entity.Module
|
||||
Instances map[int32]entity.Instance
|
||||
Schemas map[int32]entity.ConfigSchema
|
||||
}
|
||||
+6
-5
@@ -14,13 +14,13 @@ grpcOuterAddress:
|
||||
|
||||
ws:
|
||||
rest:
|
||||
port: "9001"
|
||||
port: "9011"
|
||||
ip: "0.0.0.0"
|
||||
grpc:
|
||||
port: "9002"
|
||||
port: "9022"
|
||||
ip: "0.0.0.0"
|
||||
raft:
|
||||
port: "9003"
|
||||
port: "9004"
|
||||
ip: "0.0.0.0"
|
||||
|
||||
metrics:
|
||||
@@ -35,6 +35,7 @@ metrics:
|
||||
cluster:
|
||||
dataDir: ./data
|
||||
inMemory: true
|
||||
outerAddress: 127.0.0.1:9003
|
||||
outerAddress: 127.0.0.1:9004
|
||||
peers:
|
||||
- 127.0.0.1:9003
|
||||
#- 127.0.0.1:9003
|
||||
- 127.0.0.1:9004
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"isp-config-service/helper"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/raft"
|
||||
"isp-config-service/state"
|
||||
"isp-config-service/subs"
|
||||
"isp-config-service/ws"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -35,8 +37,8 @@ func init() {
|
||||
func main() {
|
||||
cfg := config.Get().(*conf.Configuration)
|
||||
|
||||
initWebsocket(cfg.WS.Rest.GetAddress())
|
||||
initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster)
|
||||
client, store := initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster)
|
||||
initWebsocket(cfg.WS.Rest.GetAddress(), client, store)
|
||||
initGrpc(cfg.WS.Grpc)
|
||||
|
||||
ctx := context.Background()
|
||||
@@ -47,11 +49,13 @@ func main() {
|
||||
<-shutdownChan
|
||||
}
|
||||
|
||||
func initWebsocket(bindAddress string) {
|
||||
func initWebsocket(bindAddress string, clusterClint *cluster.ClusterClient, store *state.Store) {
|
||||
socket, err := ws.NewWebsocketServer()
|
||||
if err != nil {
|
||||
logger.Fatal(err)
|
||||
}
|
||||
subs.NewSocketEventHandler(socket, clusterClint, store).SubscribeAll()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/socket.io/", socket.ServeHttp)
|
||||
httpServer := &http.Server{Addr: bindAddress, Handler: mux}
|
||||
@@ -66,16 +70,20 @@ func initWebsocket(bindAddress string) {
|
||||
logger.Infof("socket.IO server start on %s", bindAddress)
|
||||
}
|
||||
|
||||
func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration) {
|
||||
r, err := raft.NewRaft(bindAddress, clusterCfg)
|
||||
func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration) (*cluster.ClusterClient, *state.Store) {
|
||||
store := state.NewStateStore()
|
||||
r, err := raft.NewRaft(bindAddress, clusterCfg, store)
|
||||
if err != nil {
|
||||
logger.Fatal(err)
|
||||
}
|
||||
holder.ClusterClient = cluster.NewRaftClusterClient(r)
|
||||
clusterClient := cluster.NewRaftClusterClient(r)
|
||||
holder.ClusterClient = clusterClient
|
||||
|
||||
_ = r.BootstrapCluster() // err can be ignored
|
||||
|
||||
logger.Infof("raft server start on %s", bindAddress)
|
||||
|
||||
return clusterClient, store
|
||||
}
|
||||
|
||||
func initGrpc(bindAddress structure.AddressConfiguration) {
|
||||
|
||||
+2
-2
@@ -83,7 +83,7 @@ func (r *Raft) listenLeader() {
|
||||
}
|
||||
}
|
||||
|
||||
func NewRaft(bind string, configuration conf.ClusterConfiguration) (*Raft, error) {
|
||||
func NewRaft(bind string, configuration conf.ClusterConfiguration, state raft.FSM) (*Raft, error) {
|
||||
logStore, store, snapshotStore, err := makeStores(configuration)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -100,7 +100,7 @@ func NewRaft(bind string, configuration conf.ClusterConfiguration) (*Raft, error
|
||||
|
||||
cfg := raft.DefaultConfig()
|
||||
cfg.LocalID = raft.ServerID(configuration.OuterAddress)
|
||||
r, err := raft.NewRaft(cfg, nil, logStore, store, snapshotStore, trans)
|
||||
r, err := raft.NewRaft(cfg, state, logStore, store, snapshotStore, trans)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create raft")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package state
|
||||
|
||||
import "github.com/integration-system/isp-lib/structure"
|
||||
|
||||
type Mesh struct {
|
||||
modulesMap map[string]NodesMap
|
||||
}
|
||||
|
||||
func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
||||
nodes[address] = backend
|
||||
} else {
|
||||
m.modulesMap[backend.ModuleName] = NodesMap{address: backend}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
||||
delete(nodes, address)
|
||||
if len(nodes) == 0 {
|
||||
delete(m.modulesMap, backend.ModuleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type NodesMap map[string]structure.BackendDeclaration
|
||||
|
||||
func NewMesh() *Mesh {
|
||||
return &Mesh{modulesMap: make(map[string]NodesMap)}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package state
|
||||
|
||||
type state struct {
|
||||
mesh *Mesh
|
||||
}
|
||||
|
||||
func newState() state {
|
||||
return state{
|
||||
mesh: NewMesh(),
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package cluster
|
||||
package state
|
||||
|
||||
import (
|
||||
"github.com/hashicorp/raft"
|
||||
@@ -14,7 +14,7 @@ var (
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
state State
|
||||
state state
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
@@ -29,14 +29,14 @@ func (f *Store) Snapshot() (raft.FSMSnapshot, error) {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
|
||||
copied := deepcopy.Copy(f.state).(State)
|
||||
copied := deepcopy.Copy(f.state).(state)
|
||||
|
||||
return &fsmSnapshot{copied}, nil
|
||||
}
|
||||
|
||||
// Restore stores the key-value store to a previous state.
|
||||
func (f *Store) Restore(rc io.ReadCloser) error {
|
||||
s := State{}
|
||||
s := state{}
|
||||
|
||||
if err := json.NewDecoder(rc).Decode(&s); err != nil {
|
||||
return errors.WithMessage(err, "unmarshal state")
|
||||
@@ -48,7 +48,7 @@ func (f *Store) Restore(rc io.ReadCloser) error {
|
||||
}
|
||||
|
||||
type fsmSnapshot struct {
|
||||
state State
|
||||
state state
|
||||
}
|
||||
|
||||
func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {
|
||||
@@ -73,3 +73,9 @@ func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {
|
||||
}
|
||||
|
||||
func (f *fsmSnapshot) Release() {}
|
||||
|
||||
func NewStateStore() *Store {
|
||||
return &Store{
|
||||
state: newState(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package subs
|
||||
|
||||
import "isp-config-service/ws"
|
||||
|
||||
func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) {
|
||||
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleRoutesUpdate(conn ws.Conn, data []byte) {
|
||||
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) {
|
||||
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) {
|
||||
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleRequestConfig(conn ws.Conn, data []byte) {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package subs
|
||||
|
||||
import (
|
||||
"isp-config-service/ws"
|
||||
)
|
||||
|
||||
func (h *socketEventHandler) applyCommandOnLeader(conn ws.Conn, cmd []byte) string {
|
||||
_, err := h.cluster.SyncApplyOnLeader(cmd)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package subs
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/logger"
|
||||
"isp-config-service/cluster"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/state"
|
||||
"isp-config-service/ws"
|
||||
)
|
||||
|
||||
const (
|
||||
ok = "ok"
|
||||
|
||||
followersRoom = "followers"
|
||||
)
|
||||
|
||||
type socketEventHandler struct {
|
||||
socket *ws.WebsocketServer
|
||||
cluster *cluster.ClusterClient
|
||||
state *state.Store
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) SubscribeAll() {
|
||||
h.socket.
|
||||
OnConnect(h.handleConnect).
|
||||
OnDisconnect(h.handleDisconnect).
|
||||
OnError(h.handleError).
|
||||
OnWithAck(cluster.ApplyCommandEvent, h.applyCommandOnLeader)
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleConnect(conn ws.Conn) {
|
||||
if conn.IsConfigClusterNode() {
|
||||
holder.Socket.Rooms().Join(conn, followersRoom)
|
||||
} else {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleDisconnect(conn ws.Conn) {
|
||||
if conn.IsConfigClusterNode() {
|
||||
holder.Socket.Rooms().Leave(conn, followersRoom)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleError(conn ws.Conn, err error) {
|
||||
logger.Warnf("socket.io: %v", err)
|
||||
}
|
||||
|
||||
func NewSocketEventHandler(socket *ws.WebsocketServer, cluster *cluster.ClusterClient, state *state.Store) *socketEventHandler {
|
||||
return &socketEventHandler{
|
||||
socket: socket,
|
||||
cluster: cluster,
|
||||
state: state,
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
socketio "github.com/googollee/go-socket.io"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"isp-config-service/cluster"
|
||||
)
|
||||
|
||||
type Conn interface {
|
||||
Id() string
|
||||
Emit(event string, args ...interface{}) error
|
||||
IsConfigClusterNode() bool
|
||||
SetBackendDeclaration(backend structure.BackendDeclaration)
|
||||
GetBackendDeclaration() *structure.BackendDeclaration
|
||||
}
|
||||
|
||||
type wsConn struct {
|
||||
conn socketio.Socket
|
||||
backend *structure.BackendDeclaration
|
||||
}
|
||||
|
||||
func (c *wsConn) Id() string {
|
||||
return c.conn.Id()
|
||||
}
|
||||
|
||||
func (c *wsConn) Emit(event string, args ...interface{}) error {
|
||||
return c.conn.Emit(event, args...)
|
||||
}
|
||||
|
||||
func (c *wsConn) IsConfigClusterNode() bool {
|
||||
isCluster := c.conn.Request().URL.Query().Get(cluster.ClusterParam)
|
||||
return isCluster == "true"
|
||||
}
|
||||
|
||||
func (c *wsConn) SetBackendDeclaration(backend structure.BackendDeclaration) {
|
||||
c.backend = &backend
|
||||
}
|
||||
|
||||
func (c *wsConn) GetBackendDeclaration() *structure.BackendDeclaration {
|
||||
return c.backend
|
||||
}
|
||||
+47
-11
@@ -1,35 +1,71 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
socketio "github.com/googollee/go-socket.io"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
idsRoom = "__id"
|
||||
)
|
||||
|
||||
type RoomStore struct {
|
||||
mu sync.RWMutex
|
||||
rooms map[string]map[string]socketio.Conn
|
||||
rooms map[string]map[string]Conn
|
||||
}
|
||||
|
||||
func (s *RoomStore) Join(conn socketio.Conn, rooms ...string) {
|
||||
func (s *RoomStore) GetOrJoinById(id string, new Conn) Conn {
|
||||
s.mu.RLock()
|
||||
var (
|
||||
conn Conn
|
||||
ok bool
|
||||
)
|
||||
idRoom, roomExist := s.rooms[idsRoom]
|
||||
if roomExist {
|
||||
conn, ok = idRoom[id]
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
if ok {
|
||||
return conn
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
idRoom, roomExist = s.rooms[idsRoom]
|
||||
if roomExist {
|
||||
conn, ok = idRoom[id]
|
||||
}
|
||||
if ok {
|
||||
return conn
|
||||
}
|
||||
conn = new
|
||||
if !roomExist {
|
||||
s.rooms[idsRoom] = map[string]Conn{conn.Id(): conn}
|
||||
return conn
|
||||
}
|
||||
idRoom[conn.Id()] = conn
|
||||
return conn
|
||||
}
|
||||
|
||||
func (s *RoomStore) Join(conn Conn, rooms ...string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, room := range rooms {
|
||||
if conns, ok := s.rooms[room]; ok {
|
||||
conns[conn.ID()] = conn
|
||||
conns[conn.Id()] = conn
|
||||
} else {
|
||||
s.rooms[room] = map[string]socketio.Conn{conn.ID(): conn}
|
||||
s.rooms[room] = map[string]Conn{conn.Id(): conn}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RoomStore) Leave(conn socketio.Conn, rooms ...string) {
|
||||
func (s *RoomStore) Leave(conn Conn, rooms ...string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, room := range rooms {
|
||||
if conns, ok := s.rooms[room]; ok {
|
||||
delete(conns, conn.ID())
|
||||
delete(conns, conn.Id())
|
||||
if len(conns) == 0 {
|
||||
delete(s.rooms, room)
|
||||
}
|
||||
@@ -37,15 +73,15 @@ func (s *RoomStore) Leave(conn socketio.Conn, rooms ...string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RoomStore) ToBroadcast(except socketio.Conn, rooms ...string) []socketio.Conn {
|
||||
func (s *RoomStore) ToBroadcast(except Conn, rooms ...string) []Conn {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]socketio.Conn, 0)
|
||||
result := make([]Conn, 0)
|
||||
for _, room := range rooms {
|
||||
if conns, ok := s.rooms[room]; ok {
|
||||
for id, conn := range conns {
|
||||
if id != except.ID() {
|
||||
if id != except.Id() {
|
||||
result = append(result, conn)
|
||||
}
|
||||
}
|
||||
@@ -58,6 +94,6 @@ func (s *RoomStore) ToBroadcast(except socketio.Conn, rooms ...string) []socketi
|
||||
func NewRoomStore() *RoomStore {
|
||||
return &RoomStore{
|
||||
mu: sync.RWMutex{},
|
||||
rooms: make(map[string]map[string]socketio.Conn),
|
||||
rooms: make(map[string]map[string]Conn),
|
||||
}
|
||||
}
|
||||
+52
-5
@@ -2,6 +2,8 @@ package ws
|
||||
|
||||
import (
|
||||
"github.com/googollee/go-socket.io"
|
||||
gosocketio "github.com/integration-system/golang-socketio"
|
||||
"github.com/integration-system/isp-lib/logger"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
@@ -11,7 +13,7 @@ type WebsocketServer struct {
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) Close() error {
|
||||
return s.s.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) ServeHttp(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -22,10 +24,57 @@ func (s *WebsocketServer) Rooms() *RoomStore {
|
||||
return s.roomStore
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) Broadcast(except socketio.Conn, room string, msg string, v ...interface{}) error {
|
||||
func (s *WebsocketServer) OnWithAck(event string, f func(conn Conn, data []byte) string) *WebsocketServer {
|
||||
must(s.s.On(event, func(conn socketio.Socket, data []byte) string {
|
||||
logger.Debugf("[%s]:$s:%s", conn.Request().RemoteAddr, event, string(data))
|
||||
|
||||
return f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), data)
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) On(event string, f func(conn Conn, data []byte)) *WebsocketServer {
|
||||
must(s.s.On(event, func(conn socketio.Socket, data []byte) {
|
||||
logger.Debugf("[%s]:$s:%s", conn.Request().RemoteAddr, event, string(data))
|
||||
|
||||
f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), data)
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) OnConnect(f func(Conn)) *WebsocketServer {
|
||||
must(s.s.On(gosocketio.OnConnection, func(conn socketio.Socket) {
|
||||
logger.Debugf("[%s]:$s", conn.Request().RemoteAddr, gosocketio.OnConnection)
|
||||
|
||||
f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}))
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) OnDisconnect(f func(Conn)) *WebsocketServer {
|
||||
must(s.s.On(gosocketio.OnDisconnection, func(conn socketio.Socket) {
|
||||
logger.Debugf("[%s]:$s", conn.Request().RemoteAddr, gosocketio.OnDisconnection)
|
||||
|
||||
c := s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn})
|
||||
f(c)
|
||||
s.roomStore.Leave(c, idsRoom)
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) OnError(f func(Conn, error)) *WebsocketServer {
|
||||
must(s.s.On(gosocketio.OnError, func(conn socketio.Socket, err error) {
|
||||
logger.Debugf("[%s]:$s:%v", conn.Request().RemoteAddr, gosocketio.OnError, err)
|
||||
|
||||
f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), err)
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) Broadcast(except Conn, room string, msg string, v ...interface{}) error {
|
||||
conns := s.roomStore.ToBroadcast(except, room)
|
||||
for _, conn := range conns {
|
||||
conn.Emit(msg, v...)
|
||||
_ = conn.Emit(msg, v...)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -36,8 +85,6 @@ func NewWebsocketServer() (*WebsocketServer, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go server.Serve()
|
||||
|
||||
return &WebsocketServer{
|
||||
s: server,
|
||||
roomStore: NewRoomStore(),
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package ws
|
||||
|
||||
func must(err error) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user