-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathmetric_middleware.go
More file actions
70 lines (58 loc) · 1.58 KB
/
metric_middleware.go
File metadata and controls
70 lines (58 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package api
import (
"bytes"
"io"
"strings"
"github.com/gin-gonic/gin"
"github.com/taosdata/taoskeeper/infrastructure/log"
)
const maxRequestBodySize = 1 << 20 // 1MB - maximum request body size for metric endpoints
var middlewareLogger = log.GetLogger("METRIC_MIDDLEWARE")
// MetricCacheMiddleware AOP middleware (synchronous version)
func MetricCacheMiddleware(parser *MetricParser) gin.HandlerFunc {
return func(c *gin.Context) {
// Fast path 1: non-POST request
if c.Request.Method != "POST" {
c.Next()
return
}
// Fast path 2: path not matched
path := c.Request.URL.Path
if !shouldCachePath(path) {
c.Next()
return
}
// Limit request body size to prevent DoS attacks
limitedReader := io.LimitReader(c.Request.Body, maxRequestBodySize)
body, err := io.ReadAll(limitedReader)
if err != nil {
c.Next()
return
}
// Check if body was truncated (exceeded max size)
if len(body) == maxRequestBodySize {
middlewareLogger.Warn("Request body exceeded 1MB limit, may have been truncated")
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
// Synchronous parsing (~5µs only, negligible latency)
if err := parser.ParseAndStore(c, body); err != nil {
middlewareLogger.Debugf("Failed to parse metrics: %v", err)
}
c.Next()
}
}
// shouldCachePath matches paths
var cachePaths = []string{
"/general-metric",
"/taosd-cluster-basic",
"/slow-sql-detail-batch",
"/adapter_report",
}
func shouldCachePath(path string) bool {
for _, prefix := range cachePaths {
if strings.HasPrefix(path, prefix) {
return true
}
}
return false
}