Skip to content

Commit 2c75ecd

Browse files
authored
Merge pull request #39 from dadav/fix_bubbleup
fix: Make stats work
2 parents 3af3e6e + f8a2e2c commit 2c75ecd

File tree

5 files changed

+44
-38
lines changed

5 files changed

+44
-38
lines changed

cmd/serve.go

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ import (
4040
backend "github.com/dadav/gorge/internal/v3/backend"
4141
"github.com/dadav/gorge/internal/v3/ui"
4242
openapi "github.com/dadav/gorge/pkg/gen/v3/openapi"
43+
"github.com/dadav/stampede"
4344
"github.com/go-chi/chi/v5"
4445
"github.com/go-chi/chi/v5/middleware"
4546
"github.com/go-chi/cors"
46-
"github.com/go-chi/stampede"
4747
"github.com/spf13/cobra"
4848
"golang.org/x/sync/errgroup"
4949
)
@@ -125,6 +125,16 @@ You can also enable the caching functionality to speed things up.`,
125125
userService := v3.NewUserOperationsApi()
126126

127127
r := chi.NewRouter()
128+
129+
// 0. Inject statistic middleware
130+
x := customMiddleware.NewStatistics()
131+
r.Use(func(next http.Handler) http.Handler {
132+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
133+
ctx := context.WithValue(r.Context(), "stats", x)
134+
next.ServeHTTP(w, r.WithContext(ctx))
135+
})
136+
})
137+
128138
// 1. Recoverer should be first to catch panics in all other middleware
129139
r.Use(middleware.Recoverer)
130140
// 2. RealIP should be early to ensure all other middleware sees the correct IP
@@ -140,8 +150,6 @@ You can also enable the caching functionality to speed things up.`,
140150
// 4. RequireUserAgent should be early to ensure all other middleware sees the correct user agent
141151
r.Use(customMiddleware.RequireUserAgent)
142152

