github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/datastore/proxy/schemacaching/caching.go (about)

     1  package schemacaching
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/dustin/go-humanize"
     8  	"github.com/stretchr/testify/require"
     9  
    10  	log "github.com/authzed/spicedb/internal/logging"
    11  	"github.com/authzed/spicedb/pkg/cache"
    12  	"github.com/authzed/spicedb/pkg/datastore"
    13  )
    14  
    15  // CachingMode is the caching mode to use for schema.
    16  type CachingMode int
    17  
    18  const (
    19  	// WatchIfSupported will use a schema watch-based cache, if caching is supported. Otherwise,
    20  	// it will fallback to just-in-time caching.
    21  	WatchIfSupported CachingMode = iota
    22  
    23  	// JustInTimeCaching will always use a just-in-time cache for schema.
    24  	JustInTimeCaching
    25  )
    26  
    27  // DatastoreProxyTestCache returns a cache used for testing.
    28  func DatastoreProxyTestCache(t testing.TB) cache.Cache {
    29  	cache, err := cache.NewCache(&cache.Config{
    30  		NumCounters: 1000,
    31  		MaxCost:     1 * humanize.MiByte,
    32  	})
    33  	require.Nil(t, err)
    34  	return cache
    35  }
    36  
    37  // NewCachingDatastoreProxy creates a new datastore proxy which caches definitions that
    38  // are loaded at specific datastore revisions.
    39  func NewCachingDatastoreProxy(delegate datastore.Datastore, c cache.Cache, gcWindow time.Duration, cachingMode CachingMode, watchHeartbeat time.Duration) datastore.Datastore {
    40  	if c == nil {
    41  		c = cache.NoopCache()
    42  	}
    43  
    44  	if cachingMode == JustInTimeCaching {
    45  		log.Info().Msg("schema watch explicitly disabled")
    46  		return &definitionCachingProxy{
    47  			Datastore: delegate,
    48  			c:         c,
    49  		}
    50  	}
    51  
    52  	return createWatchingCacheProxy(delegate, c, gcWindow, watchHeartbeat)
    53  }