Skip to content

Commit

Permalink
liangwei beautify code (#354)
Browse files Browse the repository at this point in the history
* code beautify
  • Loading branch information
Hoofffman authored Dec 8, 2023
1 parent 4738ce5 commit 86bd259
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 41 deletions.
8 changes: 3 additions & 5 deletions agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down Expand Up @@ -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
Expand All @@ -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
}

Expand Down Expand Up @@ -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)
}
4 changes: 2 additions & 2 deletions core/motan.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions dynamicConfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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()
Expand Down
20 changes: 10 additions & 10 deletions filter/rateLimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 17 additions & 13 deletions protocol/motanProtocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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]
Expand All @@ -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 {
Expand All @@ -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
Expand All @@ -423,21 +427,21 @@ 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
}
}

//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
}

Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}
Expand All @@ -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
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions protocol/motanProtocol_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)

Expand Down
8 changes: 4 additions & 4 deletions server/motanserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down

0 comments on commit 86bd259

Please sign in to comment.