cleaned up god functions

This commit is contained in:
Jan Halfar 2016-03-08 15:17:35 +01:00
parent f4311a95c3
commit 8ffae1e119

View File

@ -14,6 +14,7 @@ import (
"github.com/foomo/contentserver/responses" "github.com/foomo/contentserver/responses"
) )
// simple internal request counter
type stats struct { type stats struct {
requests int64 requests int64
chanCount chan int chanCount chan int
@ -46,23 +47,13 @@ type socketServer struct {
repo *repo.Repo repo *repo.Repo
} }
// there should be sth. built in ?! func (s *socketServer) handle(handler string, jsonBytes []byte) (replyBytes []byte, err error) {
// anyway this ony concatenates two "ByteArrays"
func concat(a []byte, b []byte) []byte {
newslice := make([]byte, len(a)+len(b))
copy(newslice, a)
copy(newslice[len(a):], b)
return newslice
}
func (s *socketServer) handleSocketRequest(handler string, jsonBuffer []byte) (replyBytes []byte, err error) {
s.stats.countRequest()
var reply interface{} var reply interface{}
var apiErr error var apiErr error
var jsonErr error var jsonErr error
log.Record(fmt.Sprintf("socket.handleSocketRequest(%d): %s %s", s.stats.requests, handler, string(jsonBuffer)))
ifJSONIsFine := func(err error, processingFunc func()) { processIfJSONIsOk := func(err error, processingFunc func()) {
if err != nil { if err != nil {
jsonErr = err jsonErr = err
return return
@ -73,46 +64,38 @@ func (s *socketServer) handleSocketRequest(handler string, jsonBuffer []byte) (r
switch handler { switch handler {
case "getURIs": case "getURIs":
getURIRequest := &requests.URIs{} getURIRequest := &requests.URIs{}
ifJSONIsFine(json.Unmarshal(jsonBuffer, &getURIRequest), func() { processIfJSONIsOk(json.Unmarshal(jsonBytes, &getURIRequest), func() {
log.Debug(" getURIRequest: " + fmt.Sprint(getURIRequest)) reply = s.repo.GetURIs(getURIRequest.Dimension, getURIRequest.Ids)
uris := s.repo.GetURIs(getURIRequest.Dimension, getURIRequest.Ids)
log.Debug(" resolved: " + fmt.Sprint(uris))
reply = uris
}) })
case "content": case "content":
contentRequest := &requests.Content{} contentRequest := &requests.Content{}
ifJSONIsFine(json.Unmarshal(jsonBuffer, &contentRequest), func() { processIfJSONIsOk(json.Unmarshal(jsonBytes, &contentRequest), func() {
log.Debug("contentRequest:", contentRequest) reply, apiErr = s.repo.GetContent(contentRequest)
content, contentAPIErr := s.repo.GetContent(contentRequest)
apiErr = contentAPIErr
reply = content
}) })
case "getNodes": case "getNodes":
nodesRequest := &requests.Nodes{} nodesRequest := &requests.Nodes{}
ifJSONIsFine(json.Unmarshal(jsonBuffer, &nodesRequest), func() { processIfJSONIsOk(json.Unmarshal(jsonBytes, &nodesRequest), func() {
log.Debug(" nodesRequest: " + fmt.Sprint(nodesRequest)) reply = s.repo.GetNodes(nodesRequest)
nodesMap := s.repo.GetNodes(nodesRequest)
reply = nodesMap
}) })
case "update": case "update":
updateRequest := &requests.Update{} updateRequest := &requests.Update{}
ifJSONIsFine(json.Unmarshal(jsonBuffer, &updateRequest), func() { processIfJSONIsOk(json.Unmarshal(jsonBytes, &updateRequest), func() {
log.Debug(" updateRequest: " + fmt.Sprint(updateRequest)) reply = s.repo.Update()
updateResponse := s.repo.Update()
reply = updateResponse
}) })
case "getRepo": case "getRepo":
repoRequest := &requests.Repo{} repoRequest := &requests.Repo{}
ifJSONIsFine(json.Unmarshal(jsonBuffer, &repoRequest), func() { processIfJSONIsOk(json.Unmarshal(jsonBytes, &repoRequest), func() {
log.Debug(" getRepoRequest: " + fmt.Sprint(repoRequest)) reply = s.repo.GetRepo()
repoResponse := s.repo.GetRepo()
reply = repoResponse
}) })
default: default:
err = errors.New(log.Error(" can not handle this one " + handler)) err = errors.New(log.Error(" can not handle this one " + handler))
errorResponse := responses.NewError(1, "unknown handler") errorResponse := responses.NewError(1, "unknown handler")
reply = errorResponse reply = errorResponse
} }
return s.reply(reply, jsonErr, apiErr)
}
func (s *socketServer) reply(reply interface{}, jsonErr error, apiErr error) (replyBytes []byte, err error) {
if jsonErr != nil { if jsonErr != nil {
err = jsonErr err = jsonErr
log.Error(" could not read incoming json:", jsonErr) log.Error(" could not read incoming json:", jsonErr)
@ -123,7 +106,9 @@ func (s *socketServer) handleSocketRequest(handler string, jsonBuffer []byte) (r
err = apiErr err = apiErr
reply = responses.NewError(3, "internal error "+apiErr.Error()) reply = responses.NewError(3, "internal error "+apiErr.Error())
} }
encodedBytes, jsonReplyErr := json.MarshalIndent(map[string]interface{}{"reply": reply}, "", " ") encodedBytes, jsonReplyErr := json.MarshalIndent(map[string]interface{}{
"reply": reply,
}, "", " ")
if jsonReplyErr != nil { if jsonReplyErr != nil {
err = jsonReplyErr err = jsonReplyErr
log.Error(" could not encode reply " + fmt.Sprint(jsonReplyErr)) log.Error(" could not encode reply " + fmt.Sprint(jsonReplyErr))
@ -133,6 +118,38 @@ func (s *socketServer) handleSocketRequest(handler string, jsonBuffer []byte) (r
return replyBytes, err return replyBytes, err
} }
func extractHandlerAndJSONLentgh(header string) (handler string, jsonLength int) {
headerParts := strings.Split(header, ":")
jsonLength, _ = strconv.Atoi(headerParts[1])
return headerParts[0], jsonLength
}
func (s *socketServer) execute(conn net.Conn, handler string, jsonBytes []byte) {
s.stats.countRequest()
log.Record("socket.handleSocketRequest(%d): %s", s.stats.requests, handler)
if log.SelectedLevel == log.LevelDebug {
log.Debug(" incoming json buffer:", string(jsonBytes))
}
reply, handlingError := s.handle(handler, jsonBytes)
if handlingError != nil {
log.Error("socket.handleConnection handlingError :", handlingError)
if reply == nil {
log.Error("giving up with nil reply")
conn.Close()
return
}
}
headerBytes := []byte(strconv.Itoa(len(reply)))
reply = append(headerBytes, reply...)
log.Debug(" replying: " + string(reply))
_, writeError := conn.Write(reply)
if writeError != nil {
log.Error("socket.handleConnection: could not write my reply: " + fmt.Sprint(writeError))
return
}
log.Debug(" replied. waiting for next request on open connection")
}
func (s *socketServer) handleConnection(conn net.Conn) { func (s *socketServer) handleConnection(conn net.Conn) {
log.Debug("socket.handleConnection") log.Debug("socket.handleConnection")
var headerBuffer [1]byte var headerBuffer [1]byte
@ -147,54 +164,33 @@ func (s *socketServer) handleConnection(conn net.Conn) {
// read next byte // read next byte
current := headerBuffer[0:] current := headerBuffer[0:]
if string(current) == "{" { if string(current) == "{" {
// json has started // reset header
headerParts := strings.Split(header, ":")
header = "" header = ""
requestHandler := headerParts[0] // json has started
jsonLength, _ := strconv.Atoi(headerParts[1]) handler, jsonLength := extractHandlerAndJSONLentgh(header)
log.Debug(fmt.Sprintf(" found json with %d bytes", jsonLength)) log.Debug(fmt.Sprintf(" found json with %d bytes", jsonLength))
if jsonLength > 0 { if jsonLength > 0 {
// let us try to read some json // let us try to read some json
jsonBuffer := make([]byte, jsonLength) jsonBytes := make([]byte, jsonLength)
// that is "{" // that is "{"
jsonBuffer[0] = 123 jsonBytes[0] = 123
_, jsonReadErr := conn.Read(jsonBuffer[1:]) _, jsonReadErr := conn.Read(jsonBytes[1:])
if jsonReadErr != nil { if jsonReadErr != nil {
log.Error(" could not read json - giving up with this client connection" + fmt.Sprint(jsonReadErr)) log.Error(" could not read json - giving up with this client connection" + fmt.Sprint(jsonReadErr))
return return
} }
if log.SelectedLevel == log.LevelDebug { if log.SelectedLevel == log.LevelDebug {
log.Debug(" read json: " + string(jsonBuffer)) log.Debug(" read json: " + string(jsonBytes))
} }
s.execute(conn, handler, jsonBytes)
// execution time
reply, handlingError := s.handleSocketRequest(requestHandler, jsonBuffer)
if handlingError != nil {
log.Error("socket.handleConnection handlingError :", handlingError)
if reply == nil {
log.Error("giving up with nil reply")
conn.Close()
return
}
}
headerBytes := []byte(strconv.Itoa(len(reply)))
reply = concat(headerBytes, reply)
log.Debug(" replying: " + string(reply))
_, writeError := conn.Write(reply)
if writeError != nil {
log.Error("socket.handleConnection: could not write my reply: " + fmt.Sprint(writeError))
return
}
log.Debug(" replied. waiting for next request on open connection")
} else {
log.Error("can not read empty json")
conn.Close()
return return
} }
} else { log.Error("can not read empty json")
// adding to header byte by byte conn.Close()
header += string(headerBuffer[0:]) return
} }
// adding to header byte by byte
header += string(headerBuffer[0:])
} }
} }
@ -209,12 +205,13 @@ func Run(server string, address string, varDir string) error {
if err != nil { if err != nil {
err = errors.New("RunSocketServer: could not start the on \"" + address + "\" - error: " + fmt.Sprint(err)) err = errors.New("RunSocketServer: could not start the on \"" + address + "\" - error: " + fmt.Sprint(err))
// failed to create socket // failed to create socket
log.Error(err.Error) log.Error(err)
return err return err
} }
// there we go // there we go
log.Record("RunSocketServer: started to listen on " + address) log.Record("RunSocketServer: started to listen on " + address)
s.repo.Update() // update can run in bg
go s.repo.Update()
for { for {
// this blocks until connection or error // this blocks until connection or error
conn, err := ln.Accept() conn, err := ln.Accept()