go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/appengine/gaemiddleware/cache.go (about) 1 // Copyright 2017 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package gaemiddleware 16 17 import ( 18 "context" 19 "time" 20 21 "go.chromium.org/luci/gae/service/info" 22 "go.chromium.org/luci/gae/service/memcache" 23 24 "go.chromium.org/luci/common/retry/transient" 25 "go.chromium.org/luci/server/caching" 26 ) 27 28 // blobCacheProvider returns caching.BlobCache implemented on top of luci/gae. 29 func blobCacheProvider(namespace string) caching.BlobCache { 30 return &gaeBlobCache{namespace} 31 } 32 33 // gaeBlobCache implements caching.BlobCache. 34 type gaeBlobCache struct { 35 ns string 36 } 37 38 func (g gaeBlobCache) Get(ctx context.Context, key string) ([]byte, error) { 39 switch itm, err := memcache.GetKey(info.MustNamespace(ctx, g.ns), key); { 40 case err == memcache.ErrCacheMiss: 41 return nil, caching.ErrCacheMiss 42 case err != nil: 43 return nil, transient.Tag.Apply(err) 44 default: 45 return itm.Value(), nil 46 } 47 } 48 49 func (g gaeBlobCache) Set(ctx context.Context, key string, value []byte, exp time.Duration) error { 50 ctx = info.MustNamespace(ctx, g.ns) 51 item := memcache.NewItem(ctx, key).SetValue(value).SetExpiration(exp) 52 if err := memcache.Set(ctx, item); err != nil { 53 return transient.Tag.Apply(err) 54 } 55 return nil 56 }