package server import ( "fmt" "net" "sync" "git.loafle.net/commons_go/logging" "git.loafle.net/overflow/overflow_discovery/discovery" cRPC "git.loafle.net/commons_go/rpc" "git.loafle.net/commons_go/server" ) func newServerHandler(addr string, rpcSH RPCServletHandler) ServerHandler { sh := &ServerHandlers{ addr: addr, rpcSH: rpcSH, } sh.Name = "Discovery" return sh } type ServerHandlers struct { server.ServerHandlers rpcSH RPCServletHandler addr string } func (sh *ServerHandlers) Init() error { return nil } func (sh *ServerHandlers) OnStart() { discovery.DiscoveryInit() } func (sh *ServerHandlers) OnConnect(conn net.Conn) (net.Conn, error) { var err error if conn, err = sh.ServerHandlers.OnConnect(conn); nil != err { return nil, err } nConn := newConn(conn, "jsonrpc") return nConn, nil } func (sh *ServerHandlers) Handle(conn net.Conn, stopChan <-chan struct{}, doneChan chan<- error) { var err error rpcServlet := retainRPCServlet(sh.rpcSH) defer func() { releaseRPCServlet(rpcServlet) doneChan <- err }() rpcDoneChan := make(chan error, 1) if err = rpcServlet.Start(soc.Context(), soc, rpcDoneChan); nil != err { return } select { case err = <-rpcDoneChan: case <-stopChan: rpcServlet.Stop() } } func (sh *ServerHandlers) OnStop() { discovery.DiscoveryDestroy() } func (sh *ServerHandlers) Validate() { sh.ServerHandlers.Validate() if "" == sh.addr { logging.Logger().Panic(fmt.Sprintf("Server: Address of server must be specified")) } if nil == sh.rpcSH { logging.Logger().Panic(fmt.Sprintf("Server: RPC Server Handler must be specified")) } } var rpcServletPool sync.Pool func retainRPCServlet(sh RPCServletHandler) cRPC.Servlet { v := rpcServletPool.Get() if v == nil { return cRPC.NewServlet(sh) } return v.(cRPC.Servlet) } func releaseRPCServlet(s cRPC.Servlet) { rpcServletPool.Put(s) }