go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/caching/request.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 caching
    16  
    17  import (
    18  	"context"
    19  
    20  	"go.chromium.org/luci/common/data/caching/lru"
    21  )
    22  
    23  var requestCacheKey = "server.caching Per-Request Cache"
    24  
    25  // WithRequestCache initializes context-bound local cache and adds it to the
    26  // Context.
    27  //
    28  // The cache has unbounded size. This is fine, since the lifetime of the cache
    29  // is still scoped to a single request.
    30  //
    31  // It can be used as a second fast layer of caching in front of memcache.
    32  // It is never trimmed, only released at once upon the request completion.
    33  //
    34  // TODO(vadimsh): Get rid of it, there's only one caller of RequestCache(...).
    35  func WithRequestCache(c context.Context) context.Context {
    36  	return context.WithValue(c, &requestCacheKey, lru.New[string, any](0))
    37  }
    38  
    39  // RequestCache retrieves a per-request in-memory cache of the Context. If no
    40  // request cache is installed, this will panic.
    41  func RequestCache(c context.Context) *lru.Cache[string, any] {
    42  	rc, _ := c.Value(&requestCacheKey).(*lru.Cache[string, any])
    43  	if rc == nil {
    44  		panic("server/caching: no request cache installed in Context")
    45  	}
    46  	return rc
    47  }