Compare commits

...
1 Commits
Author SHA1 Message Date
lukaszraczylo 8c5f229bbd fix(cache): honour X-Skip-Cache and Cache-Control no-cache
Clients sent X-Skip-Cache: true or Cache-Control: no-cache on reads
that gate money and quotas, but the proxy ignored both and answered
from its cache for up to CACHE_TTL seconds. A quota or overage setting
change therefore took effect late.

A request with either header now goes to the backend, is not stored
and does not join an identical request in flight.
2026-11-18 02:40:46 +00:00
4 changed files with 108 additions and 2 deletions
+2
View File
@@ -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:
+3 -1
View File
@@ -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
+14 -1
View File
@@ -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)
+89
View File
@@ -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")
}
})
}
}