github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/plugins/metrics/server.go (about)

     1  package metrics
     2  
     3  import (
     4  	"github.com/nyan233/littlerpc/core/middle/plugin"
     5  	perror "github.com/nyan233/littlerpc/core/protocol/error"
     6  	"github.com/nyan233/littlerpc/core/protocol/message"
     7  	"reflect"
     8  )
     9  
    10  type ServerMetricsPlugin struct {
    11  	plugin.AbstractServer
    12  	Call            *CallMetrics
    13  	UploadTraffic   *TrafficMetrics
    14  	DownloadTraffic *TrafficMetrics
    15  }
    16  
    17  func NewServer() *ServerMetricsPlugin {
    18  	return &ServerMetricsPlugin{
    19  		Call:            new(CallMetrics),
    20  		UploadTraffic:   new(TrafficMetrics),
    21  		DownloadTraffic: new(TrafficMetrics),
    22  	}
    23  }
    24  
    25  func (s *ServerMetricsPlugin) Receive4S(pub *plugin.Context, msg *message.Message) perror.LErrorDesc {
    26  	if msg == nil {
    27  		return nil
    28  	}
    29  	s.Call.IncCount()
    30  	s.UploadTraffic.Add(int64(msg.GetAndSetLength()))
    31  	return nil
    32  }
    33  
    34  func (s *ServerMetricsPlugin) Call4S(pub *plugin.Context, args []reflect.Value, err perror.LErrorDesc) perror.LErrorDesc {
    35  	if err != nil {
    36  		s.Call.IncFailed()
    37  	}
    38  	return nil
    39  }
    40  
    41  func (s *ServerMetricsPlugin) AfterCall4S(pub *plugin.Context, args, results []reflect.Value, err perror.LErrorDesc) perror.LErrorDesc {
    42  	if err != nil {
    43  		s.Call.IncFailed()
    44  	}
    45  	return nil
    46  }
    47  
    48  func (s *ServerMetricsPlugin) AfterSend4S(pub *plugin.Context, msg *message.Message, err perror.LErrorDesc) perror.LErrorDesc {
    49  	if err != nil {
    50  		s.Call.IncFailed()
    51  		return nil
    52  	}
    53  	s.Call.IncComplete()
    54  	s.DownloadTraffic.Add(int64(msg.GetAndSetLength()))
    55  	return nil
    56  }