Skip to content

Commit

Permalink
Feat/improve mqtt response time miliseconds (#30)
Browse files Browse the repository at this point in the history
* add realip tag to the middleware

* add caller to middleware

* add metricTagMap on handlers

* removes unecessary validation

* Updates to safe type assertion

Co-authored-by: Sonia Melgaço <hello@bitbanshee.dev>

* adds validation to the messages slice before putting it into a tag

* updates code style

* fix type conversion

* fix gameid type

Co-authored-by: Sonia Melgaço <hello@bitbanshee.dev>
  • Loading branch information
mflilian and bitbanshee authored Sep 29, 2022
1 parent cfe4ff8 commit fc660b2
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 5 deletions.
8 changes: 8 additions & 0 deletions app/histories_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ func HistoriesV2Handler(app *App) func(c echo.Context) error {
topicMessages := mongoclient.GetMessagesV2(c, topic, from, limit, collection)
messages = append(messages, topicMessages...)
}

if len(messages) > 0 {
gameId := messages[0].GameId
if metricTagsMap, ok := c.Get("metricTagsMap").(map[string]interface{}); ok {
metricTagsMap["gameID"] = gameId
}
}

return c.JSON(http.StatusOK, messages)
}
}
7 changes: 7 additions & 0 deletions app/history_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ func HistoryV2Handler(app *App) func(c echo.Context) error {
collection := app.Defaults.MongoMessagesCollection
messages = mongoclient.GetMessagesV2WithParameter(c, topic, from, limit, collection, isBlocked)

if len(messages) > 0 {
gameId := messages[0].GameId
if metricTagsMap, ok := c.Get("metricTagsMap").(map[string]interface{}); ok {
metricTagsMap["gameID"] = gameId
}
}

return c.JSON(http.StatusOK, messages)
}
}
61 changes: 56 additions & 5 deletions app/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/labstack/echo/engine"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/log"
"github.com/topfreegames/extensions/middleware"
"github.com/topfreegames/mqtt-history/logger"
"github.com/uber-go/zap"
)
Expand Down Expand Up @@ -68,8 +69,8 @@ func (l LoggerMiddleware) Serve(next echo.HandlerFunc) echo.HandlerFunc {
zap.String("source", "request"),
)

//all except latency to string
var ip, method, path string
// all except latency to string
var ip, method, path, gameID string
var status int
var latency time.Duration
var startTime, endTime time.Time
Expand All @@ -79,9 +80,16 @@ func (l LoggerMiddleware) Serve(next echo.HandlerFunc) echo.HandlerFunc {

startTime = time.Now()

metricTagsMap := make(map[string]interface{})
c.Set("metricTagsMap", metricTagsMap)

result := next(c)

//no time.Since in order to format it well after
if metricTagsMap, ok := c.Get("metricTagsMap").(map[string]interface{}); ok {
gameID, _ = metricTagsMap["gameID"].(string)
}

// no time.Since in order to format it well after
endTime = time.Now()
latency = endTime.Sub(startTime)

Expand All @@ -102,6 +110,7 @@ func (l LoggerMiddleware) Serve(next echo.HandlerFunc) echo.HandlerFunc {
zap.String("ip", ip),
zap.String("method", method),
zap.String("path", path),
zap.String("gameID", gameID),
)

//request failed
Expand All @@ -118,6 +127,7 @@ func (l LoggerMiddleware) Serve(next echo.HandlerFunc) echo.HandlerFunc {
//Everything went ok
reqLog.Info("Request successful.")
return result

}
}

Expand Down Expand Up @@ -180,11 +190,53 @@ func (nr *NewRelicMiddleware) Serve(next echo.HandlerFunc) echo.HandlerFunc {
txn.NoticeError(err)
return err
}

return nil
}
}

const metricName = "response_time_milliseconds"

// ResponseTimeMetricsMiddleware struct encapsulating DDStatsD
type ResponseTimeMetricsMiddleware struct {
DDStatsD *middleware.DogStatsD
}

// ResponseTimeMetricsMiddleware is a middleware to measure the response time
// of a route and send it do StatsD
func (responseTimeMiddleware ResponseTimeMetricsMiddleware) Serve(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {

startTime := time.Now()
result := next(c)
status := c.Response().Status()
route := c.Path()
method := c.Request().Method()

var gameID string
if metricTagsMap, ok := c.Get("metricTagsMap").(map[string]interface{}); ok {
gameID, _ = metricTagsMap["gameID"].(string)
}

timeUsed := time.Since(startTime)

tags := []string{
fmt.Sprintf("route:%s", route),
fmt.Sprintf("method:%s", method),
fmt.Sprintf("status:%d", status),
fmt.Sprintf("gameID:%v", gameID),
}
responseTimeMiddleware.DDStatsD.Timing(metricName, timeUsed, tags...)
return result
}
}

// ResponseTimeMetricsMiddleware returns a new ResponseTimeMetricsMiddleware
func NewResponseTimeMetricsMiddleware(ddStatsD *middleware.DogStatsD) *ResponseTimeMetricsMiddleware {
return &ResponseTimeMetricsMiddleware{
DDStatsD: ddStatsD,
}
}

// NewJaegerMiddleware create a new middleware to instrument traces.
func NewJaegerMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
Expand Down Expand Up @@ -245,7 +297,6 @@ func NewJaegerMiddleware() echo.MiddlewareFunc {
response := c.Response()
statusCode := response.Status()
span.SetTag("http.status_code", statusCode)

return err
}
}
Expand Down

0 comments on commit fc660b2

Please sign in to comment.