From 0b519ce19aba597af0aa86b7fbe2aef378ee699e Mon Sep 17 00:00:00 2001 From: Yordan Kinkov <yordan.kinkov@vereign.com> Date: Fri, 30 Sep 2022 09:41:23 +0300 Subject: [PATCH] #1 Add cache TTL as optional parameter on set endpoints --- design/design.go | 6 ++++++ design/types.go | 1 + internal/service/cache/service.go | 10 +++++++--- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/design/design.go b/design/design.go index 5d52668..b0de46f 100644 --- a/design/design.go +++ b/design/design.go @@ -83,6 +83,9 @@ var _ = Service("cache", func() { Header("scope:x-cache-scope", String, "Cache entry scope", func() { Example("administration") }) + Header("ttl:x-cache-ttl", Int, "Cache entry TTL in seconds", func() { + Example(60) + }) Body("data") Response(StatusCreated) @@ -107,6 +110,9 @@ var _ = Service("cache", func() { Header("scope:x-cache-scope", String, "Cache entry scope", func() { Example("administration") }) + Header("ttl:x-cache-ttl", Int, "Cache entry TTL in seconds", func() { + Example(60) + }) Body("data") Response(StatusOK) diff --git a/design/types.go b/design/types.go index b17285e..ae43f34 100644 --- a/design/types.go +++ b/design/types.go @@ -15,5 +15,6 @@ var CacheSetRequest = Type("CacheSetRequest", func() { Field(2, "key", String) Field(3, "namespace", String) Field(4, "scope", String) // Initial implementation with a single scope + Field(5, "ttl", Int) Required("data", "key") }) diff --git a/internal/service/cache/service.go b/internal/service/cache/service.go index ef52e30..aaa8ad9 100644 --- a/internal/service/cache/service.go +++ b/internal/service/cache/service.go @@ -73,8 +73,6 @@ func (s *Service) Set(ctx context.Context, req *cache.CacheSetRequest) error { return errors.New(errors.BadRequest, "missing key") } - // TODO(kinkov): issue #3 - evaluate key metadata (key, namespace and scope) and set TTL over a policy execution - // create key from the input fields key := makeCacheKey(req.Key, req.Namespace, req.Scope) // encode payload to json bytes for storing in cache @@ -84,7 +82,13 @@ func (s *Service) Set(ctx context.Context, req *cache.CacheSetRequest) error { return errors.New(errors.BadRequest, "cannot encode payload to json", err) } - if err := s.cache.Set(ctx, key, value, 0); err != nil { + // set cache ttl if provided in request + var ttl time.Duration + if req.TTL != nil { + ttl = time.Duration(*req.TTL) * time.Second + } + + if err := s.cache.Set(ctx, key, value, ttl); err != nil { logger.Error("error storing value in cache", zap.Error(err)) return errors.New("error storing value in cache", err) } -- GitLab