diff --git a/README.md b/README.md index 3f7de5a..0cc26a3 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/proxy.go b/proxy.go index 79a286b..4a699f2 100644 --- a/proxy.go +++ b/proxy.go @@ -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 diff --git a/server.go b/server.go index 69d3707..357ca49 100644 --- a/server.go +++ b/server.go @@ -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) diff --git a/server_handlers_test.go b/server_handlers_test.go index c55937a..38dda06 100644 --- a/server_handlers_test.go +++ b/server_handlers_test.go @@ -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") + } + }) + } +}