143-
x := customMiddleware.NewStatistics()
144-
145153
if config.UI {
146154
r.Group(func(r chi.Router) {
147155
r.HandleFunc("/", ui.IndexHandler)
@@ -168,10 +176,28 @@ You can also enable the caching functionality to speed things up.`,
168176
return stampede.StringToHash(r.Method, requestURI, strings.ToLower(token))
169177
}
170178

171-
cachedMiddleware := stampede.HandlerWithKey(
179+
cbFunc := func(fromCache bool, w http.ResponseWriter, r *http.Request) error {
180+
x.Mutex.Lock()
181+
if fromCache {
182+
log.Log.Debugf("Cache hit for path: %s", r.URL.Path)
183+
x.TotalCacheHits++
184+
x.CacheHitsPerEndpoint[r.URL.Path]++
185+
w.Header().Set("X-Cache", "Hit from gorge")
186+
} else {
187+
log.Log.Debugf("Cache miss for path: %s", r.URL.Path)
188+
x.TotalCacheMisses++
189+
x.CacheMissesPerEndpoint[r.URL.Path]++
190+
w.Header().Set("X-Cache", "MISS from gorge")
191+
}
192+
x.Mutex.Unlock()
193+
return nil
194+
}
195+
196+
cachedMiddleware := stampede.HandlerWithKeyAndCb(
172197
512,
173198
time.Duration(config.CacheMaxAge)*time.Second,
174199
customKeyFunc,
200+
cbFunc,
175201
)
176202
log.Log.Debugf("Cache middleware configured with prefixes: %s", config.CachePrefixes)
177203

@@ -188,21 +214,7 @@ You can also enable the caching functionality to speed things up.`,
188214
}
189215

190216
if shouldCache {
191-
wrapper := customMiddleware.NewResponseWrapper(w)
192-
// Set default cache status before serving
193-
// w.Header().Set("X-Cache", "MISS from gorge")
194-
195-
cachedMiddleware(next).ServeHTTP(wrapper, r)
196-
197-
// Only override if it was served from cache
198-
// TODO: this is not working as expected
199-
if wrapper.WasWritten() {
200-
log.Log.Debugf("Serving cached response for path: %s", r.URL.Path)
201-
w.Header().Set("X-Cache", "HIT from gorge")
202-
} else {
203-
log.Log.Debugf("Cache miss for path: %s", r.URL.Path)
204-
w.Header().Set("X-Cache", "MISS from gorge")
205-
}
217+
cachedMiddleware(next).ServeHTTP(w, r)
206218
} else {
207219
next.ServeHTTP(w, r)
208220
}

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ go 1.22.0
44

55
require (
66
github.com/a-h/templ v0.2.793
7+
github.com/dadav/stampede v0.0.0-20241228173147-dd16def44490
78
github.com/go-chi/chi/v5 v5.2.0
89
github.com/go-chi/cors v1.2.1
910
github.com/go-chi/jwtauth/v5 v5.3.2
10-
github.com/go-chi/stampede v0.6.0
1111
github.com/hashicorp/go-version v1.7.0
1212
github.com/mitchellh/go-homedir v1.1.0
1313
github.com/spf13/cobra v1.8.1

go.sum

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,12 @@ github.com/a-h/templ v0.2.793/go.mod h1:lq48JXoUvuQrU0VThrK31yFwdRjTCnIE5bcPCM9I
33
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
44
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
55
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
6+
github.com/dadav/stampede v0.0.0-20241228165756-61568b6ca93b h1:t22u27sjssQ2146msFpZXX47oRgtiHDdudc4zCwwyPU=
7+
github.com/dadav/stampede v0.0.0-20241228165756-61568b6ca93b/go.mod h1:O/5HgfMaQjv+J8LZCVmaKdE1cD7JsUhwnCuK5BnU0XI=
8+
github.com/dadav/stampede v0.0.0-20241228171116-ae01e8a04d08 h1:TUK02XGb2f5GgZ5PTNFWgRr+gGSEiwhijvR/pVwSz98=
9+
github.com/dadav/stampede v0.0.0-20241228171116-ae01e8a04d08/go.mod h1:O/5HgfMaQjv+J8LZCVmaKdE1cD7JsUhwnCuK5BnU0XI=
10+
github.com/dadav/stampede v0.0.0-20241228173147-dd16def44490 h1:uSaqpXtJE+DofLTUebe7+3bxm5YVrVL8rqIDV+fpRh4=
11+
github.com/dadav/stampede v0.0.0-20241228173147-dd16def44490/go.mod h1:O/5HgfMaQjv+J8LZCVmaKdE1cD7JsUhwnCuK5BnU0XI=
612
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
713
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
814
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
@@ -19,8 +25,6 @@ github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
1925
github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
2026
github.com/go-chi/jwtauth/v5 v5.3.2 h1:s+ON3ATyyMs3Me0kqyuua6Rwu+2zqIIkL0GCaMarwvs=
2127
github.com/go-chi/jwtauth/v5 v5.3.2/go.mod h1:O4QvPRuZLZghl9WvfVaON+ARfGzpD2PBX/QY5vUz7aQ=
22-
github.com/go-chi/stampede v0.6.0 h1:9YXCHtnePdj02neMOHysC93WAi3ZXZA8SygCmooNE6o=
23-
github.com/go-chi/stampede v0.6.0/go.mod h1:9sHbrc5N9uMJHMjw33pBvV8sGtyK3GQdn0lH5bOgjLA=
2428
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
2529
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
2630
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=

internal/middleware/proxy.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ func NewSingleHostReverseProxy(target *url.URL) *httputil.ReverseProxy {
4949
func ProxyFallback(upstreamHost string, forwardToProxy func(int) bool, proxiedResponseCb func(*http.Response)) func(next http.Handler) http.Handler {
5050
return func(next http.Handler) http.Handler {
5151
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
52-
5352
// Store original headers before any modifications
5453
originalHeaders := make(http.Header)
5554
for k, v := range w.Header() {
@@ -93,6 +92,12 @@ func ProxyFallback(upstreamHost string, forwardToProxy func(int) bool, proxiedRe
9392
capturedResponseWriter.sendCapturedResponse()
9493
}
9594

95+
stats := r.Context().Value("stats").(*Statistics)
96+
stats.Mutex.Lock()
97+
stats.ProxiedConnections++
98+
stats.ProxiedConnectionsPerEndpoint[r.URL.Path]++
99+
stats.Mutex.Unlock()
100+
96101
proxy.ServeHTTP(w, r)
97102
return
98103
}

internal/middleware/stats.go

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -52,23 +52,8 @@ func StatisticsMiddleware(stats *Statistics) func(next http.Handler) http.Handle
5252
duration := time.Since(start)
5353
stats.Mutex.Lock()
5454
stats.ActiveConnections--
55-
56-
if w.Header().Get("X-Cache") == "HIT from gorge" {
57-
stats.TotalCacheHits++
58-
stats.CacheHitsPerEndpoint[r.URL.Path]++
59-
} else {
60-
stats.TotalCacheMisses++
61-
stats.CacheMissesPerEndpoint[r.URL.Path]++
62-
}
63-
6455
stats.TotalResponseTime += duration
6556
stats.ResponseTimePerEndpoint[r.URL.Path] += duration
66-
67-
if w.Header().Get("X-Proxied-To") != "" {
68-
stats.ProxiedConnections++
69-
stats.ProxiedConnectionsPerEndpoint[r.URL.Path]++
70-
}
71-
7257
stats.Mutex.Unlock()
7358
}()
7459

0 commit comments

Comments
 (0)