From d4bfe3a096f6cd114d9642ac27c1d78cc6b42b2a Mon Sep 17 00:00:00 2001 From: Srikanth Chekuri Date: Wed, 5 Apr 2023 12:36:38 +0530 Subject: [PATCH] chore: set Cache-Control for auto complete requests (#2504) --- pkg/query-service/app/http_handler.go | 9 ++++++--- pkg/query-service/app/http_utils.go | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 pkg/query-service/app/http_utils.go diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.go index a617201233..4778afa723 100644 --- a/pkg/query-service/app/http_handler.go +++ b/pkg/query-service/app/http_handler.go @@ -255,9 +255,12 @@ func (aH *APIHandler) RegisterMetricsRoutes(router *mux.Router, am *AuthMiddlewa func (aH *APIHandler) RegisterQueryRangeV3Routes(router *mux.Router, am *AuthMiddleware) { subRouter := router.PathPrefix("/api/v3").Subrouter() - subRouter.HandleFunc("/autocomplete/aggregate_attributes", am.ViewAccess(aH.autocompleteAggregateAttributes)).Methods(http.MethodGet) - subRouter.HandleFunc("/autocomplete/attribute_keys", am.ViewAccess(aH.autoCompleteAttributeKeys)).Methods(http.MethodGet) - subRouter.HandleFunc("/autocomplete/attribute_values", am.ViewAccess(aH.autoCompleteAttributeValues)).Methods(http.MethodGet) + subRouter.HandleFunc("/autocomplete/aggregate_attributes", am.ViewAccess( + withCacheControl(AutoCompleteCacheControlAge, aH.autocompleteAggregateAttributes))).Methods(http.MethodGet) + subRouter.HandleFunc("/autocomplete/attribute_keys", am.ViewAccess( + withCacheControl(AutoCompleteCacheControlAge, aH.autoCompleteAttributeKeys))).Methods(http.MethodGet) + subRouter.HandleFunc("/autocomplete/attribute_values", am.ViewAccess( + withCacheControl(AutoCompleteCacheControlAge, aH.autoCompleteAttributeValues))).Methods(http.MethodGet) subRouter.HandleFunc("/query_range", am.ViewAccess(aH.QueryRangeV3)).Methods(http.MethodPost) } diff --git a/pkg/query-service/app/http_utils.go b/pkg/query-service/app/http_utils.go new file mode 100644 index 0000000000..2066044836 --- /dev/null +++ b/pkg/query-service/app/http_utils.go @@ -0,0 +1,22 @@ +package app + +import ( + "fmt" + "net/http" + "time" +) + +var ( + // AutoCompleteCacheControlAge is the max-age for the cache-control header + // for the autocomplete endpoint. + // The default export interval for the SDK is 60 seconds, and ~10s at collector, so + // one minute should be a safe value. + AutoCompleteCacheControlAge = 60 * time.Second +) + +func withCacheControl(maxAge time.Duration, h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", int(maxAge.Seconds()))) + h(w, r) + } +}