From 86bd259dd8ce0cfe7a9acaf66a0a694bf1ba5655 Mon Sep 17 00:00:00 2001 From: Hoofffman <55658814+Hoofffman@users.noreply.github.com> Date: Fri, 8 Dec 2023 15:14:01 +0800 Subject: [PATCH] liangwei beautify code (#354) * code beautify --- agent.go | 8 +++----- core/motan.go | 4 ++-- dynamicConfig.go | 8 ++++---- filter/rateLimit.go | 20 ++++++++++---------- protocol/motanProtocol.go | 30 +++++++++++++++++------------- protocol/motanProtocol_test.go | 6 +++--- server/motanserver.go | 8 ++++---- 7 files changed, 43 insertions(+), 41 deletions(-) diff --git a/agent.go b/agent.go index 103890e4..40538c7a 100644 --- a/agent.go +++ b/agent.go @@ -138,7 +138,7 @@ func (a *Agent) RegisterCommandHandler(f CommandHandler) { a.commandHandlers = append(a.commandHandlers, f) } -func (a *Agent) GetDynamicRegistryInfo() *registrySnapInfoStorage { +func (a *Agent) GetDynamicRegistryInfo() *RegistrySnapInfoStorage { return a.configurer.getRegistryInfo() } @@ -840,6 +840,7 @@ func (a *agentMessageHandler) findCluster(request motan.Request) (c *cluster.Mot if cap(matched) < len(clusters) { matched = make([]serviceMapItem, 0, len(clusters)) } + releaseClusterSlice(matched) for i, rule := range search { if i == 0 { key = rule.cond @@ -848,18 +849,15 @@ func (a *agentMessageHandler) findCluster(request motan.Request) (c *cluster.Mot } err = a.fillMatch(rule.tip, rule.cond, key, clusters, rule.condFn, &matched) if err != nil { - putBackClusterSlice(matched) return } if len(matched) == 1 { c = matched[0].cluster - putBackClusterSlice(matched) return } matched = matched[:0] } err = fmt.Errorf("less condition to select cluster, maybe this service belongs to multiple group, protocol, version; cluster: %s, %s", key, getReqInfo(service, group, protocol, version)) - putBackClusterSlice(matched) return } @@ -1268,7 +1266,7 @@ func (a *Agent) UnexportService(url *motan.URL) error { return nil } -func putBackClusterSlice(s []serviceMapItem) { +func releaseClusterSlice(s []serviceMapItem) { s = s[:0] clusterSlicePool.Put(s) } diff --git a/core/motan.go b/core/motan.go index 01807133..b1ea3d42 100644 --- a/core/motan.go +++ b/core/motan.go @@ -494,7 +494,7 @@ func GetMotanRequestFromPool() *MotanRequest { return requestPool.Get().(*MotanRequest) } -func PutMotanRequestBackPool(req *MotanRequest) { +func ReleaseMotanRequest(req *MotanRequest) { if req != nil { req.Method = "" req.RequestID = 0 @@ -650,7 +650,7 @@ func GetMotanResponseFromPool() *MotanResponse { return responsePool.Get().(*MotanResponse) } -func PutMotanResponseBackPool(resp *MotanResponse) { +func ReleaseMotanResponse(resp *MotanResponse) { if resp != nil { //resp.Reset() resp.RequestID = 0 diff --git a/dynamicConfig.go b/dynamicConfig.go index 98ca0538..afc10cc5 100644 --- a/dynamicConfig.go +++ b/dynamicConfig.go @@ -32,7 +32,7 @@ type DynamicConfigurer struct { agent *Agent } -type registrySnapInfoStorage struct { +type RegistrySnapInfoStorage struct { RegisterNodes []*core.URL `json:"register_nodes"` SubscribeNodes []*core.URL `json:"subscribe_nodes"` } @@ -60,7 +60,7 @@ func (c *DynamicConfigurer) doRecover() error { vlog.Warningln("Read configuration snapshot file error: " + err.Error()) return err } - registerSnapInfo := new(registrySnapInfoStorage) + registerSnapInfo := new(RegistrySnapInfoStorage) err = json.Unmarshal(bytes, registerSnapInfo) if err != nil { vlog.Errorln("Parse snapshot string error: " + err.Error()) @@ -162,8 +162,8 @@ func (c *DynamicConfigurer) saveSnapshot() { } } -func (c *DynamicConfigurer) getRegistryInfo() *registrySnapInfoStorage { - registrySnapInfo := registrySnapInfoStorage{} +func (c *DynamicConfigurer) getRegistryInfo() *RegistrySnapInfoStorage { + registrySnapInfo := RegistrySnapInfoStorage{} c.regLock.Lock() defer c.regLock.Unlock() diff --git a/filter/rateLimit.go b/filter/rateLimit.go index 85d5ac22..e98692b1 100644 --- a/filter/rateLimit.go +++ b/filter/rateLimit.go @@ -137,20 +137,20 @@ func (r *RateLimitFilter) GetType() int32 { func getKeyValue(key, value, prefix string) (string, float64, bool) { if strings.HasPrefix(key, prefix) { if temp := strings.Split(key, prefix); len(temp) == 2 { - if r, err := strconv.ParseFloat(value, 64); err == nil && temp[1] != "" && r > 0 { + r, err := strconv.ParseFloat(value, 64) + if err == nil && temp[1] != "" && r > 0 { return temp[1], r, true + } + if err != nil { + vlog.Warningf("[rateLimit] parse %s config error:%s", key, err.Error()) } else { - if err != nil { - vlog.Warningf("[rateLimit] parse %s config error:%s", key, err.Error()) - } else { - if r <= 0 { - vlog.Warningf("[rateLimit] parse %s config error: value is 0 or negative", key) - } - } - if temp[1] == "" { - vlog.Warningf("[rateLimit] parse %s config error: key is empty", key) + if r <= 0 { + vlog.Warningf("[rateLimit] parse %s config error: value is 0 or negative", key) } } + if temp[1] == "" { + vlog.Warningf("[rateLimit] parse %s config error: key is empty", key) + } } } return "", 0, false diff --git a/protocol/motanProtocol.go b/protocol/motanProtocol.go index 55dd23ff..2354bf83 100644 --- a/protocol/motanProtocol.go +++ b/protocol/motanProtocol.go @@ -361,6 +361,9 @@ func Decode(buf *bufio.Reader, readSlice *[]byte) (msg *Message, err error) { } func DecodeWithTime(buf *bufio.Reader, rs *[]byte, maxContentLength int) (msg *Message, start time.Time, err error) { + // readSlice is a slice used by reading header info from buf + // in order to reuse this slice, parameter rs is a slice pointer, so that + // the extension of *rs would also affect the slice outside readSlice := *rs // decode header _, err = io.ReadAtLeast(buf, readSlice[:HeaderLength], HeaderLength) @@ -373,6 +376,7 @@ func DecodeWithTime(buf *bufio.Reader, rs *[]byte, maxContentLength int) (msg *M vlog.Errorf("wrong magic num:%d, err:%v", mn, err) return nil, start, ErrMagicNum } + // get a message from pool msg = messagePool.Get().(*Message) msg.Header.Magic = MotanMagic msg.Header.MsgType = readSlice[2] @@ -388,13 +392,13 @@ func DecodeWithTime(buf *bufio.Reader, rs *[]byte, maxContentLength int) (msg *M // decode meta _, err = io.ReadAtLeast(buf, readSlice[:4], 4) if err != nil { - PutMessageBackToPool(msg) + ReleaseMessage(msg) return nil, start, err } metasize := int(binary.BigEndian.Uint32(readSlice[:4])) if metasize > maxContentLength { vlog.Errorf("meta over size. meta size:%d, max size:%d", metasize, maxContentLength) - PutMessageBackToPool(msg) + ReleaseMessage(msg) return nil, start, ErrOverSize } if metasize > 0 { @@ -404,7 +408,7 @@ func DecodeWithTime(buf *bufio.Reader, rs *[]byte, maxContentLength int) (msg *M } err := readBytes(buf, readSlice, metasize) if err != nil { - PutMessageBackToPool(msg) + ReleaseMessage(msg) return nil, start, err } s, e := 0, 0 @@ -423,7 +427,7 @@ func DecodeWithTime(buf *bufio.Reader, rs *[]byte, maxContentLength int) (msg *M } if k != "" { vlog.Errorf("decode message fail, metadata not paired. header:%v, meta:%s", msg.Header, readSlice) - PutMessageBackToPool(msg) + ReleaseMessage(msg) return nil, start, ErrMetadata } } @@ -431,13 +435,13 @@ func DecodeWithTime(buf *bufio.Reader, rs *[]byte, maxContentLength int) (msg *M //decode body _, err = io.ReadAtLeast(buf, readSlice[:4], 4) if err != nil { - PutMessageBackToPool(msg) + ReleaseMessage(msg) return nil, start, err } bodysize := int(binary.BigEndian.Uint32(readSlice[:4])) if bodysize > maxContentLength { vlog.Errorf("body over size. body size:%d, max size:%d", bodysize, maxContentLength) - PutMessageBackToPool(msg) + ReleaseMessage(msg) return nil, start, ErrOverSize } @@ -451,7 +455,7 @@ func DecodeWithTime(buf *bufio.Reader, rs *[]byte, maxContentLength int) (msg *M msg.Body = make([]byte, 0) } if err != nil { - PutMessageBackToPool(msg) + ReleaseMessage(msg) return nil, start, err } return msg, start, err @@ -589,7 +593,7 @@ func ConvertToRequest(request *Message, serialize motan.Serialization) (motan.Re request.Header.SetGzip(false) } if !rc.Proxy && serialize == nil { - motan.PutMotanRequestBackPool(motanRequest) + motan.ReleaseMotanRequest(motanRequest) return nil, ErrSerializeNil } if len(motanRequest.Arguments) <= 0 { @@ -704,13 +708,13 @@ func ConvertToResMessage(response motan.Response, serialize motan.Serialization) res.Body = b } else { vlog.Warningf("convert response value fail! serialized value not []byte. res:%+v", response) - PutMessageBackToPool(res) + ReleaseMessage(res) return nil, ErrSerializedData } } else { b, err := serialize.Serialize(response.GetValue()) if err != nil { - PutMessageBackToPool(res) + ReleaseMessage(res) return nil, err } res.Body = b @@ -745,7 +749,7 @@ func ConvertToResponse(response *Message, serialize motan.Serialization) (motan. response.Header.SetGzip(false) } if !rc.Proxy && serialize == nil { - motan.PutMotanResponseBackPool(mres) + motan.ReleaseMotanResponse(mres) return nil, ErrSerializeNil } dv := &motan.DeserializableValue{Body: response.Body, Serialization: serialize} @@ -757,7 +761,7 @@ func ConvertToResponse(response *Message, serialize motan.Serialization) (motan. var exception *motan.Exception err := json.Unmarshal([]byte(e), &exception) if err != nil { - motan.PutMotanResponseBackPool(mres) + motan.ReleaseMotanResponse(mres) return nil, err } mres.Exception = exception @@ -781,7 +785,7 @@ func ExceptionToJSON(e *motan.Exception) string { return string(errmsg) } -func PutMessageBackToPool(msg *Message) { +func ReleaseMessage(msg *Message) { if msg != nil { //msg.Reset() msg.Type = 0 diff --git a/protocol/motanProtocol_test.go b/protocol/motanProtocol_test.go index acc41513..8a11f20a 100644 --- a/protocol/motanProtocol_test.go +++ b/protocol/motanProtocol_test.go @@ -221,7 +221,7 @@ func TestPool(t *testing.T) { assertTrue(cap(readSlice) > 200, "readSlice", t) assertTrue(len(newMsg.Body) == len(msg.Body), "body", t) assert.Nil(t, err) - PutMessageBackToPool(newMsg) + ReleaseMessage(newMsg) body1 := []byte("testbody") msg1 := &Message{Header: h, Metadata: meta, Body: body1} ebytes1 := msg1.Encode() @@ -277,7 +277,7 @@ func TestConvertToResponse(t *testing.T) { assertTrue(resp.GetAttachment(MPath) == "path", "response path", t) //assertTrue(resp.GetValue().(string) == "testbody", "response body", t) pMap[fmt.Sprintf("%p", resp)] = "1" - core.PutMotanResponseBackPool(resp.(*core.MotanResponse)) + core.ReleaseMotanResponse(resp.(*core.MotanResponse)) } assert.True(t, len(pMap) < 10000) } @@ -310,7 +310,7 @@ func TestConvertToRequest(t *testing.T) { assertTrue(req.GetAttachment(MMethod) == "method", "request method", t) assertTrue(req.GetAttachment(MPath) == "path", "request path", t) pMap[fmt.Sprintf("%p", req)] = "1" - core.PutMotanRequestBackPool(req.(*core.MotanRequest)) + core.ReleaseMotanRequest(req.(*core.MotanRequest)) } assert.True(t, len(pMap) < 10000) diff --git a/server/motanserver.go b/server/motanserver.go index 0de21f06..c038eaec 100644 --- a/server/motanserver.go +++ b/server/motanserver.go @@ -271,14 +271,14 @@ func (m *MotanServer) processV2(msg *mpro.Message, start time.Time, ip string, c tc.PutResSpan(&motan.Span{Name: motan.Send, Time: resSendTime}) } // 回收message - mpro.PutMessageBackToPool(msg) - mpro.PutMessageBackToPool(res) + mpro.ReleaseMessage(msg) + mpro.ReleaseMessage(res) // 回收request if motanReq, ok := mreq.(*motan.MotanRequest); ok { - motan.PutMotanRequestBackPool(motanReq) + motan.ReleaseMotanRequest(motanReq) } if motanResp, ok := mres.(*motan.MotanResponse); ok { - motan.PutMotanResponseBackPool(motanResp) + motan.ReleaseMotanResponse(motanResp) } }