Source File
csc_commands.go
Belonging Package
github.com/redis/go-redis/v9
package redisimport ()// defaultCacheableCommands is the allow-list of read-only, deterministic// commands whose responses may be stored in the client-side cache. Keys are// lowercase to match baseCmd.Name() on the hot path.var defaultCacheableCommands = map[string]struct{}{// String commands"get": {}, "mget": {}, "getbit": {}, "getrange": {},"strlen": {}, "substr": {},// Hash commands"hget": {}, "hgetall": {}, "hmget": {},"hkeys": {}, "hvals": {}, "hlen": {},"hexists": {}, "hstrlen": {},// List commands"lindex": {}, "llen": {}, "lpos": {}, "lrange": {},// Set commands"scard": {}, "sismember": {}, "smembers": {}, "smismember": {},"sdiff": {}, "sinter": {}, "sintercard": {}, "sunion": {},// Sorted-set commands"zcard": {}, "zcount": {}, "zlexcount": {}, "zmscore": {},"zrange": {}, "zrangebylex": {}, "zrangebyscore": {},"zrank": {}, "zrevrange": {}, "zrevrangebylex": {},"zrevrangebyscore": {}, "zrevrank": {}, "zscore": {},"zdiff": {}, "zinter": {}, "zunion": {},// Bit commands"bitcount": {}, "bitfield_ro": {}, "bitpos": {},// Key/generic commands"exists": {}, "type": {}, "sort_ro": {}, "lcs": {},// Geo commands"geodist": {}, "geohash": {}, "geopos": {}, "geosearch": {},"georadiusbymember_ro": {}, "georadius_ro": {},// Stream commands. XREAD is deliberately excluded: it supports BLOCK, and// its $/+ IDs are state-relative, so identical args are not deterministic.// XPENDING is excluded for the same class of reason: its extended form// returns wall-clock-relative idle times and its IDLE filter is// time-dependent, so identical args yield different correct results with// no key modification (and therefore no invalidation)."xlen": {}, "xrange": {}, "xrevrange": {},// JSON (RedisJSON) commands"json.get": {}, "json.mget": {}, "json.arrindex": {}, "json.arrlen": {},"json.objkeys": {}, "json.objlen": {}, "json.resp": {},"json.strlen": {}, "json.type": {},// TimeSeries commands"ts.get": {}, "ts.info": {}, "ts.range": {}, "ts.revrange": {},}// isCacheable reports whether cmd is eligible for client-side caching: its// name is on the allow-list and it operates on at least one key.func isCacheable( Cmder) bool {// Commands such as RawWriteToCmd stream replies directly to an io.Writer.// Capturing their replies for CSC would buffer the entire response first,// defeating their streaming and allocation guarantees.if .NoRetry() {return false}if , := defaultCacheableCommands[.Name()]; ! {return false}// SORT_RO ... BY/GET reads pattern keys that extractRedisKeys can't// enumerate, so its invalidations would be dropped and the result go stale.// Plain SORT_RO is fine.if .Name() == "sort_ro" && sortROHasByGet() {return false}return cmdFirstKeyPosWithInfo(, nil) > 0}// sortROHasByGet reports whether a SORT_RO invocation uses BY or GET// (case-insensitive), scanning past the command name and key. stringArg// normalizes string, *string, and []byte tokens.func sortROHasByGet( Cmder) bool {for := 2; < len(.Args()); ++ {if := .stringArg(); strings.EqualFold(, "by") || strings.EqualFold(, "get") {return true}}return false}// isClientTrackingCmd reports whether cmd is a CLIENT TRACKING subcommand (any// mode: ON, OFF, or with options). Name and stringArg normalize string,// *string, and []byte arguments.func isClientTrackingCmd( Cmder) bool {return .Name() == "client" && strings.EqualFold(.stringArg(1), "tracking")}// isSelectCmd reports whether cmd changes the selected database on its// connection. CSC keys are namespaced with Options.DB, so a runtime SELECT// would make the connection's actual database diverge from the cache namespace.func isSelectCmd( Cmder) bool {return .Name() == "select"}// isAuthCmd reports whether cmd changes the authenticated user on its// connection. The cache namespace is fixed from Options.Username, so runtime// authentication would make the connection identity diverge from it.func isAuthCmd( Cmder) bool {return .Name() == "auth"}// isProtocolChangingHelloCmd reports whether HELLO includes a protocol version// (and can therefore switch a tracked RESP3 connection to RESP2). A bare HELLO// only reports connection properties and is safe.func isProtocolChangingHelloCmd( Cmder) bool {return .Name() == "hello" && len(.Args()) > 1}// isResetCmd reports whether cmd resets all server-side connection state.// RESET disables tracking, switches to RESP2, deauthenticates, and changes// other state that a pooled CSC connection relies on.func isResetCmd( Cmder) bool {return .Name() == "reset"}// isSubscribeCmd reports whether a raw command would turn an ordinary pooled// connection into a Pub/Sub connection. Pub/Sub pushes are deliberately left// for the dedicated PubSub reader, so the CSC drainer cannot safely own such a// connection.func isSubscribeCmd( Cmder) bool {switch .Name() {case "subscribe", "psubscribe", "ssubscribe":return truedefault:return false}}// buildCacheKey returns the RESP-encoded form of the command's argument list,// used as a collision-free canonical cache key. ok is false when the writer// cannot marshal the arguments, in which case the caller must skip caching// rather than bucket the command under an empty key.// (The un-namespaced form is only needed by tests; it lives in// csc_cachekey_test.go so production code has a single entry point.)// cacheKeyScratch is the reusable buffer+writer pair buildCacheKeyNS encodes// into. Building a cache key was the single largest allocator on the cached// read path -- 32% of all bytes allocated -- because every call heap-allocated// a bytes.Buffer, a proto.Writer (which itself allocates two 64-byte scratch// slices), grew the buffer, and then copied it out with String(). Only the// final String() is inherent: the key is retained, the scratch is not.type cacheKeyScratch struct {buf bytes.Bufferwr *proto.Writer}var cacheKeyScratchPool = sync.Pool{New: func() any {:= &cacheKeyScratch{}.wr = proto.NewWriter(&.buf)return},}// buildCacheKeyNS renders cmd's RESP encoding prefixed by ns, in ONE// allocation (the returned string).//// Fusing the namespace in matters as much as pooling: the caller used to take// this function's result and then do prefix+key, a second full copy of every// cache key on every cached read. Writing the prefix into the buffer first// makes the single String() produce the namespaced key directly, and the// suffix after ns is still exactly the wire encoding -- which the refresher// relies on when it slices the namespace back off to re-issue the command.func buildCacheKeyNS( Cmder, string) (string, bool) {:= .Args()if len() == 0 {return "", false}:= cacheKeyScratchPool.Get().(*cacheKeyScratch)defer func() {// Drop an oversized buffer instead of pooling it, so one huge command// does not pin that capacity for the process lifetime.if .buf.Cap() > cacheKeyScratchMaxCap {return}.buf.Reset()cacheKeyScratchPool.Put()}().buf.Reset().buf.WriteString()// The pooled writer targets s.buf for its whole life; Reset here only// guards against a zero-value scratch reaching this path.if .wr == nil {.wr = proto.NewWriter(&.buf)}if := .wr.WriteArgs(); != nil {return "", false}return .buf.String(), true}// cacheKeyScratchMaxCap bounds the buffer capacity kept in the pool.const cacheKeyScratchMaxCap = 64 << 10// isWireKeyType reports whether a key argument of v's type renders, through// stringArg, exactly as proto.Writer sends it to the server, so invalidation// lookups match the key names in the server's "invalidate" pushes. Only// byte-identical types are accepted (fmt.Sprint of any integer matches the// writer's base-10 strconv output); for anything else — pointers, bools,// times, durations, floats, BinaryMarshaler values — the rendering can// diverge, the invalidation would never match, and the entry would be served// stale forever, so the caller skips caching (see processCached).func isWireKeyType( any) bool {switch .(type) {case string, []byte,int, int8, int16, int32, int64,uint, uint8, uint16, uint32, uint64:return true}return false}// cscKeySpan returns the inclusive argument range [lo, hi] that holds cmd's// Redis keys. For every cacheable command shape the keys are contiguous.// ok is false when cmd has no key.func cscKeySpan( Cmder) (, int, bool) {:= cmdFirstKeyPosWithInfo(, nil)// SetFirstKeyPos is public and takes any int8, so a negative position is// possible. It is not a key: reject it here rather than index args with it.if <= 0 {return 0, 0, false}:= len(.Args())if >= {return 0, 0, false}switch .Name() {// All remaining args from firstKeyPos are keys.case "mget", "exists", "sdiff", "sinter", "sunion":return , - 1, true// Numkeys pattern: numkeys at args[1], keys from args[2].case "sintercard", "zdiff", "zinter", "zunion":if < 3 {return 0, 0, false}, := cscNumKeys()if ! || <= 0 {return 0, 0, false}return 2, min(2+, ) - 1, true// LCS: exactly two consecutive keys starting at firstKeyPos.case "lcs":if +1 >= {return 0, 0, false}return , + 1, true// JSON.MGET: keys from firstKeyPos to second-to-last (last arg is the// JSON path, not a key).case "json.mget":if -2 < {return 0, 0, false}return , - 2, true}// Single key at firstKeyPos (GET, HGET, LRANGE, ...).return , , true}// cscNumKeys parses the numkeys argument (args[1]). The typed commands pass// an int, which is read without rendering it to a string.func cscNumKeys( Cmder) (int, bool) {switch v := .Args()[1].(type) {case int:return , truecase int64:return int(), true}, := strconv.Atoi(.stringArg(1))return , == nil}// cscKeysRenderable reports whether every key in [lo, hi] is a type// isWireKeyType accepts. It allocates nothing, so processCached runs it on every read,// before it builds the cache key.func cscKeysRenderable( Cmder, , int) bool {:= .Args()for := ; <= ; ++ {if !isWireKeyType([]) {return false}}return true}
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |