-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add StatMiddleware for chi router (#14)
- Loading branch information
Showing
4 changed files
with
137 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
package chiware | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"net/http" | ||
"strconv" | ||
"sync/atomic" | ||
"time" | ||
|
||
"github.com/go-chi/chi/v5" | ||
"github.com/rudderlabs/rudder-go-kit/stats" | ||
) | ||
|
||
func StatMiddleware(ctx context.Context, router chi.Router, s stats.Stats, component string) func(http.Handler) http.Handler { | ||
var concurrentRequests int32 | ||
activeClientCount := s.NewStat(fmt.Sprintf("%s.concurrent_requests_count", component), stats.GaugeType) | ||
go func() { | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
return | ||
case <-time.After(10 * time.Second): | ||
activeClientCount.Gauge(atomic.LoadInt32(&concurrentRequests)) | ||
} | ||
} | ||
}() | ||
|
||
// getPath retrieves the path from the request. | ||
// The matched route's template is used if a match is found, | ||
// otherwise the request's URL path is used instead. | ||
getPath := func(r *http.Request) string { | ||
if path := chi.RouteContext(r.Context()).RoutePattern(); path != "" { | ||
return path | ||
} | ||
return r.URL.Path | ||
} | ||
return func(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
sw := newStatusCapturingWriter(w) | ||
start := time.Now() | ||
atomic.AddInt32(&concurrentRequests, 1) | ||
defer atomic.AddInt32(&concurrentRequests, -1) | ||
|
||
next.ServeHTTP(sw, r) | ||
|
||
s.NewSampledTaggedStat( | ||
fmt.Sprintf("%s.response_time", component), | ||
stats.TimerType, | ||
map[string]string{ | ||
"reqType": getPath(r), | ||
"method": r.Method, | ||
"code": strconv.Itoa(sw.status), | ||
}).Since(start) | ||
}) | ||
} | ||
} | ||
|
||
// newStatusCapturingWriter returns a new, properly initialized statusCapturingWriter | ||
func newStatusCapturingWriter(w http.ResponseWriter) *statusCapturingWriter { | ||
return &statusCapturingWriter{ | ||
ResponseWriter: w, | ||
status: http.StatusOK, | ||
} | ||
} | ||
|
||
// statusCapturingWriter is a response writer decorator that captures the status code. | ||
type statusCapturingWriter struct { | ||
http.ResponseWriter | ||
status int | ||
} | ||
|
||
// WriteHeader override the http.ResponseWriter's `WriteHeader` method | ||
func (w *statusCapturingWriter) WriteHeader(status int) { | ||
w.status = status | ||
w.ResponseWriter.WriteHeader(status) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package chiware_test | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"net/http" | ||
"net/http/httptest" | ||
"strconv" | ||
"testing" | ||
|
||
"github.com/go-chi/chi/v5" | ||
"github.com/golang/mock/gomock" | ||
"github.com/rudderlabs/rudder-go-kit/chiware" | ||
"github.com/rudderlabs/rudder-go-kit/stats" | ||
"github.com/rudderlabs/rudder-go-kit/stats/mock_stats" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestStatsMiddleware(t *testing.T) { | ||
component := "test" | ||
testCase := func(expectedStatusCode int, pathTemplate, requestPath, expectedMethod string) func(t *testing.T) { | ||
return func(t *testing.T) { | ||
ctrl := gomock.NewController(t) | ||
mockStats := mock_stats.NewMockStats(ctrl) | ||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
w.WriteHeader(expectedStatusCode) | ||
}) | ||
|
||
measurement := mock_stats.NewMockMeasurement(ctrl) | ||
mockStats.EXPECT().NewStat(fmt.Sprintf("%s.concurrent_requests_count", component), stats.GaugeType).Return(measurement).Times(1) | ||
mockStats.EXPECT().NewSampledTaggedStat(fmt.Sprintf("%s.response_time", component), stats.TimerType, | ||
map[string]string{ | ||
"reqType": pathTemplate, | ||
"method": expectedMethod, | ||
"code": strconv.Itoa(expectedStatusCode), | ||
}).Return(measurement).Times(1) | ||
measurement.EXPECT().Since(gomock.Any()).Times(1) | ||
|
||
ctx, cancel := context.WithCancel(context.Background()) | ||
defer cancel() | ||
router := chi.NewRouter() | ||
router.Use( | ||
chiware.StatMiddleware(ctx, router, mockStats, component), | ||
) | ||
router.MethodFunc(expectedMethod, pathTemplate, handler) | ||
|
||
response := httptest.NewRecorder() | ||
request := httptest.NewRequest("GET", "http://example.com"+requestPath, http.NoBody) | ||
router.ServeHTTP(response, request) | ||
require.Equal(t, expectedStatusCode, response.Code) | ||
} | ||
} | ||
|
||
t.Run("template with param in path", testCase(http.StatusNotFound, "/v1/{param}", "/v1/abc", "GET")) | ||
|
||
t.Run("template without param in path", testCase(http.StatusNotFound, "/v1/some-other/key", "/v1/some-other/key", "GET")) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters