From d678f28909a62df905056ceb6ba21832060d58c7 Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Wed, 4 Sep 2019 14:45:21 +0300 Subject: [PATCH] add commnets --- service/applylog.go | 11 +++++++---- service/discovery.go | 11 ++++++++--- store/apply.go | 2 +- store/state/mesh.go | 4 ++-- store/store.go | 4 ++-- subs/client.go | 4 ++-- subs/root.go | 3 ++- 7 files changed, 24 insertions(+), 15 deletions(-) diff --git a/service/applylog.go b/service/applylog.go index b500959..b498f2f 100644 --- a/service/applylog.go +++ b/service/applylog.go @@ -10,11 +10,13 @@ import ( "isp-config-service/store/state" ) -var ApplyLogService applyLogService +var ( + ClusterStoreService clusterStoreService +) -type applyLogService struct{} +type clusterStoreService struct{} -func (l applyLogService) HandleBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { +func (l clusterStoreService) HandleBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { state.UpsertBackend(declaration) logger.Debug("HandleBackendDeclarationCommand: upserted backend", declaration.ModuleName) DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) @@ -22,7 +24,8 @@ func (l applyLogService) HandleBackendDeclarationCommand(declaration structure.B return state, nil } -func (l applyLogService) PrepareBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { +//TODO вынести как отдельную функция с парметрами вызова (int command, payload interface{}) ([]byte, error) для возможности переиспользования +func (l clusterStoreService) PrepareBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { var buf bytes.Buffer buf2 := make([]byte, 8) binary.BigEndian.PutUint64(buf2, cluster.BackendDeclarationCommand) diff --git a/service/discovery.go b/service/discovery.go index 9f1f958..fe8e7f7 100644 --- a/service/discovery.go +++ b/service/discovery.go @@ -13,16 +13,20 @@ import ( "time" ) -var DiscoveryService = NewDiscoveryService() +const ( + RoutesSubscribersRoom = "__routesSubscribers" +) -var RoutesSubscribersRoom = "__routesSubscribers" +var ( + DiscoveryService = NewDiscoveryService() +) type discoveryService struct { subs map[string][]string lock sync.RWMutex } -func (ds *discoveryService) HandleDisconnect(connId string) { +func (ds *discoveryService) HandleDisconnect(connId string) { //TODO где то передается целиком объект ws.Conn, привести к одному виду(думаю ws.Conn) ds.lock.Lock() defer ds.lock.Unlock() if events, ok := ds.subs[connId]; ok { @@ -79,6 +83,7 @@ func (ds *discoveryService) sendAddrList(conn ws.Conn, event string, addressList } } +//TODO вынесли логику работы с роутами в отдельный сервис func (ds *discoveryService) SubscribeRoutes(conn ws.Conn, state state.State) { holder.Socket.Rooms().Join(conn, RoutesSubscribersRoom) routes := state.GetRoutes() diff --git a/store/apply.go b/store/apply.go index e5fc538..ca39bd5 100644 --- a/store/apply.go +++ b/store/apply.go @@ -13,7 +13,7 @@ func (s *Store) applyBackendDeclarationCommand(data []byte) error { logger.Warnf("Store.applyBackendDeclarationCommand: %s, error parse json data: %s", err.Error()) return err } - state, err := service.ApplyLogService.HandleBackendDeclarationCommand(declaration, s.state) + state, err := service.ClusterStoreService.HandleBackendDeclarationCommand(declaration, s.state) if err != nil { return err } diff --git a/store/state/mesh.go b/store/state/mesh.go index a1d00f1..2f5c8f9 100644 --- a/store/state/mesh.go +++ b/store/state/mesh.go @@ -54,7 +54,7 @@ func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (changed bool return } -func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { +func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { //TODO используется ? if nodes, ok := m.modulesMap[backend.ModuleName]; ok { exist = true if len(nodes) == 0 { @@ -65,7 +65,7 @@ func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { } func (m *Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfiguration { - addressList := []structure.AddressConfiguration{} + addressList := make([]structure.AddressConfiguration, 0) if nodes, ok := m.modulesMap[moduleName]; ok { for _, backend := range nodes { addressList = append(addressList, backend.Address) diff --git a/store/store.go b/store/store.go index 73024fc..28b2063 100644 --- a/store/store.go +++ b/store/store.go @@ -19,7 +19,7 @@ var ( type Store struct { state state.State - lock sync.Mutex + lock sync.Mutex //TODO RWMutex handlers map[uint64]func([]byte) error } @@ -60,7 +60,7 @@ func (s *Store) Restore(rc io.ReadCloser) error { return nil } -func (s *Store) GetState() *state.State { +func (s *Store) GetState() *state.State { //TODO почему указатель ? =), добавим функцию VisitState(f(state state)), попробуем с ней return &s.state } diff --git a/subs/client.go b/subs/client.go index 6942251..fedc817 100644 --- a/subs/client.go +++ b/subs/client.go @@ -15,7 +15,7 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) { instanceUuid, moduleName, err := conn.Parameters() logger.Debug("instanceUuid:", instanceUuid, "moduleName:", moduleName) // REMOVE if err != nil { - _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) + _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) //эти штуки тогда убертся вовсе return } @@ -34,7 +34,7 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) { logger.Warnf("SOCKET ROUTES ERROR, handleModuleDeclaration: %s, error validate routes data: %s", conn.Id(), errors) } else if h.store.GetState().CheckBackendChanged(declaration) { // TODO h.store.GetState() locks - i, err := h.cluster.SyncApply(service.ApplyLogService.PrepareBackendDeclarationCommand(declaration)) + i, err := h.cluster.SyncApply(service.ClusterStoreService.PrepareBackendDeclarationCommand(declaration)) logger.Debug("cluster.SyncApply:", i, err) } diff --git a/subs/root.go b/subs/root.go index a85fd1d..9650dde 100644 --- a/subs/root.go +++ b/subs/root.go @@ -28,7 +28,7 @@ func (h *socketEventHandler) SubscribeAll() { OnDisconnect(h.handleDisconnect). OnError(h.handleError). OnWithAck(cluster.ApplyCommandEvent, h.applyCommandOnLeader). - On(utils.ModuleReady, h.handleModuleReady). + On(utils.ModuleReady, h.handleModuleReady). //TODO сделать функцию с Ack, возвращать текстовку ошибки в случае возниконовения ошибки, константу ok, если все ок On(utils.ModuleSendRequirements, h.handleModuleRequirements) } @@ -45,6 +45,7 @@ func (h *socketEventHandler) handleDisconnect(conn ws.Conn) { holder.Socket.Rooms().Leave(conn, followersRoom) } service.DiscoveryService.HandleDisconnect(conn.Id()) + //TODO при отключении топология кластера меняется, соответсвенно нужно обновлять состояние и уведомлять всех об изменении } func (h *socketEventHandler) handleError(conn ws.Conn, err error) {