mirror of
https://github.com/lukaszraczylo/graphql-monitoring-proxy.git
synced 2026-11-18 10:35:23 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c5f229bbd | ||
|
|
e5b47fc568 |
@@ -434,6 +434,8 @@ query MyProducts @cached(refresh: true) {
|
||||
}
|
||||
```
|
||||
|
||||
To skip the cache for one request, send `X-Skip-Cache: true` or `Cache-Control: no-cache` (or `no-store`). The proxy then sends the request to the backend, does not store the response and does not merge it with an identical request in flight. Use it for reads that gate money, quotas or permissions.
|
||||
|
||||
#### Memory-Aware Caching
|
||||
|
||||
Starting with version `0.26.0`, the memory cache implementation has been enhanced with memory-aware features to prevent out-of-memory situations:
|
||||
|
||||
@@ -5,12 +5,12 @@ go 1.26.0
|
||||
toolchain go1.27.4
|
||||
|
||||
require (
|
||||
github.com/MicahParks/keyfunc/v3 v3.9.1
|
||||
github.com/MicahParks/keyfunc/v3 v3.9.2
|
||||
github.com/VictoriaMetrics/metrics v1.45.0
|
||||
github.com/alicebob/miniredis/v2 v2.40.0
|
||||
github.com/avast/retry-go/v5 v5.1.1
|
||||
github.com/goccy/go-json v0.12.0
|
||||
github.com/gofiber/contrib/v3/websocket v1.2.13
|
||||
github.com/gofiber/contrib/v3/websocket v1.2.14
|
||||
github.com/gofiber/fiber/v3 v3.7.0
|
||||
github.com/gofrs/flock v0.13.2
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
github.com/MicahParks/jwkset v0.11.4 h1:sm6pqlEpa1YDu82Hoxho/O+Y291lPcksNImVIsV74gg=
|
||||
github.com/MicahParks/jwkset v0.11.4/go.mod h1:U2oRhRaLgDCLjtpGL2GseNKGmZtLs/3O7p+OZaL5vo0=
|
||||
github.com/MicahParks/keyfunc/v3 v3.9.1 h1:10dlh2kS3kRtfj5x2bokCxLhTpmIpf3WtsvBdJ2TfOo=
|
||||
github.com/MicahParks/keyfunc/v3 v3.9.1/go.mod h1:h8DMhdulFa3yjG1q74FqaehNDekB18HrVCXPl9Raa4I=
|
||||
github.com/MicahParks/keyfunc/v3 v3.9.2 h1:yWvqmCIWMnyp8tJFR3VmNQRBGmNRJ3cMvN9bcG9Bfbc=
|
||||
github.com/MicahParks/keyfunc/v3 v3.9.2/go.mod h1:h8DMhdulFa3yjG1q74FqaehNDekB18HrVCXPl9Raa4I=
|
||||
github.com/VictoriaMetrics/metrics v1.45.0 h1:Tv8dZRAjkO90rBTxYrWOHUWFBHsAKdKcZYmS/Wbo2EU=
|
||||
github.com/VictoriaMetrics/metrics v1.45.0/go.mod h1:xDM82ULLYCYdFRgQ2JBxi8Uf1+8En1So9YUwlGTOqTc=
|
||||
github.com/alicebob/miniredis/v2 v2.40.0 h1:6IgTQbvm2JiMYZ8yur/acNJzVjtSOWCelxXbk/LUBXc=
|
||||
@@ -32,8 +32,8 @@ github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI=
|
||||
github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY=
|
||||
github.com/goccy/go-reflect v1.2.0 h1:O0T8rZCuNmGXewnATuKYnkL0xm6o8UNOJZd/gOkb9ms=
|
||||
github.com/goccy/go-reflect v1.2.0/go.mod h1:n0oYZn8VcV2CkWTxi8B9QjkCoq6GTtCEdfmR66YhFtE=
|
||||
github.com/gofiber/contrib/v3/websocket v1.2.13 h1:JaxaFpNn4ca/kv5EXmIpnFlhyN9syUqbXKIUN4hjf/Q=
|
||||
github.com/gofiber/contrib/v3/websocket v1.2.13/go.mod h1:tOI7AiJKlz9XbGw7BLv8tAkwikdNOkoNWZ7lMPOLokc=
|
||||
github.com/gofiber/contrib/v3/websocket v1.2.14 h1:/wlTsd8u2iRrNbKpQUfi+9/ZxKUhhNBXCLUpav/7ggw=
|
||||
github.com/gofiber/contrib/v3/websocket v1.2.14/go.mod h1:jchCghyb5+Tly28QOYw/123u55pwP5uLbwhetl4Npfw=
|
||||
github.com/gofiber/fiber/v3 v3.7.0 h1:aF+GfB7nP9Dd0wVsv6wmr8675v66OGfjSyoDhPmvKEo=
|
||||
github.com/gofiber/fiber/v3 v3.7.0/go.mod h1:7dlbpUZ789TJg4q/VfdS1UWDtB6Fl/Smk6ZYZusMpAQ=
|
||||
github.com/gofiber/schema v1.9.4 h1:IVNXN2WyVHmUn/S186e/rdnGlb1LFrhZ1hjndTYvn8w=
|
||||
|
||||
@@ -726,7 +726,9 @@ func performProxyRequest(c fiber.Ctx, proxyURL string) error {
|
||||
|
||||
// Check if request coalescing is enabled
|
||||
rc := GetRequestCoalescer()
|
||||
if rc != nil && cfg.RequestCoalescing.Enable {
|
||||
// A cache-bypass read must not join an identical request already in flight:
|
||||
// that one may have started before the write the caller needs to see.
|
||||
if rc != nil && cfg.RequestCoalescing.Enable && !skipCacheRequested(c) {
|
||||
// Use request coalescing to deduplicate identical concurrent requests
|
||||
response, err := rc.Do(cacheKey, func() (*CoalescedResponse, error) {
|
||||
// Execute the actual proxy request
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -474,6 +475,18 @@ func extractUserInfoFromHeaders(get func(string) string) (string, string, error)
|
||||
return extractedUserID, extractedRoleName, nil
|
||||
}
|
||||
|
||||
// skipCacheRequested reports whether the client asked to bypass the response
|
||||
// cache, with the same headers the upstream engine honours: X-Skip-Cache: true,
|
||||
// or Cache-Control no-cache / no-store. Callers send them on reads that gate
|
||||
// money, quotas or permissions, which must not be served stale.
|
||||
func skipCacheRequested(c fiber.Ctx) bool {
|
||||
if strings.EqualFold(c.Get("X-Skip-Cache"), "true") {
|
||||
return true
|
||||
}
|
||||
cc := strings.ToLower(c.Get(fiber.HeaderCacheControl))
|
||||
return strings.Contains(cc, "no-cache") || strings.Contains(cc, "no-store")
|
||||
}
|
||||
|
||||
// handleCaching manages the caching logic for GraphQL requests
|
||||
func handleCaching(c fiber.Ctx, parsedResult *parseGraphQLQueryResult, userID, userRole string) (bool, error) {
|
||||
// Calculate query hash for cache key - now includes user context for security
|
||||
@@ -499,7 +512,7 @@ func handleCaching(c fiber.Ctx, parsedResult *parseGraphQLQueryResult, userID, u
|
||||
|
||||
// Check if caching is enabled
|
||||
cacheEnabled := parsedResult.cacheRequest || cfg.Cache.CacheEnable || cfg.Cache.CacheRedisEnable
|
||||
if !cacheEnabled {
|
||||
if !cacheEnabled || skipCacheRequested(c) {
|
||||
// No caching, just proxy the request
|
||||
if err := proxyTheRequest(c, parsedResult.activeEndpoint); err != nil {
|
||||
cfg.Monitoring.Increment(libpack_monitoring.MetricsFailed, nil)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -874,3 +875,91 @@ func TestStartHTTPProxy_ErrorHandlerConfigured(t *testing.T) {
|
||||
t.Fatal("StartHTTPProxy did not return after shutdownHTTPProxy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaching_BypassHeadersSkipCache(t *testing.T) {
|
||||
parseConfig()
|
||||
_ = StartMonitoringServer()
|
||||
|
||||
libpack_cache.EnableCache(&libpack_cache.CacheConfig{
|
||||
Logger: cfg.Logger,
|
||||
TTL: 60,
|
||||
})
|
||||
|
||||
cfgMutex.Lock()
|
||||
origEnable := cfg.Cache.CacheEnable
|
||||
cfg.Cache.CacheEnable = true
|
||||
cfg.Cache.CacheTTL = 60
|
||||
cfgMutex.Unlock()
|
||||
defer func() {
|
||||
cfgMutex.Lock()
|
||||
cfg.Cache.CacheEnable = origEnable
|
||||
cfgMutex.Unlock()
|
||||
}()
|
||||
|
||||
var hits atomic.Int32
|
||||
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := hits.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(200)
|
||||
_, _ = fmt.Fprintf(w, `{"data":{"n":%d}}`, n)
|
||||
}))
|
||||
defer backend.Close()
|
||||
|
||||
cfgMutex.Lock()
|
||||
origHost := cfg.Server.HostGraphQL
|
||||
origHostRO := cfg.Server.HostGraphQLReadOnly
|
||||
cfg.Server.HostGraphQL = backend.URL
|
||||
cfg.Server.HostGraphQLReadOnly = backend.URL
|
||||
cfgMutex.Unlock()
|
||||
defer func() {
|
||||
cfgMutex.Lock()
|
||||
cfg.Server.HostGraphQL = origHost
|
||||
cfg.Server.HostGraphQLReadOnly = origHostRO
|
||||
cfgMutex.Unlock()
|
||||
}()
|
||||
|
||||
app := fiber.New()
|
||||
app.Post("/*", processGraphQLRequest)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
header string
|
||||
value string
|
||||
}{
|
||||
{"X-Skip-Cache", "X-Skip-Cache", "true"},
|
||||
{"Cache-Control no-cache", "Cache-Control", "no-cache"},
|
||||
{"Cache-Control no-store", "Cache-Control", "no-store, max-age=0"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
libpack_cache.CacheClear()
|
||||
body := `{"query":"query { n }"}`
|
||||
send := func(header, value string) *http.Response {
|
||||
req := httptest.NewRequest("POST", "/v1/graphql", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if header != "" {
|
||||
req.Header.Set(header, value)
|
||||
}
|
||||
resp, err := app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatalf("request: %v", err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
return resp
|
||||
}
|
||||
|
||||
send("", "") // warm the cache
|
||||
before := hits.Load()
|
||||
resp := send(tt.header, tt.value)
|
||||
if resp.Header.Get("X-Cache-Hit") == "true" {
|
||||
t.Fatal("bypass request was answered from the cache")
|
||||
}
|
||||
if got := hits.Load(); got != before+1 {
|
||||
t.Fatalf("bypass request must reach the backend: hits %d, want %d", got, before+1)
|
||||
}
|
||||
if resp := send("", ""); resp.Header.Get("X-Cache-Hit") != "true" {
|
||||
t.Fatal("plain request after a bypass must still use the cache")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user