diff --git a/NOTICE b/NOTICE index 7de7a17..ba2e28d 100644 --- a/NOTICE +++ b/NOTICE @@ -1,2 +1,2 @@ -rueidis +valkey-go Copyright 2024 Rueian (https://github.com/rueian) diff --git a/README.md b/README.md index 8592598..144ec44 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,26 @@ -# rueidis +# valkey-go -[![Go Reference](https://pkg.go.dev/badge/github.com/redis/rueidis.svg)](https://pkg.go.dev/github.com/redis/rueidis) -[![CircleCI](https://dl.circleci.com/status-badge/img/gh/redis/rueidis/tree/main.svg?style=shield)](https://dl.circleci.com/status-badge/redirect/gh/redis/rueidis/tree/main) -[![Go Report Card](https://goreportcard.com/badge/github.com/redis/rueidis)](https://goreportcard.com/report/github.com/redis/rueidis) -[![codecov](https://codecov.io/gh/redis/rueidis/branch/master/graph/badge.svg?token=wGTB8GdY06)](https://codecov.io/gh/redis/rueidis) +[![Go Reference](https://pkg.go.dev/badge/github.com/rueian/valkey-go.svg)](https://pkg.go.dev/github.com/rueian/valkey-go) +[![CircleCI](https://dl.circleci.com/status-badge/img/gh/rueian/valkey-go/tree/main.svg?style=shield)](https://dl.circleci.com/status-badge/redirect/gh/rueian/valkey-go/tree/main) +[![Go Report Card](https://goreportcard.com/badge/github.com/rueian/valkey-go)](https://goreportcard.com/report/github.com/rueian/valkey-go) +[![codecov](https://codecov.io/gh/rueian/valkey-go/branch/master/graph/badge.svg?token=wGTB8GdY06)](https://codecov.io/gh/rueian/valkey-go) -A fast Golang Redis client that does auto pipelining and supports server-assisted client-side caching. +A fast Golang Valkey client that does auto pipelining and supports server-assisted client-side caching. ## Features -* [Auto pipelining for non-blocking redis commands](#auto-pipelining) +* [Auto pipelining for non-blocking valkey commands](#auto-pipelining) * [Server-assisted client-side caching](#server-assisted-client-side-caching) * [Generic Object Mapping with client-side caching](./om) -* [Cache-Aside pattern with client-side caching](./rueidisaside) -* [Distributed Locks with client side caching](./rueidislock) -* [Helpers for writing tests with rueidis mock](./mock) -* [OpenTelemetry integration](./rueidisotel) -* [Hooks and other integrations](./rueidishook) -* [Go-redis like API adapter](./rueidiscompat) by [@418Coffee](https://github.com/418Coffee) +* [Cache-Aside pattern with client-side caching](./valkeyaside) +* [Distributed Locks with client side caching](./valkeylock) +* [Helpers for writing tests with valkey mock](./mock) +* [OpenTelemetry integration](./valkeyotel) +* [Hooks and other integrations](./valkeyhook) +* [Go-redis like API adapter](./valkeycompat) by [@418Coffee](https://github.com/418Coffee) * Pub/Sub, Sharded Pub/Sub, Streams -* Redis Cluster, Sentinel, RedisJSON, RedisBloom, RediSearch, RedisTimeseries, etc. -* [Probabilistic Data Structures without Redis Stack](./rueidisprob) +* Valkey Cluster, Sentinel, RedisJSON, RedisBloom, RediSearch, RedisTimeseries, etc. +* [Probabilistic Data Structures without Valkey Stack](./valkeyprob) --- @@ -31,11 +31,11 @@ package main import ( "context" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) func main() { - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } @@ -49,17 +49,17 @@ func main() { } ``` -Checkout more examples: [Command Response Cheatsheet](https://github.com/redis/rueidis#command-response-cheatsheet) +Checkout more examples: [Command Response Cheatsheet](https://github.com/rueian/valkey-go#command-response-cheatsheet) ## Developer Friendly Command Builder -`client.B()` is the builder entrypoint to construct a redis command: +`client.B()` is the builder entrypoint to construct a valkey command: ![Developer friendly command builder](https://user-images.githubusercontent.com/2727535/209358313-39000aee-eaa4-42e1-9748-0d3836c1264f.gif)\ _Recorded by @FZambia [Improving Centrifugo Redis Engine throughput and allocation efficiency with Rueidis Go library ](https://centrifugal.dev/blog/2022/12/20/improving-redis-engine-performance)_ -Once a command is built, use either `client.Do()` or `client.DoMulti()` to send it to redis. +Once a command is built, use either `client.Do()` or `client.DoMulti()` to send it to valkey. **You ❗️SHOULD NOT❗️ reuse the command to another `client.Do()` or `client.DoMulti()` call because it has been recycled to the underlying `sync.Pool` by default.** @@ -70,13 +70,13 @@ To reuse a command, use `Pin()` after `Build()` and it will prevent the command ### Auto Pipelining -All concurrent non-blocking redis commands (such as `GET`, `SET`) are automatically pipelined, +All concurrent non-blocking valkey commands (such as `GET`, `SET`) are automatically pipelined, which reduces the overall round trips and system calls, and gets higher throughput. You can easily get the benefit of [pipelining technique](https://redis.io/docs/manual/pipelining/) by just calling `client.Do()` from multiple goroutines concurrently. For example: ```go -func BenchmarkPipelining(b *testing.B, client rueidis.Client) { +func BenchmarkPipelining(b *testing.B, client valkey.Client) { // the below client.Do() operations will be issued from // multiple goroutines and thus will be pipelined automatically. b.RunParallel(func(pb *testing.PB) { @@ -89,7 +89,7 @@ func BenchmarkPipelining(b *testing.B, client rueidis.Client) { ### Benchmark comparison with go-redis v9 -Comparing to go-redis, Rueidis has higher throughput across 1, 8, and 64 parallelism settings. +Comparing to go-redis, valkey-go has higher throughput across 1, 8, and 64 parallelism settings. It is even able to achieve **~14x** throughput over go-redis in a local benchmark of Macbook Pro 16" M1 Pro 2021. (see `parallelism(64)-key(16)-value(64)-10`) @@ -97,14 +97,14 @@ It is even able to achieve **~14x** throughput over go-redis in a local benchmar Benchmark source code: https://github.com/rueian/rueidis-benchmark -A benchmark result performed on two GCP n2-highcpu-2 machines also shows that rueidis can achieve higher throughput with lower latencies: https://github.com/redis/rueidis/pull/93 +A benchmark result performed on two GCP n2-highcpu-2 machines also shows that valkey can achieve higher throughput with lower latencies: https://github.com/redis/rueidis/pull/93 ### Manual Pipelining Besides auto pipelining, you can also pipeline commands manually with `DoMulti()`: ``` golang -cmds := make(rueidis.Commands, 0, 10) +cmds := make(valkey.Commands, 0, 10) for i := 0; i < 10; i++ { cmds = append(cmds, client.B().Set().Key("key").Value("value").Build()) } @@ -122,15 +122,15 @@ The opt-in mode of [server-assisted client-side caching](https://redis.io/docs/m ```golang client.DoCache(ctx, client.B().Hmget().Key("mk").Field("1", "2").Cache(), time.Minute).ToArray() client.DoMultiCache(ctx, - rueidis.CT(client.B().Get().Key("k1").Cache(), 1*time.Minute), - rueidis.CT(client.B().Get().Key("k2").Cache(), 2*time.Minute)) + valkey.CT(client.B().Get().Key("k1").Cache(), 1*time.Minute), + valkey.CT(client.B().Get().Key("k2").Cache(), 2*time.Minute)) ``` -Cached responses will be invalidated either when being notified by redis servers or when their client side TTLs are reached. +Cached responses will be invalidated either when being notified by valkey servers or when their client side TTLs are reached. ### Benchmark -Server-assisted client-side caching can dramatically boost latencies and throughput just like **having a redis replica right inside your application**. For example: +Server-assisted client-side caching can dramatically boost latencies and throughput just like **having a valkey replica right inside your application**. For example: ![client_test_get](https://github.com/rueian/rueidis-benchmark/blob/master/client_test_get_10.png) @@ -150,21 +150,21 @@ Use `IsCacheHit()` to verify that if the response came from the client side memo client.DoCache(ctx, client.B().Get().Key("k1").Cache(), time.Minute).IsCacheHit() == true ``` -If the OpenTelemetry is enabled by the `rueidisotel.NewClient(option)`, then there are also two metrics instrumented: -* rueidis_do_cache_miss -* rueidis_do_cache_hits +If the OpenTelemetry is enabled by the `valkeyotel.NewClient(option)`, then there are also two metrics instrumented: +* valkey_do_cache_miss +* valkey_do_cache_hits ### MGET/JSON.MGET Client Side Caching Helpers -`rueidis.MGetCache` and `rueidis.JsonMGetCache` are handy helpers fetching multiple keys across different slots through the client side caching. -They will first group keys by slot to build `MGET` or `JSON.MGET` commands respectively and then send requests with only cache missed keys to redis nodes. +`valkey.MGetCache` and `valkey.JsonMGetCache` are handy helpers fetching multiple keys across different slots through the client side caching. +They will first group keys by slot to build `MGET` or `JSON.MGET` commands respectively and then send requests with only cache missed keys to valkey nodes. ### Broadcast Mode Client Side Caching Although the default is opt-in mode, you can use broadcast mode by specifying your prefixes in `ClientOption.ClientTrackingOptions`: ```go -client, err := rueidis.NewClient(rueidis.ClientOption{ +client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, ClientTrackingOptions: []string{"PREFIX", "prefix1:", "PREFIX", "prefix2:", "BCAST"}, }) @@ -176,16 +176,16 @@ client.DoCache(ctx, client.B().Get().Key("prefix1:1").Cache(), time.Minute).IsCa ``` Please make sure that commands passed to `DoCache()` and `DoMultiCache()` are covered by your prefixes. -Otherwise, their client-side cache will not be invalidated by redis. +Otherwise, their client-side cache will not be invalidated by valkey. ### Client Side Caching with Cache Aside Pattern Cache-Aside is a widely used caching strategy. -[rueidisaside](https://github.com/redis/rueidis/blob/main/rueidisaside/README.md) can help you cache data into your client-side cache backed by Redis. For example: +[valkeyaside](https://github.com/rueian/valkey-go/blob/main/valkeyaside/README.md) can help you cache data into your client-side cache backed by Valkey. For example: ```go -client, err := rueidisaside.NewClient(rueidisaside.ClientOption{ - ClientOption: rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}, +client, err := valkeyaside.NewClient(valkeyaside.ClientOption{ + ClientOption: valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}, }) if err != nil { panic(err) @@ -200,11 +200,11 @@ val, err := client.Get(context.Background(), time.Minute, "mykey", func(ctx cont // ... ``` -Please refer to the full example at [rueidisaside](https://github.com/redis/rueidis/blob/main/rueidisaside/README.md). +Please refer to the full example at [valkeyaside](https://github.com/rueian/valkey-go/blob/main/valkeyaside/README.md). ### Disable Client Side Caching -Some Redis provider doesn't support client-side caching, ex. Google Cloud Memorystore. +Some Valkey provider doesn't support client-side caching, ex. Google Cloud Memorystore. You can disable client-side caching by setting `ClientOption.DisableCache` to `true`. This will also fall back `client.DoCache()` and `client.DoMultiCache()` to `client.Do()` and `client.DoMulti()`. @@ -222,10 +222,10 @@ Please note that though operations can return early, the command is likely sent ## Pub/Sub -To receive messages from channels, `client.Receive()` should be used. It supports `SUBSCRIBE`, `PSUBSCRIBE` and Redis 7.0's `SSUBSCRIBE`: +To receive messages from channels, `client.Receive()` should be used. It supports `SUBSCRIBE`, `PSUBSCRIBE` and Valkey 7.0's `SSUBSCRIBE`: ```golang -err = client.Receive(context.Background(), client.B().Subscribe().Channel("ch1", "ch2").Build(), func(msg rueidis.PubSubMessage) { +err = client.Receive(context.Background(), client.B().Subscribe().Channel("ch1", "ch2").Build(), func(msg valkey.PubSubMessage) { // handle the msg }) ``` @@ -234,7 +234,7 @@ The provided handler will be called with received message. It is important to note that `client.Receive()` will keep blocking until returning a value in the following cases: 1. return `nil` when received any unsubscribe/punsubscribe message related to the provided `subscribe` command. -2. return `rueidis.ErrClosing` when the client is closed manually. +2. return `valkey.ErrClosing` when the client is closed manually. 3. return `ctx.Err()` when the `ctx` is done. 4. return non-nil `err` when the provided `subscribe` command failed. @@ -251,8 +251,8 @@ There is an alternative `Dedicatedclient.SetPubSubHooks()` allows users to subsc c, cancel := client.Dedicate() defer cancel() -wait := c.SetPubSubHooks(rueidis.PubSubHooks{ - OnMessage: func(m rueidis.PubSubMessage) { +wait := c.SetPubSubHooks(valkey.PubSubHooks{ + OnMessage: func(m valkey.PubSubMessage) { // Handle message. This callback will be called sequentially, but in another goroutine. } }) @@ -269,7 +269,7 @@ To do a [CAS Transaction](https://redis.io/docs/interact/transactions/#optimisti unintentional write commands between `WATCH` and `EXEC`. Otherwise, the `EXEC` may not fail as expected. ```golang -client.Dedicated(func(c rueidis.DedicatedClient) error { +client.Dedicated(func(c valkey.DedicatedClient) error { // watch keys first c.Do(ctx, c.B().Watch().Key("k1", "k2").Build()) // perform read here @@ -307,14 +307,14 @@ The `NewLuaScript` or `NewLuaScriptReadOnly` will create a script which is safe When calling the `script.Exec`, it will try sending `EVALSHA` first and fallback to `EVAL` if the server returns `NOSCRIPT`. ```golang -script := rueidis.NewLuaScript("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}") +script := valkey.NewLuaScript("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}") // the script.Exec is safe for concurrent call list, err := script.Exec(ctx, client, []string{"k1", "k2"}, []string{"a1", "a2"}).ToArray() ``` ## Streaming Read -`client.DoStream()` and `client.DoMultiStream()` can be used to send large redis responses to an `io.Writer` +`client.DoStream()` and `client.DoMultiStream()` can be used to send large valkey responses to an `io.Writer` directly without allocating them in the memory. They work by first sending commands to a dedicated connection acquired from a pool, then directly copying the response values to the given `io.Writer`, and finally recycling the connection. @@ -322,62 +322,62 @@ then directly copying the response values to the given `io.Writer`, and finally s := client.DoMultiStream(ctx, client.B().Get().Key("a{slot1}").Build(), client.B().Get().Key("b{slot1}").Build()) for s.HasNext() { n, err := s.WriteTo(io.Discard) - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { // ... } } ``` Note that these two methods will occupy connections until all responses are written to the given `io.Writer`. -This can take a long time and hurt performance. Use the normal `Do()` and `DoMulti()` instead unless you want to avoid allocating memory for large redis response. +This can take a long time and hurt performance. Use the normal `Do()` and `DoMulti()` instead unless you want to avoid allocating memory for large valkey response. -Also note that these two methods only work with `string`, `integer`, and `float` redis responses. And `DoMultiStream` currently -does not support pipelining keys across multiple slots when connecting to a redis cluster. +Also note that these two methods only work with `string`, `integer`, and `float` valkey responses. And `DoMultiStream` currently +does not support pipelining keys across multiple slots when connecting to a valkey cluster. ## Memory Consumption Consideration -Each underlying connection in rueidis allocates a ring buffer for pipelining. +Each underlying connection in valkey allocates a ring buffer for pipelining. Its size is controlled by the `ClientOption.RingScaleEachConn` and the default value is 10 which results into each ring of size 2^10. -If you have many rueidis connections, you may find that they occupy quite amount of memory. +If you have many valkey connections, you may find that they occupy quite amount of memory. In that case, you may consider reducing `ClientOption.RingScaleEachConn` to 8 or 9 at the cost of potential throughput degradation. -You may also consider setting the value of `ClientOption.PipelineMultiplex` to `-1`, which will let rueidis use only 1 connection for pipelining to each redis node. +You may also consider setting the value of `ClientOption.PipelineMultiplex` to `-1`, which will let valkey use only 1 connection for pipelining to each valkey node. -## Instantiating a new Redis Client +## Instantiating a new Valkey Client -You can create a new redis client using `NewClient` and provide several options. +You can create a new valkey client using `NewClient` and provide several options. ```golang -// Connect to a single redis node: -client, err := rueidis.NewClient(rueidis.ClientOption{ +// Connect to a single valkey node: +client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, }) -// Connect to a redis cluster -client, err := rueidis.NewClient(rueidis.ClientOption{ +// Connect to a valkey cluster +client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003"}, ShuffleInit: true, }) -// Connect to a redis cluster and use replicas for read operations -client, err := rueidis.NewClient(rueidis.ClientOption{ +// Connect to a valkey cluster and use replicas for read operations +client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003"}, - SendToReplicas: func(cmd rueidis.Completed) bool { + SendToReplicas: func(cmd valkey.Completed) bool { return cmd.IsReadOnly() }, }) // Connect to sentinels -client, err := rueidis.NewClient(rueidis.ClientOption{ +client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:26379", "127.0.0.1:26380", "127.0.0.1:26381"}, - Sentinel: rueidis.SentinelOption{ + Sentinel: valkey.SentinelOption{ MasterSet: "my_master", }, }) ``` -### Redis URL +### Valkey URL You can use `ParseURL` or `MustParseURL` to construct a `ClientOption`. @@ -386,12 +386,12 @@ The provided url must be started with either `redis://`, `rediss://` or `unix:// Currently supported url parameters are `db`, `dial_timeout`, `write_timeout`, `addr`, `protocol`, `client_cache`, `client_name`, `max_retries`, and `master_set`. ```go -// connect to a redis cluster -client, err = rueidis.NewClient(rueidis.MustParseURL("redis://127.0.0.1:7001?addr=127.0.0.1:7002&addr=127.0.0.1:7003")) -// connect to a redis node -client, err = rueidis.NewClient(rueidis.MustParseURL("redis://127.0.0.1:6379/0")) -// connect to a redis sentinel -client, err = rueidis.NewClient(rueidis.MustParseURL("redis://127.0.0.1:26379/0?master_set=my_master")) +// connect to a valkey cluster +client, err = valkey.NewClient(valkey.MustParseURL("redis://127.0.0.1:7001?addr=127.0.0.1:7002&addr=127.0.0.1:7003")) +// connect to a valkey node +client, err = valkey.NewClient(valkey.MustParseURL("redis://127.0.0.1:6379/0")) +// connect to a valkey sentinel +client, err = valkey.NewClient(valkey.MustParseURL("redis://127.0.0.1:26379/0?master_set=my_master")) ``` @@ -406,28 +406,28 @@ client.B().Arbitrary("ANY", "CMD").Keys("k1", "k2").Args("a1", "a2").Build() ## Working with JSON, Raw `[]byte`, and Vector Similarity Search -The command builder treats all the parameters as Redis strings, which are binary safe. This means that users can store `[]byte` -directly into Redis without conversion. And the `rueidis.BinaryString` helper can convert `[]byte` to `string` without copy. For example: +The command builder treats all the parameters as Valkey strings, which are binary safe. This means that users can store `[]byte` +directly into Valkey without conversion. And the `valkey.BinaryString` helper can convert `[]byte` to `string` without copy. For example: ```golang -client.B().Set().Key("b").Value(rueidis.BinaryString([]byte{...})).Build() +client.B().Set().Key("b").Value(valkey.BinaryString([]byte{...})).Build() ``` -Treating all the parameters as Redis strings also means that the command builder doesn't do any quoting, conversion automatically for users. +Treating all the parameters as Valkey strings also means that the command builder doesn't do any quoting, conversion automatically for users. -When working with RedisJSON, users frequently need to prepare JSON string in Redis string. And `rueidis.JSON` can help: +When working with RedisJSON, users frequently need to prepare JSON string in Valkey string. And `valkey.JSON` can help: ```golang -client.B().JsonSet().Key("j").Path("$.myStrField").Value(rueidis.JSON("str")).Build() +client.B().JsonSet().Key("j").Path("$.myStrField").Value(valkey.JSON("str")).Build() // equivalent to client.B().JsonSet().Key("j").Path("$.myStrField").Value(`"str"`).Build() ``` -When working with vector similarity search, users can use `rueidis.VectorString32` and `rueidis.VectorString64` to build queries: +When working with vector similarity search, users can use `valkey.VectorString32` and `valkey.VectorString64` to build queries: ```golang cmd := client.B().FtSearch().Index("idx").Query("*=>[KNN 5 @vec $V]"). - Params().Nargs(2).NameValue().NameValue("V", rueidis.VectorString64([]float64{...})). + Params().Nargs(2).NameValue().NameValue("V", valkey.VectorString64([]float64{...})). Dialect(2).Build() n, resp, err := client.Do(ctx, cmd).AsFtSearch() ``` @@ -435,7 +435,7 @@ n, resp, err := client.Do(ctx, cmd).AsFtSearch() ## Command Response Cheatsheet While the command builder is developer friendly, the response parser is a little unfriendly. Developers must know what -type of Redis response will be returned from the server beforehand and which parser they should use. Otherwise, it panics. +type of Valkey response will be returned from the server beforehand and which parser they should use. Otherwise, it panics. It is hard to remember what type of message will be returned and which parsing to used. So, here are some common examples: @@ -503,7 +503,7 @@ if err = client.Do(ctx, client.B().Set().Key("user2").Value(`{"name": "name2"}`) // Scan MGET results into []*User var users []*User // or []User is also scannable -if err := rueidis.DecodeSliceOfJSON(client.Do(ctx, client.B().Mget().Key("user1", "user2").Build()), &users); err != nil { +if err := valkey.DecodeSliceOfJSON(client.Do(ctx, client.B().Mget().Key("user1", "user2").Build()), &users); err != nil { return err } @@ -528,7 +528,7 @@ if err = client.Do(ctx, client.B().Set().Key("user1").Value("userName1").Build() // Bad users := make([]*User, 0) -if err := rueidis.DecodeSliceOfJSON(client.Do(ctx, client.B().Mget().Key("user1").Build()), &users); err != nil { +if err := valkey.DecodeSliceOfJSON(client.Do(ctx, client.B().Mget().Key("user1").Build()), &users); err != nil { return err } // -> Error: invalid character 'u' looking for beginning of value @@ -539,7 +539,7 @@ if err := rueidis.DecodeSliceOfJSON(client.Do(ctx, client.B().Mget().Key("user1" ## Contributing -Contributions are welcome, including [issues](https://github.com/redis/rueidis/issues), [pull requests](https://github.com/redis/rueidis/pulls), and [discussions](https://github.com/redis/rueidis/discussions). +Contributions are welcome, including [issues](https://github.com/rueian/valkey-go/issues), [pull requests](https://github.com/rueian/valkey-go/pulls), and [discussions](https://github.com/rueian/valkey-go/discussions). Contributions mean a lot to us and help us improve this library and the community! ### Generate command builders diff --git a/binary.go b/binary.go index 25056b0..bcb14d2 100644 --- a/binary.go +++ b/binary.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "encoding/binary" @@ -8,12 +8,12 @@ import ( ) // BinaryString convert the provided []byte into a string without copy. It does what strings.Builder.String() does. -// Redis Strings are binary safe, this means that it is safe to store any []byte into Redis directly. -// Users can use this BinaryString helper to insert a []byte as the part of redis command. For example: +// Valkey Strings are binary safe, this means that it is safe to store any []byte into Valkey directly. +// Users can use this BinaryString helper to insert a []byte as the part of valkey command. For example: // -// client.B().Set().Key(rueidis.BinaryString([]byte{0})).Value(rueidis.BinaryString([]byte{0})).Build() +// client.B().Set().Key(valkey.BinaryString([]byte{0})).Value(valkey.BinaryString([]byte{0})).Build() // -// To read back the []byte of the string returned from the Redis, it is recommended to use the RedisMessage.AsReader. +// To read back the []byte of the string returned from the Valkey, it is recommended to use the ValkeyMessage.AsReader. func BinaryString(bs []byte) string { return unsafe.String(unsafe.SliceData(bs), len(bs)) } @@ -21,7 +21,7 @@ func BinaryString(bs []byte) string { // VectorString32 convert the provided []float32 into a string. Users can use this to build vector search queries: // // client.B().FtSearch().Index("idx").Query("*=>[KNN 5 @vec $V]"). -// Params().Nargs(2).NameValue().NameValue("V", rueidis.VectorString32([]float32{1})). +// Params().Nargs(2).NameValue().NameValue("V", valkey.VectorString32([]float32{1})). // Dialect(2).Build() func VectorString32(v []float32) string { b := make([]byte, len(v)*4) @@ -32,7 +32,7 @@ func VectorString32(v []float32) string { return BinaryString(b) } -// ToVector32 reverts VectorString32. User can use this to convert redis response back to []float32. +// ToVector32 reverts VectorString32. User can use this to convert valkey response back to []float32. func ToVector32(s string) []float32 { bs := unsafe.Slice(unsafe.StringData(s), len(s)) vs := make([]float32, 0, len(bs)/4) @@ -45,7 +45,7 @@ func ToVector32(s string) []float32 { // VectorString64 convert the provided []float64 into a string. Users can use this to build vector search queries: // // client.B().FtSearch().Index("idx").Query("*=>[KNN 5 @vec $V]"). -// Params().Nargs(2).NameValue().NameValue("V", rueidis.VectorString64([]float64{1})). +// Params().Nargs(2).NameValue().NameValue("V", valkey.VectorString64([]float64{1})). // Dialect(2).Build() func VectorString64(v []float64) string { b := make([]byte, len(v)*8) @@ -56,7 +56,7 @@ func VectorString64(v []float64) string { return BinaryString(b) } -// ToVector64 reverts VectorString64. User can use this to convert redis response back to []float64. +// ToVector64 reverts VectorString64. User can use this to convert valkey response back to []float64. func ToVector64(s string) []float64 { bs := unsafe.Slice(unsafe.StringData(s), len(s)) vs := make([]float64, 0, len(bs)/8) @@ -69,7 +69,7 @@ func ToVector64(s string) []float64 { // JSON convert the provided parameter into a JSON string. Users can use this JSON helper to work with RedisJSON commands. // For example: // -// client.B().JsonSet().Key("a").Path("$.myField").Value(rueidis.JSON("str")).Build() +// client.B().JsonSet().Key("a").Path("$.myField").Value(valkey.JSON("str")).Build() func JSON(in any) string { bs, err := json.Marshal(in) if err != nil { diff --git a/binary_test.go b/binary_test.go index e95d115..3947d14 100644 --- a/binary_test.go +++ b/binary_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "encoding/json" @@ -30,7 +30,6 @@ func TestJSONPanic(t *testing.T) { JSON(a) } - func TestVectorString32(t *testing.T) { for _, test := range [][]float32{ {}, diff --git a/cache.go b/cache.go index ef5ca86..4bcbcf9 100644 --- a/cache.go +++ b/cache.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -11,7 +11,7 @@ type NewCacheStoreFn func(CacheStoreOption) CacheStore // CacheStoreOption will be passed to NewCacheStoreFn type CacheStoreOption struct { - // CacheSizeEachConn is redis client side cache size that bind to each TCP connection to a single redis instance. + // CacheSizeEachConn is valkey client side cache size that bind to each TCP connection to a single valkey instance. // The default is DefaultCacheBytes. CacheSizeEachConn int } @@ -21,35 +21,35 @@ type CacheStoreOption struct { type CacheStore interface { // Flight is called when DoCache and DoMultiCache, with the requested client side ttl and the current time. // It should look up the store in single-flight manner and return one of the following three combinations: - // Case 1: (empty RedisMessage, nil CacheEntry) <- when cache missed, and rueidis will send the request to redis. - // Case 2: (empty RedisMessage, non-nil CacheEntry) <- when cache missed, and rueidis will use CacheEntry.Wait to wait for response. - // Case 3: (non-empty RedisMessage, nil CacheEntry) <- when cache hit - Flight(key, cmd string, ttl time.Duration, now time.Time) (v RedisMessage, e CacheEntry) - // Update is called when receiving the response of the request sent by the above Flight Case 1 from redis. + // Case 1: (empty ValkeyMessage, nil CacheEntry) <- when cache missed, and valkey will send the request to valkey. + // Case 2: (empty ValkeyMessage, non-nil CacheEntry) <- when cache missed, and valkey will use CacheEntry.Wait to wait for response. + // Case 3: (non-empty ValkeyMessage, nil CacheEntry) <- when cache hit + Flight(key, cmd string, ttl time.Duration, now time.Time) (v ValkeyMessage, e CacheEntry) + // Update is called when receiving the response of the request sent by the above Flight Case 1 from valkey. // It should not only update the store but also deliver the response to all CacheEntry.Wait and return a desired client side PXAT of the response. - // Note that the server side expire time can be retrieved from RedisMessage.CachePXAT. - Update(key, cmd string, val RedisMessage) (pxat int64) + // Note that the server side expire time can be retrieved from ValkeyMessage.CachePXAT. + Update(key, cmd string, val ValkeyMessage) (pxat int64) // Cancel is called when the request sent by the above Flight Case 1 failed. // It should not only deliver the error to all CacheEntry.Wait but also remove the CacheEntry from the store. Cancel(key, cmd string, err error) - // Delete is called when receiving invalidation notifications from redis. + // Delete is called when receiving invalidation notifications from valkey. // If the keys is nil then it should delete all non-pending cached entries under all keys. // If the keys is not nil then it should delete all non-pending cached entries under those keys. - Delete(keys []RedisMessage) - // Close is called when connection between redis is broken. + Delete(keys []ValkeyMessage) + // Close is called when connection between valkey is broken. // It should flush all cached entries and deliver the error to all pending CacheEntry.Wait. Close(err error) } // CacheEntry should be used to wait for single-flight response when cache missed. type CacheEntry interface { - Wait(ctx context.Context) (RedisMessage, error) + Wait(ctx context.Context) (ValkeyMessage, error) } // SimpleCache is an alternative interface should be paired with NewSimpleCacheAdapter to construct a CacheStore type SimpleCache interface { - Get(key string) RedisMessage - Set(key string, val RedisMessage) + Get(key string) ValkeyMessage + Set(key string, val ValkeyMessage) Del(key string) Flush() } @@ -65,7 +65,7 @@ type adapter struct { mu sync.RWMutex } -func (a *adapter) Flight(key, cmd string, ttl time.Duration, now time.Time) (RedisMessage, CacheEntry) { +func (a *adapter) Flight(key, cmd string, ttl time.Duration, now time.Time) (ValkeyMessage, CacheEntry) { a.mu.RLock() if v := a.store.Get(key + cmd); v.typ != 0 && v.relativePTTL(now) > 0 { a.mu.RUnlock() @@ -74,7 +74,7 @@ func (a *adapter) Flight(key, cmd string, ttl time.Duration, now time.Time) (Red flight := a.flights[key][cmd] a.mu.RUnlock() if flight != nil { - return RedisMessage{}, flight + return ValkeyMessage{}, flight } a.mu.Lock() entries := a.flights[key] @@ -86,10 +86,10 @@ func (a *adapter) Flight(key, cmd string, ttl time.Duration, now time.Time) (Red entries[cmd] = &adapterEntry{ch: make(chan struct{}), xat: now.Add(ttl).UnixMilli()} } a.mu.Unlock() - return RedisMessage{}, flight + return ValkeyMessage{}, flight } -func (a *adapter) Update(key, cmd string, val RedisMessage) (sxat int64) { +func (a *adapter) Update(key, cmd string, val ValkeyMessage) (sxat int64) { a.mu.Lock() entries := a.flights[key] if flight, ok := entries[cmd].(*adapterEntry); ok { @@ -110,7 +110,7 @@ func (a *adapter) Cancel(key, cmd string, err error) { a.mu.Lock() entries := a.flights[key] if flight, ok := entries[cmd].(*adapterEntry); ok { - flight.set(RedisMessage{}, err) + flight.set(ValkeyMessage{}, err) entries[cmd] = nil } a.mu.Unlock() @@ -129,7 +129,7 @@ func (a *adapter) del(key string) { } } -func (a *adapter) Delete(keys []RedisMessage) { +func (a *adapter) Delete(keys []ValkeyMessage) { a.mu.Lock() if keys == nil { for key := range a.flights { @@ -152,7 +152,7 @@ func (a *adapter) Close(err error) { for _, entries := range flights { for _, e := range entries { if e != nil { - e.(*adapterEntry).set(RedisMessage{}, err) + e.(*adapterEntry).set(ValkeyMessage{}, err) } } } @@ -161,19 +161,19 @@ func (a *adapter) Close(err error) { type adapterEntry struct { err error ch chan struct{} - val RedisMessage + val ValkeyMessage xat int64 } -func (a *adapterEntry) set(val RedisMessage, err error) { +func (a *adapterEntry) set(val ValkeyMessage, err error) { a.err, a.val = err, val close(a.ch) } -func (a *adapterEntry) Wait(ctx context.Context) (RedisMessage, error) { +func (a *adapterEntry) Wait(ctx context.Context) (ValkeyMessage, error) { select { case <-ctx.Done(): - return RedisMessage{}, ctx.Err() + return ValkeyMessage{}, ctx.Err() case <-a.ch: return a.val, a.err } diff --git a/cache_test.go b/cache_test.go index 82d5e71..3da5525 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -15,22 +15,22 @@ func test(t *testing.T, storeFn func() CacheStore) { v, e := store.Flight("key", "cmd", time.Millisecond*100, now) if v.typ != 0 || e != nil { - t.Fatal("first flight should return empty RedisMessage and nil CacheEntry") + t.Fatal("first flight should return empty ValkeyMessage and nil CacheEntry") } v, e = store.Flight("key", "cmd", time.Millisecond*100, now) if v.typ != 0 || e == nil { - t.Fatal("flights before Update should return empty RedisMessage and non-nil CacheEntry") + t.Fatal("flights before Update should return empty ValkeyMessage and non-nil CacheEntry") } - store.Delete([]RedisMessage{{typ: '+', string: "key"}}) // Delete should not affect pending CacheEntry + store.Delete([]ValkeyMessage{{typ: '+', string: "key"}}) // Delete should not affect pending CacheEntry v2, e2 := store.Flight("key", "cmd", time.Millisecond*100, now) if v2.typ != 0 || e != e2 { - t.Fatal("flights before Update should return empty RedisMessage and the same CacheEntry, not be affected by Delete") + t.Fatal("flights before Update should return empty ValkeyMessage and the same CacheEntry, not be affected by Delete") } - v = RedisMessage{typ: '+', string: "val"} + v = ValkeyMessage{typ: '+', string: "val"} v.setExpireAt(now.Add(time.Second).UnixMilli()) if pttl := store.Update("key", "cmd", v); pttl < now.Add(90*time.Millisecond).UnixMilli() || pttl > now.Add(100*time.Millisecond).UnixMilli() { t.Fatal("Update should return a desired pttl") @@ -46,16 +46,16 @@ func test(t *testing.T, storeFn func() CacheStore) { v2, e2 = store.Flight("key", "cmd", time.Millisecond*100, now) if v2.typ != v.typ || v2.string != v.string { - t.Fatal("flights after Update should return updated RedisMessage") + t.Fatal("flights after Update should return updated ValkeyMessage") } if pttl := v2.CachePXAT(); pttl < now.Add(90*time.Millisecond).UnixMilli() || pttl > now.Add(100*time.Millisecond).UnixMilli() { t.Fatal("CachePXAT should return a desired pttl") } - store.Delete([]RedisMessage{{typ: '+', string: "key"}}) + store.Delete([]ValkeyMessage{{typ: '+', string: "key"}}) v, e = store.Flight("key", "cmd", time.Millisecond*100, now) if v.typ != 0 || e != nil { - t.Fatal("flights after Delete should return empty RedisMessage and nil CacheEntry") + t.Fatal("flights after Delete should return empty ValkeyMessage and nil CacheEntry") } }) @@ -66,19 +66,19 @@ func test(t *testing.T, storeFn func() CacheStore) { v, e := store.Flight("key", "cmd", time.Millisecond*100, now) if v.typ != 0 || e != nil { - t.Fatal("first flight should return empty RedisMessage and nil CacheEntry") + t.Fatal("first flight should return empty ValkeyMessage and nil CacheEntry") } v, e = store.Flight("key", "cmd", time.Millisecond*100, now) if v.typ != 0 || e == nil { - t.Fatal("flights before Update should return empty RedisMessage and non-nil CacheEntry") + t.Fatal("flights before Update should return empty ValkeyMessage and non-nil CacheEntry") } - store.Delete([]RedisMessage{{typ: '+', string: "key"}}) // Delete should not affect pending CacheEntry + store.Delete([]ValkeyMessage{{typ: '+', string: "key"}}) // Delete should not affect pending CacheEntry v2, e2 := store.Flight("key", "cmd", time.Millisecond*100, now) if v2.typ != 0 || e != e2 { - t.Fatal("flights before Update should return empty RedisMessage and the same CacheEntry, not be affected by Delete") + t.Fatal("flights before Update should return empty ValkeyMessage and the same CacheEntry, not be affected by Delete") } store.Cancel("key", "cmd", errors.New("err")) @@ -90,7 +90,7 @@ func test(t *testing.T, storeFn func() CacheStore) { v, e = store.Flight("key", "cmd", time.Millisecond*100, now) if v.typ != 0 || e != nil { - t.Fatal("flights after Cancel should return empty RedisMessage and nil CacheEntry") + t.Fatal("flights after Cancel should return empty ValkeyMessage and nil CacheEntry") } }) @@ -98,23 +98,23 @@ func test(t *testing.T, storeFn func() CacheStore) { var now = time.Now() var store = storeFn() - for _, deletions := range [][]RedisMessage{ + for _, deletions := range [][]ValkeyMessage{ {{typ: '+', string: "key"}}, nil, } { store.Flight("key", "cmd1", time.Millisecond*100, now) store.Flight("key", "cmd2", time.Millisecond*100, now) - store.Update("key", "cmd1", RedisMessage{typ: '+', string: "val"}) - store.Update("key", "cmd2", RedisMessage{typ: '+', string: "val"}) + store.Update("key", "cmd1", ValkeyMessage{typ: '+', string: "val"}) + store.Update("key", "cmd2", ValkeyMessage{typ: '+', string: "val"}) store.Delete(deletions) if v, e := store.Flight("key", "cmd1", time.Millisecond*100, now); v.typ != 0 || e != nil { - t.Fatal("flight after delete should return empty RedisMessage and nil CacheEntry") + t.Fatal("flight after delete should return empty ValkeyMessage and nil CacheEntry") } if v, e := store.Flight("key", "cmd2", time.Millisecond*100, now); v.typ != 0 || e != nil { - t.Fatal("flight after delete should return empty RedisMessage and nil CacheEntry") + t.Fatal("flight after delete should return empty ValkeyMessage and nil CacheEntry") } } }) @@ -125,16 +125,16 @@ func test(t *testing.T, storeFn func() CacheStore) { v, e := store.Flight("key", "cmd", time.Second, now) if v.typ != 0 || e != nil { - t.Fatal("first flight should return empty RedisMessage and nil CacheEntry") + t.Fatal("first flight should return empty ValkeyMessage and nil CacheEntry") } - v = RedisMessage{typ: '+', string: "val"} + v = ValkeyMessage{typ: '+', string: "val"} v.setExpireAt(now.Add(time.Millisecond).UnixMilli()) store.Update("key", "cmd", v) v, e = store.Flight("key", "cmd", time.Second, now.Add(time.Millisecond)) if v.typ != 0 || e != nil { - t.Fatal("flight after TTL should return empty RedisMessage and nil CacheEntry") + t.Fatal("flight after TTL should return empty ValkeyMessage and nil CacheEntry") } }) @@ -153,7 +153,7 @@ func test(t *testing.T, storeFn func() CacheStore) { _, e = store.Flight("key", "cmd", time.Millisecond*100, now) if e != nil { - t.Fatal("flight after Close should return empty RedisMessage and nil CacheEntry") + t.Fatal("flight after Close should return empty ValkeyMessage and nil CacheEntry") } }) @@ -180,20 +180,20 @@ func TestCacheStore(t *testing.T) { }) t.Run("SimpleCache", func(t *testing.T) { test(t, func() CacheStore { - return NewSimpleCacheAdapter(&simple{store: map[string]RedisMessage{}}) + return NewSimpleCacheAdapter(&simple{store: map[string]ValkeyMessage{}}) }) }) } type simple struct { - store map[string]RedisMessage + store map[string]ValkeyMessage } -func (s *simple) Get(key string) RedisMessage { +func (s *simple) Get(key string) ValkeyMessage { return s.store[key] } -func (s *simple) Set(key string, val RedisMessage) { +func (s *simple) Set(key string, val ValkeyMessage) { s.store[key] = val } diff --git a/client.go b/client.go index e3a7921..447b243 100644 --- a/client.go +++ b/client.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -6,7 +6,7 @@ import ( "sync/atomic" "time" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go/internal/cmds" ) type singleClient struct { @@ -41,27 +41,27 @@ func (c *singleClient) B() Builder { return c.cmd } -func (c *singleClient) Do(ctx context.Context, cmd Completed) (resp RedisResult) { +func (c *singleClient) Do(ctx context.Context, cmd Completed) (resp ValkeyResult) { retry: resp = c.conn.Do(ctx, cmd) - if c.retry && cmd.IsReadOnly() && c.isRetryable(resp.NonRedisError(), ctx) { + if c.retry && cmd.IsReadOnly() && c.isRetryable(resp.NonValkeyError(), ctx) { goto retry } - if resp.NonRedisError() == nil { // not recycle cmds if error, since cmds may be used later in pipe. consider recycle them by pipe + if resp.NonValkeyError() == nil { // not recycle cmds if error, since cmds may be used later in pipe. consider recycle them by pipe cmds.PutCompleted(cmd) } return resp } -func (c *singleClient) DoStream(ctx context.Context, cmd Completed) RedisResultStream { +func (c *singleClient) DoStream(ctx context.Context, cmd Completed) ValkeyResultStream { s := c.conn.DoStream(ctx, cmd) cmds.PutCompleted(cmd) return s } -func (c *singleClient) DoMultiStream(ctx context.Context, multi ...Completed) MultiRedisResultStream { +func (c *singleClient) DoMultiStream(ctx context.Context, multi ...Completed) MultiValkeyResultStream { if len(multi) == 0 { - return RedisResultStream{e: io.EOF} + return ValkeyResultStream{e: io.EOF} } s := c.conn.DoMultiStream(ctx, multi...) for _, cmd := range multi { @@ -70,7 +70,7 @@ func (c *singleClient) DoMultiStream(ctx context.Context, multi ...Completed) Mu return s } -func (c *singleClient) DoMulti(ctx context.Context, multi ...Completed) (resps []RedisResult) { +func (c *singleClient) DoMulti(ctx context.Context, multi ...Completed) (resps []ValkeyResult) { if len(multi) == 0 { return nil } @@ -78,20 +78,20 @@ retry: resps = c.conn.DoMulti(ctx, multi...).s if c.retry && allReadOnly(multi) { for _, resp := range resps { - if c.isRetryable(resp.NonRedisError(), ctx) { + if c.isRetryable(resp.NonValkeyError(), ctx) { goto retry } } } for i, cmd := range multi { - if resps[i].NonRedisError() == nil { + if resps[i].NonValkeyError() == nil { cmds.PutCompleted(cmd) } } return resps } -func (c *singleClient) DoMultiCache(ctx context.Context, multi ...CacheableTTL) (resps []RedisResult) { +func (c *singleClient) DoMultiCache(ctx context.Context, multi ...CacheableTTL) (resps []ValkeyResult) { if len(multi) == 0 { return nil } @@ -99,26 +99,26 @@ retry: resps = c.conn.DoMultiCache(ctx, multi...).s if c.retry { for _, resp := range resps { - if c.isRetryable(resp.NonRedisError(), ctx) { + if c.isRetryable(resp.NonValkeyError(), ctx) { goto retry } } } for i, cmd := range multi { - if err := resps[i].NonRedisError(); err == nil || err == ErrDoCacheAborted { + if err := resps[i].NonValkeyError(); err == nil || err == ErrDoCacheAborted { cmds.PutCacheable(cmd.Cmd) } } return resps } -func (c *singleClient) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp RedisResult) { +func (c *singleClient) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp ValkeyResult) { retry: resp = c.conn.DoCache(ctx, cmd, ttl) - if c.retry && c.isRetryable(resp.NonRedisError(), ctx) { + if c.retry && c.isRetryable(resp.NonValkeyError(), ctx) { goto retry } - if err := resp.NonRedisError(); err == nil || err == ErrDoCacheAborted { + if err := resp.NonValkeyError(); err == nil || err == ErrDoCacheAborted { cmds.PutCacheable(cmd) } return resp @@ -128,7 +128,7 @@ func (c *singleClient) Receive(ctx context.Context, subscribe Completed, fn func retry: err = c.conn.Receive(ctx, subscribe, fn) if c.retry { - if _, ok := err.(*RedisError); !ok && c.isRetryable(err, ctx) { + if _, ok := err.(*ValkeyError); !ok && c.isRetryable(err, ctx) { goto retry } } @@ -174,20 +174,20 @@ func (c *dedicatedSingleClient) B() Builder { return c.cmd } -func (c *dedicatedSingleClient) Do(ctx context.Context, cmd Completed) (resp RedisResult) { +func (c *dedicatedSingleClient) Do(ctx context.Context, cmd Completed) (resp ValkeyResult) { retry: c.check() resp = c.wire.Do(ctx, cmd) - if c.retry && cmd.IsReadOnly() && isRetryable(resp.NonRedisError(), c.wire, ctx) { + if c.retry && cmd.IsReadOnly() && isRetryable(resp.NonValkeyError(), c.wire, ctx) { goto retry } - if resp.NonRedisError() == nil { + if resp.NonValkeyError() == nil { cmds.PutCompleted(cmd) } return resp } -func (c *dedicatedSingleClient) DoMulti(ctx context.Context, multi ...Completed) (resp []RedisResult) { +func (c *dedicatedSingleClient) DoMulti(ctx context.Context, multi ...Completed) (resp []ValkeyResult) { if len(multi) == 0 { return nil } @@ -202,7 +202,7 @@ retry: goto retry } for i, cmd := range multi { - if resp[i].NonRedisError() == nil { + if resp[i].NonValkeyError() == nil { cmds.PutCompleted(cmd) } } @@ -214,7 +214,7 @@ retry: c.check() err = c.wire.Receive(ctx, subscribe, fn) if c.retry { - if _, ok := err.(*RedisError); !ok && isRetryable(err, c.wire, ctx) { + if _, ok := err.(*ValkeyError); !ok && isRetryable(err, c.wire, ctx) { goto retry } } @@ -254,9 +254,9 @@ func isRetryable(err error, w wire, ctx context.Context) bool { return err != nil && w.Error() == nil && ctx.Err() == nil } -func anyRetryable(resp []RedisResult, w wire, ctx context.Context) bool { +func anyRetryable(resp []ValkeyResult, w wire, ctx context.Context) bool { for _, r := range resp { - if isRetryable(r.NonRedisError(), w, ctx) { + if isRetryable(r.NonValkeyError(), w, ctx) { return true } } diff --git a/client_test.go b/client_test.go index b02cedf..f93ed2d 100644 --- a/client_test.go +++ b/client_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -13,14 +13,14 @@ import ( ) type mockConn struct { - DoFn func(cmd Completed) RedisResult - DoCacheFn func(cmd Cacheable, ttl time.Duration) RedisResult - DoMultiFn func(multi ...Completed) *redisresults - DoMultiCacheFn func(multi ...CacheableTTL) *redisresults + DoFn func(cmd Completed) ValkeyResult + DoCacheFn func(cmd Cacheable, ttl time.Duration) ValkeyResult + DoMultiFn func(multi ...Completed) *valkeyresults + DoMultiCacheFn func(multi ...CacheableTTL) *valkeyresults ReceiveFn func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error - DoStreamFn func(cmd Completed) RedisResultStream - DoMultiStreamFn func(cmd ...Completed) MultiRedisResultStream - InfoFn func() map[string]RedisMessage + DoStreamFn func(cmd Completed) ValkeyResultStream + DoMultiStreamFn func(cmd ...Completed) MultiValkeyResultStream + InfoFn func() map[string]ValkeyMessage VersionFn func() int ErrorFn func() error CloseFn func() @@ -30,8 +30,8 @@ type mockConn struct { OverrideFn func(c conn) AddrFn func() string - DoOverride map[string]func(cmd Completed) RedisResult - DoCacheOverride map[string]func(cmd Cacheable, ttl time.Duration) RedisResult + DoOverride map[string]func(cmd Completed) ValkeyResult + DoCacheOverride map[string]func(cmd Cacheable, ttl time.Duration) ValkeyResult ReceiveOverride map[string]func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error } @@ -61,35 +61,35 @@ func (m *mockConn) Store(w wire) { } } -func (m *mockConn) Do(ctx context.Context, cmd Completed) RedisResult { +func (m *mockConn) Do(ctx context.Context, cmd Completed) ValkeyResult { if fn := m.DoOverride[strings.Join(cmd.Commands(), " ")]; fn != nil { return fn(cmd) } if m.DoFn != nil { return m.DoFn(cmd) } - return RedisResult{} + return ValkeyResult{} } -func (m *mockConn) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) RedisResult { +func (m *mockConn) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) ValkeyResult { if fn := m.DoCacheOverride[strings.Join(cmd.Commands(), " ")]; fn != nil { return fn(cmd, ttl) } if m.DoCacheFn != nil { return m.DoCacheFn(cmd, ttl) } - return RedisResult{} + return ValkeyResult{} } -func (m *mockConn) DoMultiCache(ctx context.Context, multi ...CacheableTTL) *redisresults { - overrides := make([]RedisResult, 0, len(multi)) +func (m *mockConn) DoMultiCache(ctx context.Context, multi ...CacheableTTL) *valkeyresults { + overrides := make([]ValkeyResult, 0, len(multi)) for _, cmd := range multi { if fn := m.DoCacheOverride[strings.Join(cmd.Cmd.Commands(), " ")]; fn != nil { overrides = append(overrides, fn(cmd.Cmd, cmd.TTL)) } } if len(overrides) == len(multi) { - return &redisresults{s: overrides} + return &valkeyresults{s: overrides} } if m.DoMultiCacheFn != nil { return m.DoMultiCacheFn(multi...) @@ -97,15 +97,15 @@ func (m *mockConn) DoMultiCache(ctx context.Context, multi ...CacheableTTL) *red return nil } -func (m *mockConn) DoMulti(ctx context.Context, multi ...Completed) *redisresults { - overrides := make([]RedisResult, 0, len(multi)) +func (m *mockConn) DoMulti(ctx context.Context, multi ...Completed) *valkeyresults { + overrides := make([]ValkeyResult, 0, len(multi)) for _, cmd := range multi { if fn := m.DoOverride[strings.Join(cmd.Commands(), " ")]; fn != nil { overrides = append(overrides, fn(cmd)) } } if len(overrides) == len(multi) { - return &redisresults{s: overrides} + return &valkeyresults{s: overrides} } if m.DoMultiFn != nil { return m.DoMultiFn(multi...) @@ -123,18 +123,18 @@ func (m *mockConn) Receive(ctx context.Context, subscribe Completed, hdl func(me return nil } -func (m *mockConn) DoStream(ctx context.Context, cmd Completed) RedisResultStream { +func (m *mockConn) DoStream(ctx context.Context, cmd Completed) ValkeyResultStream { if m.DoStreamFn != nil { return m.DoStreamFn(cmd) } - return RedisResultStream{} + return ValkeyResultStream{} } -func (m *mockConn) DoMultiStream(ctx context.Context, cmd ...Completed) MultiRedisResultStream { +func (m *mockConn) DoMultiStream(ctx context.Context, cmd ...Completed) MultiValkeyResultStream { if m.DoMultiStreamFn != nil { return m.DoMultiStreamFn(cmd...) } - return MultiRedisResultStream{} + return MultiValkeyResultStream{} } func (m *mockConn) CleanSubscriptions() { @@ -149,7 +149,7 @@ func (m *mockConn) SetOnCloseHook(func(error)) { } -func (m *mockConn) Info() map[string]RedisMessage { +func (m *mockConn) Info() map[string]ValkeyMessage { if m.InfoFn != nil { return m.InfoFn() } @@ -243,11 +243,11 @@ func TestSingleClient(t *testing.T) { t.Run("Delegate Do", func(t *testing.T) { c := client.B().Get().Key("Do").Build() - m.DoFn = func(cmd Completed) RedisResult { + m.DoFn = func(cmd Completed) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), c.Commands()) { t.Fatalf("unexpected command %v", cmd) } - return newResult(RedisMessage{typ: '+', string: "Do"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "Do"}, nil) } if v, err := client.Do(context.Background(), c).ToString(); err != nil || v != "Do" { t.Fatalf("unexpected response %v %v", v, err) @@ -256,8 +256,8 @@ func TestSingleClient(t *testing.T) { t.Run("Delegate DoStream", func(t *testing.T) { c := client.B().Get().Key("Do").Build() - m.DoStreamFn = func(cmd Completed) RedisResultStream { - return RedisResultStream{e: errors.New(cmd.Commands()[1])} + m.DoStreamFn = func(cmd Completed) ValkeyResultStream { + return ValkeyResultStream{e: errors.New(cmd.Commands()[1])} } if s := client.DoStream(context.Background(), c); s.Error().Error() != "Do" { t.Fatalf("unexpected response %v", s.Error()) @@ -266,11 +266,11 @@ func TestSingleClient(t *testing.T) { t.Run("Delegate DoMulti", func(t *testing.T) { c := client.B().Get().Key("Do").Build() - m.DoMultiFn = func(cmd ...Completed) *redisresults { + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { if !reflect.DeepEqual(cmd[0].Commands(), c.Commands()) { t.Fatalf("unexpected command %v", cmd) } - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "Do"}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "Do"}, nil)}} } if len(client.DoMulti(context.Background())) != 0 { t.Fatalf("unexpected response length") @@ -282,8 +282,8 @@ func TestSingleClient(t *testing.T) { t.Run("Delegate DoMultiStream", func(t *testing.T) { c := client.B().Get().Key("Do").Build() - m.DoMultiStreamFn = func(cmd ...Completed) MultiRedisResultStream { - return MultiRedisResultStream{e: errors.New(cmd[0].Commands()[1])} + m.DoMultiStreamFn = func(cmd ...Completed) MultiValkeyResultStream { + return MultiValkeyResultStream{e: errors.New(cmd[0].Commands()[1])} } if s := client.DoMultiStream(context.Background()); s.Error() != io.EOF { t.Fatalf("unexpected response %v", err) @@ -295,11 +295,11 @@ func TestSingleClient(t *testing.T) { t.Run("Delegate DoCache", func(t *testing.T) { c := client.B().Get().Key("DoCache").Cache() - m.DoCacheFn = func(cmd Cacheable, ttl time.Duration) RedisResult { + m.DoCacheFn = func(cmd Cacheable, ttl time.Duration) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), c.Commands()) || ttl != 100 { t.Fatalf("unexpected command %v, %v", cmd, ttl) } - return newResult(RedisMessage{typ: '+', string: "DoCache"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "DoCache"}, nil) } if v, err := client.DoCache(context.Background(), c, 100).ToString(); err != nil || v != "DoCache" { t.Fatalf("unexpected response %v %v", v, err) @@ -308,11 +308,11 @@ func TestSingleClient(t *testing.T) { t.Run("Delegate DoMultiCache", func(t *testing.T) { c := client.B().Get().Key("DoCache").Cache() - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { if !reflect.DeepEqual(multi[0].Cmd.Commands(), c.Commands()) || multi[0].TTL != 100 { t.Fatalf("unexpected command %v, %v", multi[0].Cmd, multi[0].TTL) } - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "DoCache"}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "DoCache"}, nil)}} } if len(client.DoMultiCache(context.Background())) != 0 { t.Fatalf("unexpected response length") @@ -336,9 +336,9 @@ func TestSingleClient(t *testing.T) { } }) - t.Run("Delegate Receive Redis Err", func(t *testing.T) { + t.Run("Delegate Receive Valkey Err", func(t *testing.T) { c := client.B().Subscribe().Channel("ch").Build() - e := &RedisError{} + e := &ValkeyError{} m.ReceiveFn = func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e } @@ -365,8 +365,8 @@ func TestSingleClient(t *testing.T) { } }) - t.Run("Dedicated Delegate Receive Redis Err", func(t *testing.T) { - e := &RedisError{} + t.Run("Dedicated Delegate Receive Valkey Err", func(t *testing.T) { + e := &ValkeyError{} w := &mockWire{ ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e @@ -385,11 +385,11 @@ func TestSingleClient(t *testing.T) { t.Run("Dedicated Delegate", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "Delegate"}, nil)}} + DoMultiFn: func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil)}} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return ErrClosing @@ -451,11 +451,11 @@ func TestSingleClient(t *testing.T) { t.Run("Dedicate Delegate", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "Delegate"}, nil)}} + DoMultiFn: func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil)}} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return ErrClosing @@ -605,17 +605,17 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { return fn(m), m } - makeDoFn := func(results ...RedisResult) func(cmd Completed) RedisResult { + makeDoFn := func(results ...ValkeyResult) func(cmd Completed) ValkeyResult { count := -1 - return func(cmd Completed) RedisResult { + return func(cmd Completed) ValkeyResult { count++ return results[count] } } - makeDoCacheFn := func(results ...RedisResult) func(cmd Cacheable, ttl time.Duration) RedisResult { + makeDoCacheFn := func(results ...ValkeyResult) func(cmd Cacheable, ttl time.Duration) ValkeyResult { count := -1 - return func(cmd Cacheable, ttl time.Duration) RedisResult { + return func(cmd Cacheable, ttl time.Duration) ValkeyResult { count++ return results[count] } @@ -629,19 +629,19 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { } } - makeDoMultiFn := func(results ...[]RedisResult) func(multi ...Completed) *redisresults { + makeDoMultiFn := func(results ...[]ValkeyResult) func(multi ...Completed) *valkeyresults { count := -1 - return func(multi ...Completed) *redisresults { + return func(multi ...Completed) *valkeyresults { count++ - return &redisresults{s: results[count]} + return &valkeyresults{s: results[count]} } } - makeDoMultiCacheFn := func(results ...[]RedisResult) func(multi ...CacheableTTL) *redisresults { + makeDoMultiCacheFn := func(results ...[]ValkeyResult) func(multi ...CacheableTTL) *valkeyresults { count := -1 - return func(multi ...CacheableTTL) *redisresults { + return func(multi ...CacheableTTL) *valkeyresults { count++ - return &redisresults{s: results[count]} + return &valkeyresults{s: results[count]} } } @@ -649,7 +649,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { c, m := setup() m.DoFn = makeDoFn( newErrResult(ErrClosing), - newResult(RedisMessage{typ: '+', string: "Do"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Do"}, nil), ) if v, err := c.Do(context.Background(), c.B().Get().Key("Do").Build()).ToString(); err != nil || v != "Do" { t.Fatalf("unexpected response %v %v", v, err) @@ -686,8 +686,8 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Delegate DoMulti ReadOnly Retry", func(t *testing.T) { c, m := setup() m.DoMultiFn = makeDoMultiFn( - []RedisResult{newErrResult(ErrClosing)}, - []RedisResult{newResult(RedisMessage{typ: '+', string: "Do"}, nil)}, + []ValkeyResult{newErrResult(ErrClosing)}, + []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "Do"}, nil)}, ) if v, err := c.DoMulti(context.Background(), c.B().Get().Key("Do").Build())[0].ToString(); err != nil || v != "Do" { t.Fatalf("unexpected response %v %v", v, err) @@ -696,7 +696,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Delegate DoMulti ReadOnly NoRetry - closed", func(t *testing.T) { c, m := setup() - m.DoMultiFn = makeDoMultiFn([]RedisResult{newErrResult(ErrClosing)}) + m.DoMultiFn = makeDoMultiFn([]ValkeyResult{newErrResult(ErrClosing)}) c.Close() if v, err := c.DoMulti(context.Background(), c.B().Get().Key("Do").Build())[0].ToString(); err != ErrClosing { t.Fatalf("unexpected response %v %v", v, err) @@ -705,7 +705,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Delegate DoMulti ReadOnly NoRetry - ctx done", func(t *testing.T) { c, m := setup() - m.DoMultiFn = makeDoMultiFn([]RedisResult{newErrResult(ErrClosing)}) + m.DoMultiFn = makeDoMultiFn([]ValkeyResult{newErrResult(ErrClosing)}) ctx, cancel := context.WithCancel(context.Background()) cancel() if v, err := c.DoMulti(ctx, c.B().Get().Key("Do").Build())[0].ToString(); err != ErrClosing { @@ -715,7 +715,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Delegate DoMulti Write NoRetry", func(t *testing.T) { c, m := setup() - m.DoMultiFn = makeDoMultiFn([]RedisResult{newErrResult(ErrClosing)}) + m.DoMultiFn = makeDoMultiFn([]ValkeyResult{newErrResult(ErrClosing)}) if v, err := c.DoMulti(context.Background(), c.B().Set().Key("Do").Value("V").Build())[0].ToString(); err != ErrClosing { t.Fatalf("unexpected response %v %v", v, err) } @@ -725,7 +725,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { c, m := setup() m.DoCacheFn = makeDoCacheFn( newErrResult(ErrClosing), - newResult(RedisMessage{typ: '+', string: "Do"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Do"}, nil), ) if v, err := c.DoCache(context.Background(), c.B().Get().Key("Do").Cache(), 0).ToString(); err != nil || v != "Do" { t.Fatalf("unexpected response %v %v", v, err) @@ -754,8 +754,8 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Delegate DoMultiCache Retry", func(t *testing.T) { c, m := setup() m.DoMultiCacheFn = makeDoMultiCacheFn( - []RedisResult{newErrResult(ErrClosing)}, - []RedisResult{newResult(RedisMessage{typ: '+', string: "Do"}, nil)}, + []ValkeyResult{newErrResult(ErrClosing)}, + []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "Do"}, nil)}, ) if v, err := c.DoMultiCache(context.Background(), CT(c.B().Get().Key("Do").Cache(), 0))[0].ToString(); err != nil || v != "Do" { t.Fatalf("unexpected response %v %v", v, err) @@ -764,7 +764,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Delegate DoMultiCache NoRetry - closed", func(t *testing.T) { c, m := setup() - m.DoMultiCacheFn = makeDoMultiCacheFn([]RedisResult{newErrResult(ErrClosing)}) + m.DoMultiCacheFn = makeDoMultiCacheFn([]ValkeyResult{newErrResult(ErrClosing)}) c.Close() if v, err := c.DoMultiCache(context.Background(), CT(c.B().Get().Key("Do").Cache(), 0))[0].ToString(); err != ErrClosing { t.Fatalf("unexpected response %v %v", v, err) @@ -773,7 +773,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Delegate DoMultiCache ReadOnly NoRetry - ctx done", func(t *testing.T) { c, m := setup() - m.DoMultiCacheFn = makeDoMultiCacheFn([]RedisResult{newErrResult(ErrClosing)}) + m.DoMultiCacheFn = makeDoMultiCacheFn([]ValkeyResult{newErrResult(ErrClosing)}) ctx, cancel := context.WithCancel(context.Background()) cancel() if v, err := c.DoMultiCache(ctx, CT(c.B().Get().Key("Do").Cache(), 0))[0].ToString(); err != ErrClosing { @@ -812,7 +812,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { c, m := setup() m.DoFn = makeDoFn( newErrResult(ErrClosing), - newResult(RedisMessage{typ: '+', string: "Do"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Do"}, nil), ) m.AcquireFn = func() wire { return &mockWire{DoFn: m.DoFn} } if ret := c.Dedicated(func(cc DedicatedClient) error { @@ -864,8 +864,8 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Dedicate Delegate DoMulti ReadOnly Retry", func(t *testing.T) { c, m := setup() m.DoMultiFn = makeDoMultiFn( - []RedisResult{newErrResult(ErrClosing)}, - []RedisResult{newResult(RedisMessage{typ: '+', string: "Do"}, nil)}, + []ValkeyResult{newErrResult(ErrClosing)}, + []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "Do"}, nil)}, ) m.AcquireFn = func() wire { return &mockWire{DoMultiFn: m.DoMultiFn} } if ret := c.Dedicated(func(cc DedicatedClient) error { @@ -880,7 +880,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Dedicate Delegate DoMulti ReadOnly NoRetry - broken", func(t *testing.T) { c, m := setup() - m.DoMultiFn = makeDoMultiFn([]RedisResult{newErrResult(ErrClosing)}) + m.DoMultiFn = makeDoMultiFn([]ValkeyResult{newErrResult(ErrClosing)}) m.ErrorFn = func() error { return ErrClosing } m.AcquireFn = func() wire { return &mockWire{DoMultiFn: m.DoMultiFn, ErrorFn: m.ErrorFn} } if ret := c.Dedicated(func(cc DedicatedClient) error { @@ -892,7 +892,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Dedicate Delegate DoMulti ReadOnly NoRetry - ctx done", func(t *testing.T) { c, m := setup() - m.DoMultiFn = makeDoMultiFn([]RedisResult{newErrResult(ErrClosing)}) + m.DoMultiFn = makeDoMultiFn([]ValkeyResult{newErrResult(ErrClosing)}) m.AcquireFn = func() wire { return &mockWire{DoMultiFn: m.DoMultiFn} } ctx, cancel := context.WithCancel(context.Background()) cancel() @@ -905,7 +905,7 @@ func SetupClientRetry(t *testing.T, fn func(mock *mockConn) Client) { t.Run("Dedicate Delegate DoMulti Write NoRetry", func(t *testing.T) { c, m := setup() - m.DoMultiFn = makeDoMultiFn([]RedisResult{newErrResult(ErrClosing)}) + m.DoMultiFn = makeDoMultiFn([]ValkeyResult{newErrResult(ErrClosing)}) m.AcquireFn = func() wire { return &mockWire{DoMultiFn: m.DoMultiFn} } if ret := c.Dedicated(func(cc DedicatedClient) error { return cc.DoMulti(context.Background(), c.B().Set().Key("Do").Value("Do").Build())[0].Error() diff --git a/cluster.go b/cluster.go index 5ba956a..81106f3 100644 --- a/cluster.go +++ b/cluster.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -13,12 +13,12 @@ import ( "sync/atomic" "time" - "github.com/redis/rueidis/internal/cmds" - "github.com/redis/rueidis/internal/util" + "github.com/rueian/valkey-go/internal/cmds" + "github.com/rueian/valkey-go/internal/util" ) -// ErrNoSlot indicates that there is no redis node owns the key slot. -var ErrNoSlot = errors.New("the slot has no redis node") +// ErrNoSlot indicates that there is no valkey node owns the key slot. +var ErrNoSlot = errors.New("the slot has no valkey node") var ErrReplicaOnlyConflict = errors.New("ReplicaOnly conflicts with SendToReplicas option") type retry struct { @@ -176,7 +176,7 @@ func (c *clusterClient) lazyRefresh() { type clusterslots struct { addr string - reply RedisResult + reply ValkeyResult ver int } @@ -351,9 +351,9 @@ func parseEndpoint(fallback, endpoint string, port int64) string { return net.JoinHostPort(endpoint, strconv.FormatInt(port, 10)) } -// parseSlots - map redis slots for each redis nodes/addresses +// parseSlots - map valkey slots for each valkey nodes/addresses // defaultAddr is needed in case the node does not know its own IP -func parseSlots(slots RedisMessage, defaultAddr string) map[string]group { +func parseSlots(slots ValkeyMessage, defaultAddr string) map[string]group { groups := make(map[string]group, len(slots.values)) for _, v := range slots.values { master := parseEndpoint(defaultAddr, v.values[2].values[0].string, v.values[2].values[1].integer) @@ -376,9 +376,9 @@ func parseSlots(slots RedisMessage, defaultAddr string) map[string]group { return groups } -// parseShards - map redis shards for each redis nodes/addresses +// parseShards - map valkey shards for each valkey nodes/addresses // defaultAddr is needed in case the node does not know its own IP -func parseShards(shards RedisMessage, defaultAddr string, tls bool) map[string]group { +func parseShards(shards ValkeyMessage, defaultAddr string, tls bool) map[string]group { groups := make(map[string]group, len(shards.values)) for _, v := range shards.values { m := -1 @@ -476,14 +476,14 @@ func (c *clusterClient) B() Builder { return c.cmd } -func (c *clusterClient) Do(ctx context.Context, cmd Completed) (resp RedisResult) { - if resp = c.do(ctx, cmd); resp.NonRedisError() == nil { // not recycle cmds if error, since cmds may be used later in pipe. consider recycle them by pipe +func (c *clusterClient) Do(ctx context.Context, cmd Completed) (resp ValkeyResult) { + if resp = c.do(ctx, cmd); resp.NonValkeyError() == nil { // not recycle cmds if error, since cmds may be used later in pipe. consider recycle them by pipe cmds.PutCompleted(cmd) } return resp } -func (c *clusterClient) do(ctx context.Context, cmd Completed) (resp RedisResult) { +func (c *clusterClient) do(ctx context.Context, cmd Completed) (resp ValkeyResult) { retry: cc, err := c.pick(ctx, cmd.Slot(), c.toReplica(cmd)) if err != nil { @@ -616,7 +616,7 @@ func (c *clusterClient) pickMulti(ctx context.Context, multi []Completed) (*conn return conns, slot, toReplica, nil } -func (c *clusterClient) doresultfn(ctx context.Context, results *redisresults, retries *connretry, mu *sync.Mutex, cc conn, cIndexes []int, commands []Completed, resps []RedisResult) { +func (c *clusterClient) doresultfn(ctx context.Context, results *valkeyresults, retries *connretry, mu *sync.Mutex, cc conn, cIndexes []int, commands []Completed, resps []ValkeyResult) { for i, resp := range resps { ii := cIndexes[i] cm := commands[i] @@ -649,7 +649,7 @@ func (c *clusterClient) doresultfn(ctx context.Context, results *redisresults, r } } -func (c *clusterClient) doretry(ctx context.Context, cc conn, results *redisresults, retries *connretry, re *retry, mu *sync.Mutex, wg *sync.WaitGroup) { +func (c *clusterClient) doretry(ctx context.Context, cc conn, results *valkeyresults, retries *connretry, re *retry, mu *sync.Mutex, wg *sync.WaitGroup) { if len(re.commands) != 0 { resps := cc.DoMulti(ctx, re.commands...) c.doresultfn(ctx, results, retries, mu, cc, re.cIndexes, re.commands, resps.s) @@ -666,7 +666,7 @@ func (c *clusterClient) doretry(ctx context.Context, cc conn, results *redisresu wg.Done() } -func (c *clusterClient) DoMulti(ctx context.Context, multi ...Completed) []RedisResult { +func (c *clusterClient) DoMulti(ctx context.Context, multi ...Completed) []ValkeyResult { if len(multi) == 0 { return nil } @@ -704,14 +704,14 @@ retry: } for i, cmd := range multi { - if results.s[i].NonRedisError() == nil { + if results.s[i].NonValkeyError() == nil { cmds.PutCompleted(cmd) } } return results.s } -func fillErrs(n int, err error) (results []RedisResult) { +func fillErrs(n int, err error) (results []ValkeyResult) { results = resultsp.Get(n, n).s for i := range results { results[i] = newErrResult(err) @@ -719,7 +719,7 @@ func fillErrs(n int, err error) (results []RedisResult) { return results } -func (c *clusterClient) doMulti(ctx context.Context, slot uint16, multi []Completed, toReplica bool) []RedisResult { +func (c *clusterClient) doMulti(ctx context.Context, slot uint16, multi []Completed, toReplica bool) []ValkeyResult { retry: cc, err := c.pick(ctx, slot, toReplica) if err != nil { @@ -752,7 +752,7 @@ process: return resps.s } -func (c *clusterClient) doCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp RedisResult) { +func (c *clusterClient) doCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp ValkeyResult) { retry: cc, err := c.pick(ctx, cmd.Slot(), c.toReplica(Completed(cmd))) if err != nil { @@ -778,15 +778,15 @@ process: return resp } -func (c *clusterClient) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp RedisResult) { +func (c *clusterClient) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp ValkeyResult) { resp = c.doCache(ctx, cmd, ttl) - if err := resp.NonRedisError(); err == nil || err == ErrDoCacheAborted { + if err := resp.NonValkeyError(); err == nil || err == ErrDoCacheAborted { cmds.PutCacheable(cmd) } return resp } -func askingMulti(cc conn, ctx context.Context, multi []Completed) *redisresults { +func askingMulti(cc conn, ctx context.Context, multi []Completed) *valkeyresults { commands := make([]Completed, 0, len(multi)*2) for _, cmd := range multi { commands = append(commands, cmds.AskingCmd, cmd) @@ -800,7 +800,7 @@ func askingMulti(cc conn, ctx context.Context, multi []Completed) *redisresults return results } -func askingMultiCache(cc conn, ctx context.Context, multi []CacheableTTL) *redisresults { +func askingMultiCache(cc conn, ctx context.Context, multi []CacheableTTL) *valkeyresults { commands := make([]Completed, 0, len(multi)*6) for _, cmd := range multi { ck, _ := cmds.CacheKey(cmd.Cmd) @@ -896,7 +896,7 @@ func (c *clusterClient) pickMultiCache(ctx context.Context, multi []CacheableTTL return conns, nil } -func (c *clusterClient) resultcachefn(ctx context.Context, results *redisresults, retries *connretrycache, mu *sync.Mutex, cc conn, cIndexes []int, commands []CacheableTTL, resps []RedisResult) { +func (c *clusterClient) resultcachefn(ctx context.Context, results *valkeyresults, retries *connretrycache, mu *sync.Mutex, cc conn, cIndexes []int, commands []CacheableTTL, resps []ValkeyResult) { for i, resp := range resps { ii := cIndexes[i] cm := commands[i] @@ -929,7 +929,7 @@ func (c *clusterClient) resultcachefn(ctx context.Context, results *redisresults } } -func (c *clusterClient) doretrycache(ctx context.Context, cc conn, results *redisresults, retries *connretrycache, re *retrycache, mu *sync.Mutex, wg *sync.WaitGroup) { +func (c *clusterClient) doretrycache(ctx context.Context, cc conn, results *valkeyresults, retries *connretrycache, re *retrycache, mu *sync.Mutex, wg *sync.WaitGroup) { if len(re.commands) != 0 { resps := cc.DoMultiCache(ctx, re.commands...) c.resultcachefn(ctx, results, retries, mu, cc, re.cIndexes, re.commands, resps.s) @@ -946,7 +946,7 @@ func (c *clusterClient) doretrycache(ctx context.Context, cc conn, results *redi wg.Done() } -func (c *clusterClient) DoMultiCache(ctx context.Context, multi ...CacheableTTL) []RedisResult { +func (c *clusterClient) DoMultiCache(ctx context.Context, multi ...CacheableTTL) []ValkeyResult { if len(multi) == 0 { return nil } @@ -977,7 +977,7 @@ retry: } for i, cmd := range multi { - if err := results.s[i].NonRedisError(); err == nil || err == ErrDoCacheAborted { + if err := results.s[i].NonValkeyError(); err == nil || err == ErrDoCacheAborted { cmds.PutCacheable(cmd.Cmd) } } @@ -1002,19 +1002,19 @@ ret: return err } -func (c *clusterClient) DoStream(ctx context.Context, cmd Completed) RedisResultStream { +func (c *clusterClient) DoStream(ctx context.Context, cmd Completed) ValkeyResultStream { cc, err := c.pick(ctx, cmd.Slot(), c.toReplica(cmd)) if err != nil { - return RedisResultStream{e: err} + return ValkeyResultStream{e: err} } ret := cc.DoStream(ctx, cmd) cmds.PutCompleted(cmd) return ret } -func (c *clusterClient) DoMultiStream(ctx context.Context, multi ...Completed) MultiRedisResultStream { +func (c *clusterClient) DoMultiStream(ctx context.Context, multi ...Completed) MultiValkeyResultStream { if len(multi) == 0 { - return RedisResultStream{e: io.EOF} + return ValkeyResultStream{e: io.EOF} } slot := multi[0].Slot() repl := c.toReplica(multi[0]) @@ -1030,7 +1030,7 @@ func (c *clusterClient) DoMultiStream(ctx context.Context, multi ...Completed) M } cc, err := c.pick(ctx, slot, repl) if err != nil { - return RedisResultStream{e: err} + return ValkeyResultStream{e: err} } ret := cc.DoMultiStream(ctx, multi...) for _, cmd := range multi { @@ -1072,7 +1072,7 @@ func (c *clusterClient) Close() { func (c *clusterClient) shouldRefreshRetry(err error, ctx context.Context) (addr string, mode RedirectMode) { if err != nil && atomic.LoadUint32(&c.stop) == 0 { - if err, ok := err.(*RedisError); ok { + if err, ok := err.(*ValkeyError); ok { if addr, ok = err.IsMoved(); ok { mode = RedirectMove } else if addr, ok = err.IsAsk(); ok { @@ -1158,7 +1158,7 @@ func (c *dedicatedClusterClient) B() Builder { return c.cmd } -func (c *dedicatedClusterClient) Do(ctx context.Context, cmd Completed) (resp RedisResult) { +func (c *dedicatedClusterClient) Do(ctx context.Context, cmd Completed) (resp ValkeyResult) { retry: if w, err := c.acquire(ctx, cmd.Slot()); err != nil { resp = newErrResult(err) @@ -1172,13 +1172,13 @@ retry: } } } - if resp.NonRedisError() == nil { + if resp.NonValkeyError() == nil { cmds.PutCompleted(cmd) } return resp } -func (c *dedicatedClusterClient) DoMulti(ctx context.Context, multi ...Completed) (resp []RedisResult) { +func (c *dedicatedClusterClient) DoMulti(ctx context.Context, multi ...Completed) (resp []ValkeyResult) { if len(multi) == 0 { return nil } @@ -1210,7 +1210,7 @@ retry: } } for i, cmd := range multi { - if resp[i].NonRedisError() == nil { + if resp[i].NonValkeyError() == nil { cmds.PutCompleted(cmd) } } diff --git a/cluster_test.go b/cluster_test.go index 543099a..c07c8bf 100644 --- a/cluster_test.go +++ b/cluster_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -16,16 +16,16 @@ import ( "time" ) -var slotsResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ +var slotsResp = newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 16383}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.0.1"}, {typ: ':', integer: 0}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica + {typ: '*', values: []ValkeyMessage{ // replica {typ: '+', string: "127.0.1.1"}, {typ: ':', integer: 1}, {typ: '+', string: ""}, @@ -33,30 +33,30 @@ var slotsResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ }}, }}, nil) -var slotsMultiResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ +var slotsMultiResp = newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 8192}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.0.1"}, {typ: ':', integer: 0}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica + {typ: '*', values: []ValkeyMessage{ // replica {typ: '+', string: "127.0.1.1"}, {typ: ':', integer: 1}, {typ: '+', string: ""}, }}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 8193}, {typ: ':', integer: 16383}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.2.1"}, {typ: ':', integer: 0}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica + {typ: '*', values: []ValkeyMessage{ // replica {typ: '+', string: "127.0.3.1"}, {typ: ':', integer: 1}, {typ: '+', string: ""}, @@ -64,20 +64,20 @@ var slotsMultiResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ }}, }}, nil) -var slotsMultiRespWithoutReplicas = newResult(RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ +var slotsMultiRespWithoutReplicas = newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 8192}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.0.1"}, {typ: ':', integer: 0}, {typ: '+', string: ""}, }}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 8193}, {typ: ':', integer: 16383}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.1.1"}, {typ: ':', integer: 0}, {typ: '+', string: ""}, @@ -85,50 +85,50 @@ var slotsMultiRespWithoutReplicas = newResult(RedisMessage{typ: '*', values: []R }}, }}, nil) -var slotsMultiRespWithMultiReplicas = newResult(RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ +var slotsMultiRespWithMultiReplicas = newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 8192}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.0.1"}, {typ: ':', integer: 0}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica1 + {typ: '*', values: []ValkeyMessage{ // replica1 {typ: '+', string: "127.0.0.2"}, {typ: ':', integer: 1}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica2 + {typ: '*', values: []ValkeyMessage{ // replica2 {typ: '+', string: "127.0.0.3"}, {typ: ':', integer: 2}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica3 + {typ: '*', values: []ValkeyMessage{ // replica3 {typ: '+', string: "127.0.0.4"}, {typ: ':', integer: 3}, {typ: '+', string: ""}, }}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 8193}, {typ: ':', integer: 16383}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.1.1"}, {typ: ':', integer: 0}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica1 + {typ: '*', values: []ValkeyMessage{ // replica1 {typ: '+', string: "127.0.1.2"}, {typ: ':', integer: 1}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica2 + {typ: '*', values: []ValkeyMessage{ // replica2 {typ: '+', string: "127.0.1.3"}, {typ: ':', integer: 2}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica3 + {typ: '*', values: []ValkeyMessage{ // replica3 {typ: '+', string: "127.0.1.4"}, {typ: ':', integer: 3}, {typ: '+', string: ""}, @@ -136,11 +136,11 @@ var slotsMultiRespWithMultiReplicas = newResult(RedisMessage{typ: '*', values: [ }}, }}, nil) -var singleSlotResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ +var singleSlotResp = newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 0}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.0.1"}, {typ: ':', integer: 0}, {typ: '+', string: ""}, @@ -148,11 +148,11 @@ var singleSlotResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ }}, }}, nil) -var singleSlotResp2 = newResult(RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ +var singleSlotResp2 = newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 0}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.3.1"}, {typ: ':', integer: 3}, {typ: '+', string: ""}, @@ -160,25 +160,25 @@ var singleSlotResp2 = newResult(RedisMessage{typ: '*', values: []RedisMessage{ }}, }}, nil) -var singleSlotWithoutIP = newResult(RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ +var singleSlotWithoutIP = newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 0}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: ""}, {typ: ':', integer: 4}, {typ: '+', string: ""}, }}, - {typ: '*', values: []RedisMessage{ // replica + {typ: '*', values: []ValkeyMessage{ // replica {typ: '+', string: "?"}, {typ: ':', integer: 1}, {typ: '+', string: ""}, }}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 0}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "?"}, {typ: ':', integer: 4}, {typ: '+', string: ""}, @@ -186,16 +186,16 @@ var singleSlotWithoutIP = newResult(RedisMessage{typ: '*', values: []RedisMessag }}, }}, nil) -var shardsResp = newResult(RedisMessage{typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ +var shardsResp = newResult(ValkeyMessage{typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ {typ: typeBlobString, string: "slots"}, - {typ: typeArray, values: []RedisMessage{ + {typ: typeArray, values: []ValkeyMessage{ {typ: typeBlobString, string: "0"}, {typ: typeBlobString, string: "16383"}, }}, {typ: typeBlobString, string: "nodes"}, - {typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ // master + {typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ // master {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -217,7 +217,7 @@ var shardsResp = newResult(RedisMessage{typ: typeArray, values: []RedisMessage{ {typ: typeBlobString, string: "health"}, {typ: typeBlobString, string: "online"}, }}, - {typ: typeMap, values: []RedisMessage{ // replica + {typ: typeMap, values: []ValkeyMessage{ // replica {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -243,16 +243,16 @@ var shardsResp = newResult(RedisMessage{typ: typeArray, values: []RedisMessage{ }}, }}, nil) -var shardsRespTls = newResult(RedisMessage{typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ +var shardsRespTls = newResult(ValkeyMessage{typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ {typ: typeBlobString, string: "slots"}, - {typ: typeArray, values: []RedisMessage{ + {typ: typeArray, values: []ValkeyMessage{ {typ: typeBlobString, string: "0"}, {typ: typeBlobString, string: "16383"}, }}, {typ: typeBlobString, string: "nodes"}, - {typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ // replica, tls + {typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ // replica, tls {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -274,7 +274,7 @@ var shardsRespTls = newResult(RedisMessage{typ: typeArray, values: []RedisMessag {typ: typeBlobString, string: "health"}, {typ: typeBlobString, string: "online"}, }}, - {typ: typeMap, values: []RedisMessage{ // master, tls + port + {typ: typeMap, values: []ValkeyMessage{ // master, tls + port {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -299,7 +299,7 @@ var shardsRespTls = newResult(RedisMessage{typ: typeArray, values: []RedisMessag {typ: typeBlobString, string: "health"}, {typ: typeBlobString, string: "online"}, }}, - {typ: typeMap, values: []RedisMessage{ // replica, port + {typ: typeMap, values: []ValkeyMessage{ // replica, port {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -325,16 +325,16 @@ var shardsRespTls = newResult(RedisMessage{typ: typeArray, values: []RedisMessag }}, }}, nil) -var shardsMultiResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ +var shardsMultiResp = newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ {typ: typeBlobString, string: "slots"}, - {typ: typeArray, values: []RedisMessage{ + {typ: typeArray, values: []ValkeyMessage{ {typ: typeBlobString, string: "0"}, {typ: typeBlobString, string: "8192"}, }}, {typ: typeBlobString, string: "nodes"}, - {typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ // master + {typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ // master {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -356,7 +356,7 @@ var shardsMultiResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ {typ: typeBlobString, string: "health"}, {typ: typeBlobString, string: "online"}, }}, - {typ: typeMap, values: []RedisMessage{ // replica + {typ: typeMap, values: []ValkeyMessage{ // replica {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -380,15 +380,15 @@ var shardsMultiResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ }}, }}, }}, - {typ: typeMap, values: []RedisMessage{ + {typ: typeMap, values: []ValkeyMessage{ {typ: typeBlobString, string: "slots"}, - {typ: typeArray, values: []RedisMessage{ + {typ: typeArray, values: []ValkeyMessage{ {typ: typeBlobString, string: "8193"}, {typ: typeBlobString, string: "16383"}, }}, {typ: typeBlobString, string: "nodes"}, - {typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ // master + {typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ // master {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -410,7 +410,7 @@ var shardsMultiResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ {typ: typeBlobString, string: "health"}, {typ: typeBlobString, string: "online"}, }}, - {typ: typeMap, values: []RedisMessage{ // replica + {typ: typeMap, values: []ValkeyMessage{ // replica {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -436,16 +436,16 @@ var shardsMultiResp = newResult(RedisMessage{typ: '*', values: []RedisMessage{ }}, }}, nil) -var singleShardResp2 = newResult(RedisMessage{typ: '*', values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ +var singleShardResp2 = newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ {typ: typeBlobString, string: "slots"}, - {typ: typeArray, values: []RedisMessage{ + {typ: typeArray, values: []ValkeyMessage{ {typ: typeBlobString, string: "0"}, {typ: typeBlobString, string: "0"}, }}, {typ: typeBlobString, string: "nodes"}, - {typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ // master + {typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ // master {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -471,16 +471,16 @@ var singleShardResp2 = newResult(RedisMessage{typ: '*', values: []RedisMessage{ }}, }}, nil) -var singleShardWithoutIP = newResult(RedisMessage{typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ +var singleShardWithoutIP = newResult(ValkeyMessage{typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ {typ: typeBlobString, string: "slots"}, - {typ: typeArray, values: []RedisMessage{ + {typ: typeArray, values: []ValkeyMessage{ {typ: typeBlobString, string: "0"}, {typ: typeBlobString, string: "0"}, }}, {typ: typeBlobString, string: "nodes"}, - {typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ // master + {typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ // master {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -502,7 +502,7 @@ var singleShardWithoutIP = newResult(RedisMessage{typ: typeArray, values: []Redi {typ: typeBlobString, string: "health"}, {typ: typeBlobString, string: "online"}, }}, - {typ: typeMap, values: []RedisMessage{ // replica + {typ: typeMap, values: []ValkeyMessage{ // replica {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -526,15 +526,15 @@ var singleShardWithoutIP = newResult(RedisMessage{typ: typeArray, values: []Redi }}, }}, }}, - {typ: typeMap, values: []RedisMessage{ + {typ: typeMap, values: []ValkeyMessage{ {typ: typeBlobString, string: "slots"}, - {typ: typeArray, values: []RedisMessage{ + {typ: typeArray, values: []ValkeyMessage{ {typ: typeBlobString, string: "0"}, {typ: typeBlobString, string: "0"}, }}, {typ: typeBlobString, string: "nodes"}, - {typ: typeArray, values: []RedisMessage{ - {typ: typeMap, values: []RedisMessage{ // master + {typ: typeArray, values: []ValkeyMessage{ + {typ: typeMap, values: []ValkeyMessage{ // master {typ: typeBlobString, string: "id"}, {typ: typeBlobString, string: ""}, @@ -581,7 +581,7 @@ func TestClusterClientInit(t *testing.T) { t.Run("Refresh err", func(t *testing.T) { v := errors.New("refresh err") if _, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { return newErrResult(v) }} + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return newErrResult(v) }} }); err != v { t.Fatalf("unexpected err %v", err) } @@ -591,9 +591,9 @@ func TestClusterClientInit(t *testing.T) { var first int64 if _, err := newClusterClient(&ClientOption{InitAddress: []string{"127.0.0.1:0", "127.0.1.1:1"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if atomic.AddInt64(&first, 1) == 1 { - return newResult(RedisMessage{typ: '*', values: []RedisMessage{}}, nil) + return newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{}}, nil) } return slotsResp }, @@ -607,9 +607,9 @@ func TestClusterClientInit(t *testing.T) { var first int64 if _, err := newClusterClient(&ClientOption{InitAddress: []string{"127.0.0.1:0", "127.0.1.1:1"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if atomic.AddInt64(&first, 1) == 1 { - return newResult(RedisMessage{typ: '*', values: []RedisMessage{}}, nil) + return newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{}}, nil) } return shardsResp }, @@ -623,8 +623,8 @@ func TestClusterClientInit(t *testing.T) { t.Run("Refresh no slots cluster", func(t *testing.T) { if _, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '*', values: []RedisMessage{}}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{}}, nil) }, } }); err != nil { @@ -635,8 +635,8 @@ func TestClusterClientInit(t *testing.T) { t.Run("Refresh no shards cluster", func(t *testing.T) { if _, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '*', values: []RedisMessage{}}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{}}, nil) }, VersionFn: func() int { return 7 }, } @@ -649,7 +649,7 @@ func TestClusterClientInit(t *testing.T) { getClient := func(version int) (client *clusterClient, err error) { return newClusterClient(&ClientOption{InitAddress: []string{"127.0.4.1:4"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return singleSlotWithoutIP } @@ -719,7 +719,7 @@ func TestClusterClientInit(t *testing.T) { var first int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{"127.0.1.1:1", "127.0.2.1:2"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if atomic.LoadInt64(&first) == 1 { return singleSlotResp2 } @@ -737,7 +737,7 @@ func TestClusterClientInit(t *testing.T) { var first int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{"127.0.1.1:1", "127.0.2.1:2"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if atomic.LoadInt64(&first) == 1 { return singleShardResp2 } @@ -756,7 +756,7 @@ func TestClusterClientInit(t *testing.T) { t.Run("Shards tls", func(t *testing.T) { client, err := newClusterClient(&ClientOption{InitAddress: []string{"127.0.0.1:0"}, TLSConfig: &tls.Config{}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return shardsRespTls }, VersionFn: func() int { return 7 }, @@ -780,7 +780,7 @@ func TestClusterClientInit(t *testing.T) { getClient := func(version int) (client *clusterClient, err error) { return newClusterClient(&ClientOption{InitAddress: []string{"xxxxx.amazonaws.com:1"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if dst == "xxxxx.amazonaws.com:1" && strings.Join(cmd.Commands(), " ") == "CLUSTER SHARDS" { return shardsResp } @@ -811,11 +811,11 @@ func TestClusterClientInit(t *testing.T) { t.Run("Refresh cluster which has only primary node per shard with SendToReplica option", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiRespWithoutReplicas } - return RedisResult{} + return ValkeyResult{} }, } @@ -863,18 +863,18 @@ func TestClusterClientInit(t *testing.T) { t.Run("Refresh cluster which has multi nodes per shard with SendToReplica option", func(t *testing.T) { primaryNodeConn := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } - return RedisResult{ + return ValkeyResult{ err: errors.New("unexpected call"), } }, } replicaNodeConn := &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{ + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{ err: errors.New("unexpected call"), } }, @@ -936,43 +936,43 @@ func TestClusterClientInit(t *testing.T) { func TestClusterClient(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } - return RedisResult{} + return ValkeyResult{} }, - DoStreamFn: func(cmd Completed) RedisResultStream { - return RedisResultStream{e: errors.New(cmd.Commands()[1])} + DoStreamFn: func(cmd Completed) ValkeyResultStream { + return ValkeyResultStream{e: errors.New(cmd.Commands()[1])} }, - DoMultiFn: func(multi ...Completed) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiFn: func(multi ...Completed) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, - DoMultiStreamFn: func(cmd ...Completed) MultiRedisResultStream { - return MultiRedisResultStream{e: errors.New(cmd[0].Commands()[1])} + DoMultiStreamFn: func(cmd ...Completed) MultiValkeyResultStream { + return MultiValkeyResultStream{e: errors.New(cmd[0].Commands()[1])} }, - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Cmd.Commands(), " ")}, nil) } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, - DoOverride: map[string]func(cmd Completed) RedisResult{ - "GET Do": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Do"}, nil) + DoOverride: map[string]func(cmd Completed) ValkeyResult{ + "GET Do": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Do"}, nil) }, - "INFO": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Info"}, nil) + "INFO": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Info"}, nil) }, }, - DoCacheOverride: map[string]func(cmd Cacheable, ttl time.Duration) RedisResult{ - "GET DoCache": func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '+', string: "DoCache"}, nil) + DoCacheOverride: map[string]func(cmd Cacheable, ttl time.Duration) ValkeyResult{ + "GET DoCache": func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "DoCache"}, nil) }, }, } @@ -1167,9 +1167,9 @@ func TestClusterClient(t *testing.T) { } }) - t.Run("Delegate Receive Redis Err", func(t *testing.T) { + t.Run("Delegate Receive Valkey Err", func(t *testing.T) { c := client.B().Subscribe().Channel("ch").Build() - e := &RedisError{} + e := &ValkeyError{} m.ReceiveFn = func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e } @@ -1218,11 +1218,11 @@ func TestClusterClient(t *testing.T) { }() m.AcquireFn = func() wire { return &mockWire{ - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}, nil), + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}, nil), }} }, } @@ -1262,8 +1262,8 @@ func TestClusterClient(t *testing.T) { } }) - t.Run("Dedicated Delegate Receive Redis Err", func(t *testing.T) { - e := &RedisError{} + t.Run("Dedicated Delegate Receive Valkey Err", func(t *testing.T) { + e := &ValkeyError{} w := &mockWire{ ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e @@ -1282,24 +1282,24 @@ func TestClusterClient(t *testing.T) { t.Run("Dedicated Delegate", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { if len(cmd) == 4 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "Delegate0"}, {typ: '+', string: "Delegate1"}, }}, nil), }} } - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "Delegate0"}, nil), - newResult(RedisMessage{typ: '+', string: "Delegate1"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "Delegate0"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Delegate1"}, nil), }} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { @@ -1390,24 +1390,24 @@ func TestClusterClient(t *testing.T) { t.Run("Dedicated Delegate", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { if len(cmd) == 4 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "Delegate0"}, {typ: '+', string: "Delegate1"}, }}, nil), }} } - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "Delegate0"}, nil), - newResult(RedisMessage{typ: '+', string: "Delegate1"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "Delegate0"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Delegate1"}, nil), }} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { @@ -1598,47 +1598,47 @@ func TestClusterClient_SendToOnlyPrimaryNodes(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) primaryNodeConn := &mockConn{ - DoOverride: map[string]func(cmd Completed) RedisResult{ - "CLUSTER SLOTS": func(cmd Completed) RedisResult { + DoOverride: map[string]func(cmd Completed) ValkeyResult{ + "CLUSTER SLOTS": func(cmd Completed) ValkeyResult { return slotsMultiResp }, - "GET Do": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET Do"}, nil) + "GET Do": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET Do"}, nil) }, - "GET K1{a}": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K1{a}"}, nil) + "GET K1{a}": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K1{a}"}, nil) }, - "GET K2{a}": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K2{a}"}, nil) + "GET K2{a}": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K2{a}"}, nil) }, - "INFO": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "INFO"}, nil) + "INFO": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "INFO"}, nil) }, }, - DoMultiFn: func(multi ...Completed) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiFn: func(multi ...Completed) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, - DoCacheOverride: map[string]func(cmd Cacheable, ttl time.Duration) RedisResult{ - "GET DoCache": func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET DoCache"}, nil) + DoCacheOverride: map[string]func(cmd Cacheable, ttl time.Duration) ValkeyResult{ + "GET DoCache": func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET DoCache"}, nil) }, - "GET K1{a}": func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K1{a}"}, nil) + "GET K1{a}": func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K1{a}"}, nil) }, - "GET K2{a}": func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K2{a}"}, nil) + "GET K2{a}": func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K2{a}"}, nil) }, }, - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Cmd.Commands(), " ")}, nil) } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, } replicaNodeConn := &mockConn{} @@ -1778,9 +1778,9 @@ func TestClusterClient_SendToOnlyPrimaryNodes(t *testing.T) { } }) - t.Run("Receive Redis Err", func(t *testing.T) { + t.Run("Receive Valkey Err", func(t *testing.T) { c := client.B().Subscribe().Channel("ch").Build() - e := &RedisError{} + e := &ValkeyError{} primaryNodeConn.ReceiveFn = func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e } @@ -1822,11 +1822,11 @@ func TestClusterClient_SendToOnlyPrimaryNodes(t *testing.T) { }() primaryNodeConn.AcquireFn = func() wire { return &mockWire{ - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}, nil), + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}, nil), }} }, } @@ -1866,8 +1866,8 @@ func TestClusterClient_SendToOnlyPrimaryNodes(t *testing.T) { } }) - t.Run("Dedicated Receive Redis Err", func(t *testing.T) { - e := &RedisError{} + t.Run("Dedicated Receive Valkey Err", func(t *testing.T) { + e := &ValkeyError{} w := &mockWire{ ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e @@ -1886,24 +1886,24 @@ func TestClusterClient_SendToOnlyPrimaryNodes(t *testing.T) { t.Run("Dedicated", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { if len(cmd) == 4 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "Delegate0"}, {typ: '+', string: "Delegate1"}, }}, nil), }} } - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "Delegate0"}, nil), - newResult(RedisMessage{typ: '+', string: "Delegate1"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "Delegate0"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Delegate1"}, nil), }} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { @@ -1994,24 +1994,24 @@ func TestClusterClient_SendToOnlyPrimaryNodes(t *testing.T) { t.Run("Dedicate", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { if len(cmd) == 4 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "Delegate0"}, {typ: '+', string: "Delegate1"}, }}, nil), }} } - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "Delegate0"}, nil), - newResult(RedisMessage{typ: '+', string: "Delegate1"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "Delegate0"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Delegate1"}, nil), }} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { @@ -2103,47 +2103,47 @@ func TestClusterClient_SendToOnlyReplicaNodes(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) primaryNodeConn := &mockConn{ - DoOverride: map[string]func(cmd Completed) RedisResult{ - "CLUSTER SLOTS": func(cmd Completed) RedisResult { + DoOverride: map[string]func(cmd Completed) ValkeyResult{ + "CLUSTER SLOTS": func(cmd Completed) ValkeyResult { return slotsMultiResp }, - "INFO": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "INFO"}, nil) + "INFO": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "INFO"}, nil) }, - "GET K1{a}": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K1{a}"}, nil) + "GET K1{a}": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K1{a}"}, nil) }, }, } replicaNodeConn := &mockConn{ - DoMultiFn: func(multi ...Completed) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiFn: func(multi ...Completed) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Cmd.Commands(), " ")}, nil) } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, - DoOverride: map[string]func(cmd Completed) RedisResult{ - "GET Do": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET Do"}, nil) + DoOverride: map[string]func(cmd Completed) ValkeyResult{ + "GET Do": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET Do"}, nil) }, - "GET K1{a}": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K1{a}"}, nil) + "GET K1{a}": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K1{a}"}, nil) }, - "GET K2{a}": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K2{a}"}, nil) + "GET K2{a}": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K2{a}"}, nil) }, }, - DoCacheOverride: map[string]func(cmd Cacheable, ttl time.Duration) RedisResult{ - "GET DoCache": func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET DoCache"}, nil) + DoCacheOverride: map[string]func(cmd Cacheable, ttl time.Duration) ValkeyResult{ + "GET DoCache": func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET DoCache"}, nil) }, }, } @@ -2282,9 +2282,9 @@ func TestClusterClient_SendToOnlyReplicaNodes(t *testing.T) { } }) - t.Run("Receive Redis Err", func(t *testing.T) { + t.Run("Receive Valkey Err", func(t *testing.T) { c := client.B().Ssubscribe().Channel("ch").Build() - e := &RedisError{} + e := &ValkeyError{} primaryNodeConn.ReceiveFn = func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e } @@ -2317,11 +2317,11 @@ func TestClusterClient_SendToOnlyReplicaNodes(t *testing.T) { }() primaryNodeConn.AcquireFn = func() wire { return &mockWire{ - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}, nil), + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}, nil), }} }, } @@ -2361,8 +2361,8 @@ func TestClusterClient_SendToOnlyReplicaNodes(t *testing.T) { } }) - t.Run("Dedicated Receive Redis Err", func(t *testing.T) { - e := &RedisError{} + t.Run("Dedicated Receive Valkey Err", func(t *testing.T) { + e := &ValkeyError{} w := &mockWire{ ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e @@ -2381,24 +2381,24 @@ func TestClusterClient_SendToOnlyReplicaNodes(t *testing.T) { t.Run("Dedicated", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { if len(cmd) == 4 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "Delegate0"}, {typ: '+', string: "Delegate1"}, }}, nil), }} } - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "Delegate0"}, nil), - newResult(RedisMessage{typ: '+', string: "Delegate1"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "Delegate0"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Delegate1"}, nil), }} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { @@ -2489,24 +2489,24 @@ func TestClusterClient_SendToOnlyReplicaNodes(t *testing.T) { t.Run("Dedicate", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { if len(cmd) == 4 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "Delegate0"}, {typ: '+', string: "Delegate1"}, }}, nil), }} } - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "Delegate0"}, nil), - newResult(RedisMessage{typ: '+', string: "Delegate1"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "Delegate0"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Delegate1"}, nil), }} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { @@ -2598,97 +2598,97 @@ func TestClusterClient_SendReadOperationToReplicaNodesWriteOperationToPrimaryNod defer ShouldNotLeaked(SetupLeakDetection()) primaryNodeConn := &mockConn{ - DoOverride: map[string]func(cmd Completed) RedisResult{ - "CLUSTER SLOTS": func(cmd Completed) RedisResult { + DoOverride: map[string]func(cmd Completed) ValkeyResult{ + "CLUSTER SLOTS": func(cmd Completed) ValkeyResult { return slotsMultiResp }, - "INFO": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "INFO"}, nil) + "INFO": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "INFO"}, nil) }, - "SET Do V": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "SET Do V"}, nil) + "SET Do V": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "SET Do V"}, nil) }, - "SET K2{a} V2{a}": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "SET K2{a} V2{a}"}, nil) + "SET K2{a} V2{a}": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "SET K2{a} V2{a}"}, nil) }, }, - DoMultiFn: func(multi ...Completed) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiFn: func(multi ...Completed) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { if strings.HasPrefix(strings.Join(cmd.Commands(), " "), "SET K1") { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) continue } if strings.HasPrefix(strings.Join(cmd.Commands(), " "), "SET K2") { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) continue } if strings.HasPrefix(strings.Join(cmd.Commands(), " "), "MULTI") { - resps[i] = newResult(RedisMessage{typ: '+', string: "MULTI"}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: "MULTI"}, nil) continue } if strings.HasPrefix(strings.Join(cmd.Commands(), " "), "EXEC") { - resps[i] = newResult(RedisMessage{typ: '+', string: "EXEC"}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: "EXEC"}, nil) continue } - return &redisresults{ - s: []RedisResult{}, + return &valkeyresults{ + s: []ValkeyResult{}, } } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, } replicaNodeConn := &mockConn{ - DoOverride: map[string]func(cmd Completed) RedisResult{ - "GET Do": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET Do"}, nil) + DoOverride: map[string]func(cmd Completed) ValkeyResult{ + "GET Do": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET Do"}, nil) }, - "GET K1{a}": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K1{a}"}, nil) + "GET K1{a}": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K1{a}"}, nil) }, - "GET K2{a}": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K2{a}"}, nil) + "GET K2{a}": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K2{a}"}, nil) }, }, - DoMultiFn: func(multi ...Completed) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiFn: func(multi ...Completed) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { if strings.HasPrefix(strings.Join(cmd.Commands(), " "), "GET K1") { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Commands(), " ")}, nil) continue } - return &redisresults{ - s: []RedisResult{}, + return &valkeyresults{ + s: []ValkeyResult{}, } } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, - DoCacheOverride: map[string]func(cmd Cacheable, ttl time.Duration) RedisResult{ - "GET DoCache": func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET DoCache"}, nil) + DoCacheOverride: map[string]func(cmd Cacheable, ttl time.Duration) ValkeyResult{ + "GET DoCache": func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET DoCache"}, nil) }, - "GET K1{a}": func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K1{a}"}, nil) + "GET K1{a}": func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K1{a}"}, nil) }, - "GET K2{a}": func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '+', string: "GET K2{a}"}, nil) + "GET K2{a}": func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "GET K2{a}"}, nil) }, }, - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { if strings.HasPrefix(strings.Join(cmd.Cmd.Commands(), " "), "GET K1") { - resps[i] = newResult(RedisMessage{typ: '+', string: strings.Join(cmd.Cmd.Commands(), " ")}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: strings.Join(cmd.Cmd.Commands(), " ")}, nil) continue } - return &redisresults{ - s: []RedisResult{}, + return &valkeyresults{ + s: []ValkeyResult{}, } } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, } @@ -2878,9 +2878,9 @@ func TestClusterClient_SendReadOperationToReplicaNodesWriteOperationToPrimaryNod } }) - t.Run("Receive Redis Err", func(t *testing.T) { + t.Run("Receive Valkey Err", func(t *testing.T) { c := client.B().Ssubscribe().Channel("ch").Build() - e := &RedisError{} + e := &ValkeyError{} primaryNodeConn.ReceiveFn = func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e } @@ -2913,11 +2913,11 @@ func TestClusterClient_SendReadOperationToReplicaNodesWriteOperationToPrimaryNod }() primaryNodeConn.AcquireFn = func() wire { return &mockWire{ - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}, nil), + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}, nil), }} }, } @@ -2957,8 +2957,8 @@ func TestClusterClient_SendReadOperationToReplicaNodesWriteOperationToPrimaryNod } }) - t.Run("Dedicated Receive Redis Err", func(t *testing.T) { - e := &RedisError{} + t.Run("Dedicated Receive Valkey Err", func(t *testing.T) { + e := &ValkeyError{} w := &mockWire{ ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e @@ -2977,24 +2977,24 @@ func TestClusterClient_SendReadOperationToReplicaNodesWriteOperationToPrimaryNod t.Run("Dedicated", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { if len(cmd) == 4 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "Delegate0"}, {typ: '+', string: "Delegate1"}, }}, nil), }} } - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "Delegate0"}, nil), - newResult(RedisMessage{typ: '+', string: "Delegate1"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "Delegate0"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Delegate1"}, nil), }} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { @@ -3085,24 +3085,24 @@ func TestClusterClient_SendReadOperationToReplicaNodesWriteOperationToPrimaryNod t.Run("Dedicate", func(t *testing.T) { closed := false w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { if len(cmd) == 4 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '+', string: "OK"}, nil), - newResult(RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '+', string: "OK"}, nil), + newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "Delegate0"}, {typ: '+', string: "Delegate1"}, }}, nil), }} } - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "Delegate0"}, nil), - newResult(RedisMessage{typ: '+', string: "Delegate1"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "Delegate0"}, nil), + newResult(ValkeyMessage{typ: '+', string: "Delegate1"}, nil), }} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { @@ -3194,31 +3194,31 @@ func TestClusterClient_SendPrimaryNodeOnlyButOneSlotAssigned(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) primaryNodeConn := &mockConn{ - DoOverride: map[string]func(cmd Completed) RedisResult{ - "CLUSTER SLOTS": func(cmd Completed) RedisResult { + DoOverride: map[string]func(cmd Completed) ValkeyResult{ + "CLUSTER SLOTS": func(cmd Completed) ValkeyResult { return singleSlotResp }, - "INFO": func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "INFO"}, nil) + "INFO": func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "INFO"}, nil) }, }, - DoMultiFn: func(multi ...Completed) *redisresults { - resps := make([]RedisResult, len(multi)) + DoMultiFn: func(multi ...Completed) *valkeyresults { + resps := make([]ValkeyResult, len(multi)) for i, cmd := range multi { if strings.HasPrefix(strings.Join(cmd.Commands(), " "), "MULTI") { - resps[i] = newResult(RedisMessage{typ: '+', string: "MULTI"}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: "MULTI"}, nil) continue } if strings.HasPrefix(strings.Join(cmd.Commands(), " "), "EXEC") { - resps[i] = newResult(RedisMessage{typ: '+', string: "EXEC"}, nil) + resps[i] = newResult(ValkeyMessage{typ: '+', string: "EXEC"}, nil) continue } - return &redisresults{ - s: []RedisResult{}, + return &valkeyresults{ + s: []ValkeyResult{}, } } - return &redisresults{s: resps} + return &valkeyresults{s: resps} }, } @@ -3267,35 +3267,35 @@ func TestClusterClientErr(t *testing.T) { cancel() v := ctx.Err() m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { atomic.AddInt64(&count, 1) return slotsResp } return newErrResult(v) }, - DoStreamFn: func(cmd Completed) RedisResultStream { - return RedisResultStream{e: v} + DoStreamFn: func(cmd Completed) ValkeyResultStream { + return ValkeyResultStream{e: v} }, - DoMultiFn: func(multi ...Completed) *redisresults { - res := make([]RedisResult, len(multi)) + DoMultiFn: func(multi ...Completed) *valkeyresults { + res := make([]ValkeyResult, len(multi)) for i := range res { res[i] = newErrResult(v) } - return &redisresults{s: res} + return &valkeyresults{s: res} }, - DoMultiStreamFn: func(cmd ...Completed) MultiRedisResultStream { - return MultiRedisResultStream{e: v} + DoMultiStreamFn: func(cmd ...Completed) MultiValkeyResultStream { + return MultiValkeyResultStream{e: v} }, - DoCacheFn: func(cmd Cacheable, ttl time.Duration) RedisResult { + DoCacheFn: func(cmd Cacheable, ttl time.Duration) ValkeyResult { return newErrResult(v) }, - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - res := make([]RedisResult, len(multi)) + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + res := make([]ValkeyResult, len(multi)) for i := range res { res[i] = newErrResult(v) } - return &redisresults{s: res} + return &valkeyresults{s: res} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return v @@ -3337,7 +3337,7 @@ func TestClusterClientErr(t *testing.T) { var first int64 v := errors.New("refresh err") m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if atomic.AddInt64(&first, 1) == 1 { return singleSlotResp } @@ -3387,7 +3387,7 @@ func TestClusterClientErr(t *testing.T) { }) t.Run("refresh empty on pick", func(t *testing.T) { - m := &mockConn{DoFn: func(cmd Completed) RedisResult { + m := &mockConn{DoFn: func(cmd Completed) ValkeyResult { return singleSlotResp }} client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { @@ -3418,7 +3418,7 @@ func TestClusterClientErr(t *testing.T) { }) t.Run("refresh empty on pick in dedicated wire", func(t *testing.T) { - m := &mockConn{DoFn: func(cmd Completed) RedisResult { + m := &mockConn{DoFn: func(cmd Completed) ValkeyResult { return singleSlotResp }} client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { @@ -3440,7 +3440,7 @@ func TestClusterClientErr(t *testing.T) { }) t.Run("refresh empty on pick in dedicated wire (multi)", func(t *testing.T) { - m := &mockConn{DoFn: func(cmd Completed) RedisResult { + m := &mockConn{DoFn: func(cmd Completed) ValkeyResult { return singleSlotResp }} client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { @@ -3470,14 +3470,14 @@ func TestClusterClientErr(t *testing.T) { var count, check int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { atomic.AddInt64(&check, 1) - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } if atomic.AddInt64(&count, 1) <= 3 { - return newResult(RedisMessage{typ: '-', string: "MOVED 0 :0"}, nil) + return newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :0"}, nil) } - return newResult(RedisMessage{typ: '+', string: "b"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "b"}, nil) }} }) if err != nil { @@ -3494,14 +3494,14 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot moved", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } if atomic.AddInt64(&count, 1) <= 3 { - return newResult(RedisMessage{typ: '-', string: "MOVED 0 :1"}, nil) + return newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :1"}, nil) } - return newResult(RedisMessage{typ: '+', string: "b"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "b"}, nil) }} }) if err != nil { @@ -3515,20 +3515,20 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot moved DoMulti (single)", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiFn: func(multi ...Completed) *redisresults { - ret := make([]RedisResult, len(multi)) + }, DoMultiFn: func(multi ...Completed) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 3 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "MOVED 0 :1"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :1"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := range ret { - ret[i] = newResult(RedisMessage{typ: '+', string: multi[i].Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: multi[i].Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }} }) if err != nil { @@ -3542,20 +3542,20 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot moved DoMulti (multi)", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiFn: func(multi ...Completed) *redisresults { - ret := make([]RedisResult, len(multi)) + }, DoMultiFn: func(multi ...Completed) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 3 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "MOVED 0 :1"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :1"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := range ret { - ret[i] = newResult(RedisMessage{typ: '+', string: multi[i].Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: multi[i].Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }} }) if err != nil { @@ -3575,20 +3575,20 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot moved DoMulti (multi) TRYAGAIN", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiFn: func(multi ...Completed) *redisresults { - ret := make([]RedisResult, len(multi)) + }, DoMultiFn: func(multi ...Completed) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 2 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "TRYAGAIN"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "TRYAGAIN"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := range ret { - ret[i] = newResult(RedisMessage{typ: '+', string: multi[i].Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: multi[i].Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }} }) if err != nil { @@ -3609,14 +3609,14 @@ func TestClusterClientErr(t *testing.T) { if dst == ":2" { atomic.AddInt64(&check, 1) } - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } if atomic.AddInt64(&count, 1) <= 3 { - return newResult(RedisMessage{typ: '-', string: "MOVED 0 :2"}, nil) + return newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :2"}, nil) } - return newResult(RedisMessage{typ: '+', string: "b"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "b"}, nil) }} }) @@ -3637,20 +3637,20 @@ func TestClusterClientErr(t *testing.T) { if dst == ":2" { atomic.AddInt64(&check, 1) } - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiFn: func(multi ...Completed) *redisresults { - ret := make([]RedisResult, len(multi)) + }, DoMultiFn: func(multi ...Completed) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 3 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "MOVED 0 :2"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :2"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := range ret { - ret[i] = newResult(RedisMessage{typ: '+', string: multi[i].Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: multi[i].Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }} }) if err != nil { @@ -3670,20 +3670,20 @@ func TestClusterClientErr(t *testing.T) { if dst == ":2" { atomic.AddInt64(&check, 1) } - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiFn: func(multi ...Completed) *redisresults { - ret := make([]RedisResult, len(multi)) + }, DoMultiFn: func(multi ...Completed) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 3 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "MOVED 0 :2"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :2"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := range ret { - ret[i] = newResult(RedisMessage{typ: '+', string: multi[i].Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: multi[i].Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }} }) if err != nil { @@ -3706,20 +3706,20 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot moved new (multi 2) TRYAGAIN", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiFn: func(multi ...Completed) *redisresults { - ret := make([]RedisResult, len(multi)) + }, DoMultiFn: func(multi ...Completed) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 2 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "TRYAGAIN"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "TRYAGAIN"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := range ret { - ret[i] = newResult(RedisMessage{typ: '+', string: multi[i].Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: multi[i].Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }} }) if err != nil { @@ -3738,14 +3738,14 @@ func TestClusterClientErr(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp }, - DoCacheFn: func(cmd Cacheable, ttl time.Duration) RedisResult { + DoCacheFn: func(cmd Cacheable, ttl time.Duration) ValkeyResult { if atomic.AddInt64(&count, 1) <= 3 { - return newResult(RedisMessage{typ: '-', string: "MOVED 0 :1"}, nil) + return newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :1"}, nil) } - return newResult(RedisMessage{typ: '+', string: "b"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "b"}, nil) }, } }) @@ -3760,20 +3760,20 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot moved (cache multi 1)", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - ret := make([]RedisResult, len(multi)) + }, DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 3 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "MOVED 0 :1"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :1"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := range ret { - ret[i] = newResult(RedisMessage{typ: '+', string: multi[i].Cmd.Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: multi[i].Cmd.Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }} }) if err != nil { @@ -3787,20 +3787,20 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot moved (cache multi 2)", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - ret := make([]RedisResult, len(multi)) + }, DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 3 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "MOVED 0 :1"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "MOVED 0 :1"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := range ret { - ret[i] = newResult(RedisMessage{typ: '+', string: multi[i].Cmd.Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: multi[i].Cmd.Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }} }) if err != nil { @@ -3821,17 +3821,17 @@ func TestClusterClientErr(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } - return newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil) + return newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil) }, - DoMultiFn: func(multi ...Completed) *redisresults { + DoMultiFn: func(multi ...Completed) *valkeyresults { if atomic.AddInt64(&count, 1) <= 3 { - return &redisresults{s: []RedisResult{{}, newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil)}} + return &valkeyresults{s: []ValkeyResult{{}, newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil)}} } - return &redisresults{s: []RedisResult{{}, newResult(RedisMessage{typ: '+', string: "b"}, nil)}} + return &valkeyresults{s: []ValkeyResult{{}, newResult(ValkeyMessage{typ: '+', string: "b"}, nil)}} }, } }) @@ -3847,22 +3847,22 @@ func TestClusterClientErr(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp }, - DoMultiFn: func(multi ...Completed) *redisresults { - ret := make([]RedisResult, len(multi)) + DoMultiFn: func(multi ...Completed) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 3 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := 0; i < len(multi); i += 2 { - ret[i] = newResult(RedisMessage{typ: '+', string: "OK"}, nil) - ret[i+1] = newResult(RedisMessage{typ: '+', string: multi[i+1].Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) + ret[i+1] = newResult(ValkeyMessage{typ: '+', string: multi[i+1].Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }, } }) @@ -3878,22 +3878,22 @@ func TestClusterClientErr(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp }, - DoMultiFn: func(multi ...Completed) *redisresults { - ret := make([]RedisResult, len(multi)) + DoMultiFn: func(multi ...Completed) *valkeyresults { + ret := make([]ValkeyResult, len(multi)) if atomic.AddInt64(&count, 1) <= 3 { for i := range ret { - ret[i] = newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil) + ret[i] = newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} } for i := 0; i < len(multi); i += 2 { - ret[i] = newResult(RedisMessage{typ: '+', string: "OK"}, nil) - ret[i+1] = newResult(RedisMessage{typ: '+', string: multi[i+1].Commands()[1]}, nil) + ret[i] = newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) + ret[i+1] = newResult(ValkeyMessage{typ: '+', string: multi[i+1].Commands()[1]}, nil) } - return &redisresults{s: ret} + return &valkeyresults{s: ret} }, } }) @@ -3915,17 +3915,17 @@ func TestClusterClientErr(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp }, - DoCacheFn: func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil) + DoCacheFn: func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil) }, - DoMultiFn: func(multi ...Completed) *redisresults { + DoMultiFn: func(multi ...Completed) *valkeyresults { if atomic.AddInt64(&count, 1) <= 3 { - return &redisresults{s: []RedisResult{{}, {}, {}, {}, {}, newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil)}} + return &valkeyresults{s: []ValkeyResult{{}, {}, {}, {}, {}, newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil)}} } - return &redisresults{s: []RedisResult{{}, {}, {}, {}, {}, newResult(RedisMessage{typ: '*', values: []RedisMessage{{}, {typ: '+', string: "b"}}}, nil)}} + return &valkeyresults{s: []ValkeyResult{{}, {}, {}, {}, {}, newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{}, {typ: '+', string: "b"}}}, nil)}} }, } }) @@ -3941,17 +3941,17 @@ func TestClusterClientErr(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp }, - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil)}} + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil)}} }, - DoMultiFn: func(multi ...Completed) *redisresults { + DoMultiFn: func(multi ...Completed) *valkeyresults { if atomic.AddInt64(&count, 1) <= 3 { - return &redisresults{s: []RedisResult{{}, {}, {}, {}, {}, newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil)}} + return &valkeyresults{s: []ValkeyResult{{}, {}, {}, {}, {}, newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil)}} } - return &redisresults{s: []RedisResult{{}, {}, {}, {}, {}, newResult(RedisMessage{typ: '*', values: []RedisMessage{{}, {typ: '+', string: "b"}}}, nil)}} + return &valkeyresults{s: []ValkeyResult{{}, {}, {}, {}, {}, newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{}, {typ: '+', string: "b"}}}, nil)}} }, } }) @@ -3967,22 +3967,22 @@ func TestClusterClientErr(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp }, - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil)}} + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil)}} }, - DoMultiFn: func(multi ...Completed) *redisresults { + DoMultiFn: func(multi ...Completed) *valkeyresults { if atomic.AddInt64(&count, 1) <= 3 { - return &redisresults{s: []RedisResult{ - {}, {}, {}, {}, {}, newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil), - {}, {}, {}, {}, {}, newResult(RedisMessage{typ: '-', string: "ASK 0 :1"}, nil), + return &valkeyresults{s: []ValkeyResult{ + {}, {}, {}, {}, {}, newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil), + {}, {}, {}, {}, {}, newResult(ValkeyMessage{typ: '-', string: "ASK 0 :1"}, nil), }} } - return &redisresults{s: []RedisResult{ - {}, {}, {}, {}, {}, newResult(RedisMessage{typ: '*', values: []RedisMessage{{}, {}, {typ: '+', string: multi[4].Commands()[1]}}}, nil), - {}, {}, {}, {}, {}, newResult(RedisMessage{typ: '*', values: []RedisMessage{{}, {}, {typ: '+', string: multi[10].Commands()[1]}}}, nil), + return &valkeyresults{s: []ValkeyResult{ + {}, {}, {}, {}, {}, newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{}, {}, {typ: '+', string: multi[4].Commands()[1]}}}, nil), + {}, {}, {}, {}, {}, newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{}, {}, {typ: '+', string: multi[10].Commands()[1]}}}, nil), }} }, } @@ -4004,14 +4004,14 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot try again", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } if atomic.AddInt64(&count, 1) <= 3 { - return newResult(RedisMessage{typ: '-', string: "TRYAGAIN"}, nil) + return newResult(ValkeyMessage{typ: '-', string: "TRYAGAIN"}, nil) } - return newResult(RedisMessage{typ: '+', string: "b"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "b"}, nil) }} }) if err != nil { @@ -4025,15 +4025,15 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot try again DoMulti 1", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiFn: func(multi ...Completed) *redisresults { + }, DoMultiFn: func(multi ...Completed) *valkeyresults { if atomic.AddInt64(&count, 1) <= 3 { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '-', string: "TRYAGAIN"}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '-', string: "TRYAGAIN"}, nil)}} } - ret := make([]RedisResult, len(multi)) - ret[0] = newResult(RedisMessage{typ: '+', string: "b"}, nil) - return &redisresults{s: ret} + ret := make([]ValkeyResult, len(multi)) + ret[0] = newResult(ValkeyMessage{typ: '+', string: "b"}, nil) + return &valkeyresults{s: ret} }} }) if err != nil { @@ -4047,15 +4047,15 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot try again DoMulti 2", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiFn: func(multi ...Completed) *redisresults { + }, DoMultiFn: func(multi ...Completed) *valkeyresults { if atomic.AddInt64(&count, 1) <= 3 { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '-', string: "TRYAGAIN"}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '-', string: "TRYAGAIN"}, nil)}} } - ret := make([]RedisResult, len(multi)) - ret[0] = newResult(RedisMessage{typ: '+', string: multi[0].Commands()[1]}, nil) - return &redisresults{s: ret} + ret := make([]ValkeyResult, len(multi)) + ret[0] = newResult(ValkeyMessage{typ: '+', string: multi[0].Commands()[1]}, nil) + return &valkeyresults{s: ret} }} }) if err != nil { @@ -4076,14 +4076,14 @@ func TestClusterClientErr(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp }, - DoCacheFn: func(cmd Cacheable, ttl time.Duration) RedisResult { + DoCacheFn: func(cmd Cacheable, ttl time.Duration) ValkeyResult { if atomic.AddInt64(&count, 1) <= 3 { - return newResult(RedisMessage{typ: '-', string: "TRYAGAIN"}, nil) + return newResult(ValkeyMessage{typ: '-', string: "TRYAGAIN"}, nil) } - return newResult(RedisMessage{typ: '+', string: "b"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "b"}, nil) }, } }) @@ -4098,13 +4098,13 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot try again (cache multi 1)", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { return slotsMultiResp - }, DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { + }, DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { if atomic.AddInt64(&count, 1) <= 3 { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '-', string: "TRYAGAIN"}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '-', string: "TRYAGAIN"}, nil)}} } - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "b"}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "b"}, nil)}} }} }) if err != nil { @@ -4118,16 +4118,16 @@ func TestClusterClientErr(t *testing.T) { t.Run("slot try again (cache multi 2)", func(t *testing.T) { var count int64 client, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { - return &mockConn{DoFn: func(cmd Completed) RedisResult { + return &mockConn{DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } return shardsMultiResp - }, DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { + }, DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { if atomic.AddInt64(&count, 1) <= 3 { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '-', string: "TRYAGAIN"}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '-', string: "TRYAGAIN"}, nil)}} } - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: multi[0].Cmd.Commands()[1]}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: multi[0].Cmd.Commands()[1]}, nil)}} }} }) if err != nil { @@ -4148,8 +4148,8 @@ func TestClusterClientErr(t *testing.T) { func TestClusterClientRetry(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) SetupClientRetry(t, func(m *mockConn) Client { - m.DoOverride = map[string]func(cmd Completed) RedisResult{ - "CLUSTER SLOTS": func(cmd Completed) RedisResult { return slotsMultiResp }, + m.DoOverride = map[string]func(cmd Completed) ValkeyResult{ + "CLUSTER SLOTS": func(cmd Completed) ValkeyResult { return slotsMultiResp }, } c, err := newClusterClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return m @@ -4164,11 +4164,11 @@ func TestClusterClientRetry(t *testing.T) { func TestClusterClientReplicaOnly_PickReplica(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } - return RedisResult{} + return ValkeyResult{} }, } @@ -4199,11 +4199,11 @@ func TestClusterClientReplicaOnly_PickMasterIfNoReplica(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) t.Run("replicas should be picked", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiResp } - return RedisResult{} + return ValkeyResult{} }, } @@ -4231,11 +4231,11 @@ func TestClusterClientReplicaOnly_PickMasterIfNoReplica(t *testing.T) { t.Run("distributed to replicas", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if strings.Join(cmd.Commands(), " ") == "CLUSTER SLOTS" { return slotsMultiRespWithMultiReplicas } - return RedisResult{} + return ValkeyResult{} }, } diff --git a/cmds.go b/cmds.go index ce5ab6a..b702156 100644 --- a/cmds.go +++ b/cmds.go @@ -1,17 +1,17 @@ -package rueidis +package valkey -import "github.com/redis/rueidis/internal/cmds" +import "github.com/rueian/valkey-go/internal/cmds" // Builder represents a command builder. It should only be created from the client.B() method. type Builder = cmds.Builder -// Incomplete represents an incomplete Redis command. It should then be completed by calling the Build(). +// Incomplete represents an incomplete Valkey command. It should then be completed by calling the Build(). type Incomplete = cmds.Incomplete -// Completed represents a completed Redis command. It should only be created from the Build() of a command builder. +// Completed represents a completed Valkey command. It should only be created from the Build() of a command builder. type Completed = cmds.Completed -// Cacheable represents a completed Redis command which supports server-assisted client side caching, +// Cacheable represents a completed Valkey command which supports server-assisted client side caching, // and it should be created by the Cache() of command builder. type Cacheable = cmds.Cacheable @@ -21,7 +21,7 @@ type Cacheable = cmds.Cacheable // c, release := client.Dedicate() // defer release() // -// cmds := make(rueidis.Commands, 0, 10) +// cmds := make(valkey.Commands, 0, 10) // for i := 0; i < 10; i++ { // cmds = append(cmds, c.B().Set().Key(strconv.Itoa(i)).Value(strconv.Itoa(i)).Build()) // } diff --git a/docker-compose.yml b/docker-compose.yml index 7e71b78..ac761cd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,12 +1,12 @@ version: "3.8" services: - redis: - image: redis:7.2-rc-alpine + valkey: + image: valkey/valkey:7.2-alpine ports: - "6379:6379" - redislock: - image: redis:7.2-rc-alpine + valkeylock: + image: valkey/valkey:7.2-alpine ports: - "6376:6379" redis5: @@ -18,11 +18,11 @@ services: ports: - "6344:6379" dragonflydb: - image: docker.dragonflydb.io/dragonflydb/dragonfly:v1.4.0 + image: docker.dragonflydb.io/dragonflydb/dragonfly:v1.17.1 ports: - "6333:6379" kvrocks: - image: apache/kvrocks:2.2.0 + image: apache/kvrocks:2.8.0 ports: - "6666:6666" redisearch: @@ -38,14 +38,14 @@ services: ports: - "6356:6379" sentinel: - image: redis:7.2-rc-alpine + image: valkey/valkey:7.2-alpine entrypoint: - /bin/sh - -c - | - redis-server --save "" --appendonly no --port 6380 & + valkey-server --save "" --appendonly no --port 6380 & echo "sentinel monitor test 127.0.0.1 6380 2\n" > sentinel.conf - redis-server sentinel.conf --sentinel + valkey-server sentinel.conf --sentinel ports: - "6380:6380" - "26379:26379" @@ -62,15 +62,15 @@ services: - "6385:6385" - "26355:26379" cluster: - image: redis:7.2-rc-alpine + image: valkey/valkey:7.2-alpine entrypoint: - /bin/sh - -c - | - redis-server --port 7001 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7001.conf & - redis-server --port 7002 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7002.conf & - redis-server --port 7003 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7003.conf & - while ! redis-cli --cluster create 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 --cluster-yes; do sleep 1; done + valkey-server --port 7001 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7001.conf & + valkey-server --port 7002 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7002.conf & + valkey-server --port 7003 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7003.conf & + while ! valkey-cli --cluster create 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 --cluster-yes; do sleep 1; done wait ports: - "7001:7001" @@ -107,15 +107,15 @@ services: - "7008:7008" - "7009:7009" clusteradapter: - image: redis:7.2-rc-alpine + image: valkey/valkey:7.2-alpine entrypoint: - /bin/sh - -c - | - redis-server --port 7010 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7010.conf & - redis-server --port 7011 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7011.conf & - redis-server --port 7012 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7012.conf & - while ! redis-cli --cluster create 127.0.0.1:7010 127.0.0.1:7011 127.0.0.1:7012 --cluster-yes; do sleep 1; done + valkey-server --port 7010 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7010.conf & + valkey-server --port 7011 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7011.conf & + valkey-server --port 7012 --save "" --appendonly no --cluster-enabled yes --cluster-config-file 7012.conf & + while ! valkey-cli --cluster create 127.0.0.1:7010 127.0.0.1:7011 127.0.0.1:7012 --cluster-yes; do sleep 1; done wait ports: - "7010:7010" diff --git a/go.mod b/go.mod index 0caeefa..da3a1bc 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,10 @@ -module github.com/redis/rueidis +module github.com/rueian/valkey-go go 1.20 require ( github.com/onsi/gomega v1.31.1 - golang.org/x/sys v0.17.0 + golang.org/x/sys v0.19.0 ) require ( @@ -12,7 +12,7 @@ require ( github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect github.com/kr/pretty v0.1.0 // indirect github.com/kr/text v0.2.0 // indirect - golang.org/x/net v0.19.0 // indirect + golang.org/x/net v0.24.0 // indirect golang.org/x/text v0.14.0 // indirect gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index dbb186f..677b531 100644 --- a/go.sum +++ b/go.sum @@ -14,10 +14,10 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/onsi/ginkgo/v2 v2.15.0 h1:79HwNRBAZHOEwrczrgSOPy+eFTTlIGELKy5as+ClttY= github.com/onsi/gomega v1.31.1 h1:KYppCUK+bUgAZwHOu7EXVBKyQA6ILvOESHkn/tgoqvo= github.com/onsi/gomega v1.31.1/go.mod h1:y40C95dwAD1Nz36SsEnxvfFe8FFfNxzI5eJ0EYGyAy0= -golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= -golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= -golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= -golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA= diff --git a/hack/cmds/commands.json b/hack/cmds/commands.json index d1e2e69..a1b2784 100644 --- a/hack/cmds/commands.json +++ b/hack/cmds/commands.json @@ -151,7 +151,7 @@ }, "APPEND": { "summary": "Append a value to a key", - "complexity": "O(1). The amortized time complexity is O(1) assuming the appended value is small and the already present value is of any size, since the dynamic string library used by Redis will double the free space available on every reallocation.", + "complexity": "O(1). The amortized time complexity is O(1) assuming the appended value is small and the already present value is of any size, since the dynamic string library used by Valkey will double the free space available on every reallocation.", "arguments": [ { "name": "key", @@ -1099,7 +1099,7 @@ "group": "cluster" }, "CLUSTER INFO": { - "summary": "Provides info about Redis Cluster node state", + "summary": "Provides info about Valkey Cluster node state", "complexity": "O(1)", "since": "3.0.0", "group": "cluster" @@ -1186,7 +1186,7 @@ "group": "cluster" }, "CLUSTER RESET": { - "summary": "Reset a Redis Cluster node", + "summary": "Reset a Valkey Cluster node", "complexity": "O(N) where N is the number of known nodes. The command may execute a FLUSHALL as a side effect.", "arguments": [ { @@ -1269,7 +1269,7 @@ "group": "cluster" }, "COMMAND COUNT": { - "summary": "Get total number of Redis commands", + "summary": "Get total number of Valkey commands", "complexity": "O(1)", "since": "2.8.13", "group": "server" @@ -1286,7 +1286,7 @@ "group": "server" }, "COMMAND GETKEYS": { - "summary": "Extract keys given a full Redis command", + "summary": "Extract keys given a full Valkey command", "complexity": "O(N) where N is the number of arguments to the command", "since": "2.8.13", "group": "server", @@ -1304,7 +1304,7 @@ ] }, "COMMAND GETKEYSANDFLAGS": { - "summary": "Extract keys given a full Redis command", + "summary": "Extract keys given a full Valkey command", "since": "7.0.0", "group": "server", "arguments": [ @@ -1321,7 +1321,7 @@ ] }, "COMMAND INFO": { - "summary": "Get array of specific Redis command details", + "summary": "Get array of specific Valkey command details", "complexity": "O(N) when N is number of commands to look up", "since": "2.8.13", "arguments": [ @@ -1351,8 +1351,8 @@ "group": "server" }, "COMMAND": { - "summary": "Get array of Redis command details", - "complexity": "O(N) where N is the total number of Redis commands", + "summary": "Get array of Valkey command details", + "complexity": "O(N) where N is the total number of Valkey commands", "since": "2.8.13", "group": "server" }, @@ -1496,7 +1496,7 @@ }, "DUMP": { "summary": "Return a serialized version of the value stored at the specified key.", - "complexity": "O(1) to access the key and additional O(N*M) to serialize it, where N is the number of Redis objects composing the value and M their average size. For small string values the time complexity is thus O(1)+O(1*M) where M is small, so simply O(1).", + "complexity": "O(1) to access the key and additional O(N*M) to serialize it, where N is the number of Valkey objects composing the value and M their average size. For small string values the time complexity is thus O(1)+O(1*M) where M is small, so simply O(1).", "arguments": [ { "name": "key", @@ -2781,7 +2781,7 @@ "group": "hash" }, "HELLO": { - "summary": "Handshake with Redis", + "summary": "Handshake with Valkey", "complexity": "O(1)", "arguments": [ { @@ -3402,7 +3402,7 @@ "group": "list" }, "LOLWUT": { - "summary": "Display some computer art and the Redis version", + "summary": "Display some computer art and the Valkey version", "arguments": [ { "command": "VERSION", @@ -3636,7 +3636,7 @@ "group": "string" }, "MIGRATE": { - "summary": "Atomically transfer a key from a Redis instance to another one.", + "summary": "Atomically transfer a key from a Valkey instance to another one.", "complexity": "This command actually executes a DUMP+DEL in the source instance, and a RESTORE in the target instance. See the pages of these commands for time complexity. Also an O(N) data transfer between the two instances is performed.", "arguments": [ { @@ -3841,7 +3841,7 @@ "group": "transactions" }, "OBJECT ENCODING": { - "summary": "Inspect the internal encoding of a Redis object", + "summary": "Inspect the internal encoding of a Valkey object", "complexity": "O(1)", "since": "2.2.3", "group": "generic", @@ -3853,7 +3853,7 @@ ] }, "OBJECT FREQ": { - "summary": "Get the logarithmic access frequency counter of a Redis object", + "summary": "Get the logarithmic access frequency counter of a Valkey object", "complexity": "O(1)", "since": "4.0.0", "group": "generic", @@ -3871,7 +3871,7 @@ "group": "generic" }, "OBJECT IDLETIME": { - "summary": "Get the time since a Redis object was last accessed", + "summary": "Get the time since a Valkey object was last accessed", "complexity": "O(1)", "since": "2.2.3", "group": "generic", @@ -4288,7 +4288,7 @@ }, "RESTORE": { "summary": "Create a key using the provided serialized value, previously obtained using DUMP.", - "complexity": "O(1) to create the new key and additional O(N*M) to reconstruct the serialized value, where N is the number of Redis objects composing the value and M their average size. For small string values the time complexity is thus O(1)+O(1*M) where M is small, so simply O(1). However for sorted set values the complexity is O(N*M*log(N)) because inserting values into sorted sets is O(log(N)).", + "complexity": "O(1) to create the new key and additional O(N*M) to reconstruct the serialized value, where N is the number of Valkey objects composing the value and M their average size. For small string values the time complexity is thus O(1)+O(1*M) where M is small, so simply O(1). However for sorted set values the complexity is O(N*M*log(N)) because inserting values into sorted sets is O(log(N)).", "arguments": [ { "name": "key", @@ -4814,7 +4814,7 @@ "group": "set" }, "SLAVEOF": { - "summary": "Make the server a replica of another instance, or promote it as master. Deprecated starting with Redis 5. Use REPLICAOF instead.", + "summary": "Make the server a replica of another instance, or promote it as master. Deprecated starting with Valkey 5. Use REPLICAOF instead.", "arguments": [ { "name": "args", @@ -5221,7 +5221,7 @@ "group": "pubsub" }, "SWAPDB": { - "summary": "Swaps two Redis databases", + "summary": "Swaps two Valkey databases", "complexity": "O(N) where N is the count of clients watching or blocking on keys from both databases.", "arguments": [ { diff --git a/hack/cmds/commands_gears2.json b/hack/cmds/commands_gears2.json index cff8a13..8ff5778 100644 --- a/hack/cmds/commands_gears2.json +++ b/hack/cmds/commands_gears2.json @@ -58,7 +58,7 @@ ] }, "TFUNCTION DELETE": { - "summary": "Delete a JavaScript library from Redis by name", + "summary": "Delete a JavaScript library from Valkey by name", "since": "2.0.0", "group": "triggers_and_functions", "complexity": "O(1)", @@ -71,7 +71,7 @@ ] }, "TFUNCTION LOAD": { - "summary": "Load a new JavaScript library into Redis", + "summary": "Load a new JavaScript library into Valkey", "since": "2.0.0", "group": "triggers_and_functions", "complexity": "O(1)", @@ -101,10 +101,10 @@ ] }, "TFUNCTION LIST": { - "summary": "List all JavaScript libraries loaded into Redis", + "summary": "List all JavaScript libraries loaded into Valkey", "since": "2.0.0", "group": "triggers_and_functions", - "complexity": "O(N) where N is the number of libraries loaded into Redis", + "complexity": "O(N) where N is the number of libraries loaded into Valkey", "arguments": [ { "name": "library-name", diff --git a/hack/cmds/commands_graph.json b/hack/cmds/commands_graph.json index ac70ad6..9fb33c4 100644 --- a/hack/cmds/commands_graph.json +++ b/hack/cmds/commands_graph.json @@ -104,7 +104,7 @@ "group": "graph" }, "GRAPH.CONFIG GET": { - "summary": "Retrieves a RedisGraph configuration", + "summary": "Retrieves a ValkeyGraph configuration", "arguments": [ { "name": "name", @@ -115,7 +115,7 @@ "group": "graph" }, "GRAPH.CONFIG SET": { - "summary": "Updates a RedisGraph configuration", + "summary": "Updates a ValkeyGraph configuration", "arguments": [ { "name": "name", diff --git a/hack/cmds/commands_json.json b/hack/cmds/commands_json.json index 8689cb7..26aced3 100644 --- a/hack/cmds/commands_json.json +++ b/hack/cmds/commands_json.json @@ -469,7 +469,7 @@ "group": "json" }, "JSON.RESP": { - "summary": "Returns the JSON value at path in Redis Serialization Protocol (RESP)", + "summary": "Returns the JSON value at path in Valkey Serialization Protocol (RESP)", "complexity": "O(N) when path is evaluated to a single value, where N is the size of the value, O(N) when path is evaluated to multiple values, where N is the size of the key", "arguments": [ { diff --git a/helper.go b/helper.go index 18ca293..8fa6b50 100644 --- a/helper.go +++ b/helper.go @@ -1,12 +1,12 @@ -package rueidis +package valkey import ( "context" "errors" "time" - intl "github.com/redis/rueidis/internal/cmds" - "github.com/redis/rueidis/internal/util" + intl "github.com/rueian/valkey-go/internal/cmds" + "github.com/rueian/valkey-go/internal/util" ) type mgetcachecmds struct { @@ -42,9 +42,9 @@ var mgetcmdsp = util.NewPool(func(capacity int) *mgetcmds { }) // MGetCache is a helper that consults the client-side caches with multiple keys by grouping keys within same slot into multiple GETs -func MGetCache(client Client, ctx context.Context, ttl time.Duration, keys []string) (ret map[string]RedisMessage, err error) { +func MGetCache(client Client, ctx context.Context, ttl time.Duration, keys []string) (ret map[string]ValkeyMessage, err error) { if len(keys) == 0 { - return make(map[string]RedisMessage), nil + return make(map[string]ValkeyMessage), nil } cmds := mgetcachecmdsp.Get(len(keys), len(keys)) defer mgetcachecmdsp.Put(cmds) @@ -54,10 +54,10 @@ func MGetCache(client Client, ctx context.Context, ttl time.Duration, keys []str return doMultiCache(client, ctx, cmds.s, keys) } -// MGet is a helper that consults the redis directly with multiple keys by grouping keys within same slot into MGET or multiple GETs -func MGet(client Client, ctx context.Context, keys []string) (ret map[string]RedisMessage, err error) { +// MGet is a helper that consults the valkey directly with multiple keys by grouping keys within same slot into MGET or multiple GETs +func MGet(client Client, ctx context.Context, keys []string) (ret map[string]ValkeyMessage, err error) { if len(keys) == 0 { - return make(map[string]RedisMessage), nil + return make(map[string]ValkeyMessage), nil } switch client.(type) { @@ -73,7 +73,7 @@ func MGet(client Client, ctx context.Context, keys []string) (ret map[string]Red return doMultiGet(client, ctx, cmds.s, keys) } -// MSet is a helper that consults the redis directly with multiple keys by grouping keys within same slot into MSETs or multiple SETs +// MSet is a helper that consults the valkey directly with multiple keys by grouping keys within same slot into MSETs or multiple SETs func MSet(client Client, ctx context.Context, kvs map[string]string) map[string]error { if len(kvs) == 0 { return make(map[string]error) @@ -92,7 +92,7 @@ func MSet(client Client, ctx context.Context, kvs map[string]string) map[string] return doMultiSet(client, ctx, cmds.s) } -// MDel is a helper that consults the redis directly with multiple keys by grouping keys within same slot into DELs +// MDel is a helper that consults the valkey directly with multiple keys by grouping keys within same slot into DELs func MDel(client Client, ctx context.Context, keys []string) map[string]error { if len(keys) == 0 { return make(map[string]error) @@ -111,7 +111,7 @@ func MDel(client Client, ctx context.Context, keys []string) map[string]error { return doMultiSet(client, ctx, cmds.s) } -// MSetNX is a helper that consults the redis directly with multiple keys by grouping keys within same slot into MSETNXs or multiple SETNXs +// MSetNX is a helper that consults the valkey directly with multiple keys by grouping keys within same slot into MSETNXs or multiple SETNXs func MSetNX(client Client, ctx context.Context, kvs map[string]string) map[string]error { if len(kvs) == 0 { return make(map[string]error) @@ -131,9 +131,9 @@ func MSetNX(client Client, ctx context.Context, kvs map[string]string) map[strin } // JsonMGetCache is a helper that consults the client-side caches with multiple keys by grouping keys within same slot into multiple JSON.GETs -func JsonMGetCache(client Client, ctx context.Context, ttl time.Duration, keys []string, path string) (ret map[string]RedisMessage, err error) { +func JsonMGetCache(client Client, ctx context.Context, ttl time.Duration, keys []string, path string) (ret map[string]ValkeyMessage, err error) { if len(keys) == 0 { - return make(map[string]RedisMessage), nil + return make(map[string]ValkeyMessage), nil } cmds := mgetcachecmdsp.Get(len(keys), len(keys)) defer mgetcachecmdsp.Put(cmds) @@ -143,10 +143,10 @@ func JsonMGetCache(client Client, ctx context.Context, ttl time.Duration, keys [ return doMultiCache(client, ctx, cmds.s, keys) } -// JsonMGet is a helper that consults redis directly with multiple keys by grouping keys within same slot into JSON.MGETs or multiple JSON.GETs -func JsonMGet(client Client, ctx context.Context, keys []string, path string) (ret map[string]RedisMessage, err error) { +// JsonMGet is a helper that consults valkey directly with multiple keys by grouping keys within same slot into JSON.MGETs or multiple JSON.GETs +func JsonMGet(client Client, ctx context.Context, keys []string, path string) (ret map[string]ValkeyMessage, err error) { if len(keys) == 0 { - return make(map[string]RedisMessage), nil + return make(map[string]ValkeyMessage), nil } switch client.(type) { @@ -162,7 +162,7 @@ func JsonMGet(client Client, ctx context.Context, keys []string, path string) (r return doMultiGet(client, ctx, cmds.s, keys) } -// JsonMSet is a helper that consults redis directly with multiple keys by grouping keys within same slot into JSON.MSETs or multiple JOSN.SETs +// JsonMSet is a helper that consults valkey directly with multiple keys by grouping keys within same slot into JSON.MSETs or multiple JOSN.SETs func JsonMSet(client Client, ctx context.Context, kvs map[string]string, path string) map[string]error { if len(kvs) == 0 { return make(map[string]error) @@ -181,8 +181,8 @@ func JsonMSet(client Client, ctx context.Context, kvs map[string]string, path st return doMultiSet(client, ctx, cmds.s) } -// DecodeSliceOfJSON is a helper that struct-scans each RedisMessage into dest, which must be a slice of pointer. -func DecodeSliceOfJSON[T any](result RedisResult, dest *[]T) error { +// DecodeSliceOfJSON is a helper that struct-scans each ValkeyMessage into dest, which must be a slice of pointer. +func DecodeSliceOfJSON[T any](result ValkeyResult, dest *[]T) error { values, err := result.ToArray() if err != nil { return err @@ -192,7 +192,7 @@ func DecodeSliceOfJSON[T any](result RedisResult, dest *[]T) error { for i, v := range values { var t T if err = v.DecodeJSON(&t); err != nil { - if IsRedisNil(err) { + if IsValkeyNil(err) { continue } return err @@ -203,12 +203,12 @@ func DecodeSliceOfJSON[T any](result RedisResult, dest *[]T) error { return nil } -func clientMGet(client Client, ctx context.Context, cmd Completed, keys []string) (ret map[string]RedisMessage, err error) { +func clientMGet(client Client, ctx context.Context, cmd Completed, keys []string) (ret map[string]ValkeyMessage, err error) { arr, err := client.Do(ctx, cmd).ToArray() if err != nil { return nil, err } - return arrayToKV(make(map[string]RedisMessage, len(keys)), arr, keys), nil + return arrayToKV(make(map[string]ValkeyMessage, len(keys)), arr, keys), nil } func clientMSet(client Client, ctx context.Context, mset string, kvs map[string]string, ret map[string]error) map[string]error { @@ -247,12 +247,12 @@ func clientMDel(client Client, ctx context.Context, keys []string) map[string]er return ret } -func doMultiCache(cc Client, ctx context.Context, cmds []CacheableTTL, keys []string) (ret map[string]RedisMessage, err error) { - ret = make(map[string]RedisMessage, len(keys)) +func doMultiCache(cc Client, ctx context.Context, cmds []CacheableTTL, keys []string) (ret map[string]ValkeyMessage, err error) { + ret = make(map[string]ValkeyMessage, len(keys)) resps := cc.DoMultiCache(ctx, cmds...) - defer resultsp.Put(&redisresults{s: resps}) + defer resultsp.Put(&valkeyresults{s: resps}) for i, resp := range resps { - if err := resp.NonRedisError(); err != nil { + if err := resp.NonValkeyError(); err != nil { return nil, err } ret[keys[i]] = resp.val @@ -260,12 +260,12 @@ func doMultiCache(cc Client, ctx context.Context, cmds []CacheableTTL, keys []st return ret, nil } -func doMultiGet(cc Client, ctx context.Context, cmds []Completed, keys []string) (ret map[string]RedisMessage, err error) { - ret = make(map[string]RedisMessage, len(keys)) +func doMultiGet(cc Client, ctx context.Context, cmds []Completed, keys []string) (ret map[string]ValkeyMessage, err error) { + ret = make(map[string]ValkeyMessage, len(keys)) resps := cc.DoMulti(ctx, cmds...) - defer resultsp.Put(&redisresults{s: resps}) + defer resultsp.Put(&valkeyresults{s: resps}) for i, resp := range resps { - if err := resp.NonRedisError(); err != nil { + if err := resp.NonValkeyError(); err != nil { return nil, err } ret[keys[i]] = resp.val @@ -277,15 +277,15 @@ func doMultiSet(cc Client, ctx context.Context, cmds []Completed) (ret map[strin ret = make(map[string]error, len(cmds)) resps := cc.DoMulti(ctx, cmds...) for i, resp := range resps { - if ret[cmds[i].Commands()[1]] = resp.Error(); resp.NonRedisError() == nil { + if ret[cmds[i].Commands()[1]] = resp.Error(); resp.NonValkeyError() == nil { intl.PutCompletedForce(cmds[i]) } } - resultsp.Put(&redisresults{s: resps}) + resultsp.Put(&valkeyresults{s: resps}) return ret } -func arrayToKV(m map[string]RedisMessage, arr []RedisMessage, keys []string) map[string]RedisMessage { +func arrayToKV(m map[string]ValkeyMessage, arr []ValkeyMessage, keys []string) map[string]ValkeyMessage { for i, resp := range arr { m[keys[i]] = resp } diff --git a/helper_test.go b/helper_test.go index dcb1e17..e59c0c7 100644 --- a/helper_test.go +++ b/helper_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -19,12 +19,12 @@ func TestMGetCache(t *testing.T) { t.Fatalf("unexpected err %v", err) } t.Run("Delegate DoCache", func(t *testing.T) { - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { if reflect.DeepEqual(multi[0].Cmd.Commands(), []string{"GET", "1"}) && multi[0].TTL == 100 && reflect.DeepEqual(multi[1].Cmd.Commands(), []string{"GET", "2"}) && multi[1].TTL == 100 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "1"}, nil), - newResult(RedisMessage{typ: '+', string: "2"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "1"}, nil), + newResult(ValkeyMessage{typ: '+', string: "2"}, nil), }} } t.Fatalf("unexpected command %v", multi) @@ -42,8 +42,8 @@ func TestMGetCache(t *testing.T) { t.Run("Delegate DoCache Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{}, context.Canceled), newResult(RedisMessage{}, context.Canceled)}} + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{}, context.Canceled), newResult(ValkeyMessage{}, context.Canceled)}} } if v, err := MGetCache(client, ctx, 100, []string{"1", "2"}); err != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -52,7 +52,7 @@ func TestMGetCache(t *testing.T) { }) t.Run("cluster client", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsResp }, } @@ -67,16 +67,16 @@ func TestMGetCache(t *testing.T) { for i := range keys { keys[i] = strconv.Itoa(i) } - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { - result := make([]RedisResult, len(multi)) + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { + result := make([]ValkeyResult, len(multi)) for i, key := range keys { if !reflect.DeepEqual(multi[i].Cmd.Commands(), []string{"GET", key}) || multi[i].TTL != 100 { t.Fatalf("unexpected command %v", multi) return nil } - result[i] = newResult(RedisMessage{typ: '+', string: key}, nil) + result[i] = newResult(ValkeyMessage{typ: '+', string: key}, nil) } - return &redisresults{s: result} + return &valkeyresults{s: result} } v, err := MGetCache(client, context.Background(), 100, keys) if err != nil { @@ -96,12 +96,12 @@ func TestMGetCache(t *testing.T) { t.Run("Delegate DoCache Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { - result := make([]RedisResult, len(multi)) + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { + result := make([]ValkeyResult, len(multi)) for i := range result { result[i] = newErrResult(context.Canceled) } - return &redisresults{s: result} + return &valkeyresults{s: result} } if v, err := MGetCache(client, ctx, 100, []string{"1", "2"}); err != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -122,11 +122,11 @@ func TestMGet(t *testing.T) { t.Fatalf("unexpected err %v", err) } t.Run("Delegate Do", func(t *testing.T) { - m.DoFn = func(cmd Completed) RedisResult { + m.DoFn = func(cmd Completed) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), []string{"MGET", "1", "2"}) { t.Fatalf("unexpected command %v", cmd) } - return newResult(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "1"}, {typ: '+', string: "2"}}}, nil) + return newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "1"}, {typ: '+', string: "2"}}}, nil) } if v, err := MGet(client, context.Background(), []string{"1", "2"}); err != nil || v["1"].string != "1" || v["2"].string != "2" { t.Fatalf("unexpected response %v %v", v, err) @@ -140,8 +140,8 @@ func TestMGet(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoFn = func(cmd Completed) RedisResult { - return newResult(RedisMessage{}, context.Canceled) + m.DoFn = func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{}, context.Canceled) } if v, err := MGet(client, ctx, []string{"1", "2"}); err != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -150,7 +150,7 @@ func TestMGet(t *testing.T) { }) t.Run("cluster client", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsResp }, } @@ -165,16 +165,16 @@ func TestMGet(t *testing.T) { for i := range keys { keys[i] = strconv.Itoa(i) } - m.DoMultiFn = func(cmd ...Completed) *redisresults { - result := make([]RedisResult, len(cmd)) + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + result := make([]ValkeyResult, len(cmd)) for i, key := range keys { if !reflect.DeepEqual(cmd[i].Commands(), []string{"GET", key}) { t.Fatalf("unexpected command %v", cmd) return nil } - result[i] = newResult(RedisMessage{typ: '+', string: key}, nil) + result[i] = newResult(ValkeyMessage{typ: '+', string: key}, nil) } - return &redisresults{s: result} + return &valkeyresults{s: result} } v, err := MGet(client, context.Background(), keys) if err != nil { @@ -194,8 +194,8 @@ func TestMGet(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiFn = func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} } if v, err := MGet(client, ctx, []string{"1", "2"}); err != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -216,11 +216,11 @@ func TestMDel(t *testing.T) { t.Fatalf("unexpected err %v", err) } t.Run("Delegate Do", func(t *testing.T) { - m.DoFn = func(cmd Completed) RedisResult { + m.DoFn = func(cmd Completed) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), []string{"DEL", "1", "2"}) { t.Fatalf("unexpected command %v", cmd) } - return newResult(RedisMessage{typ: ':', integer: 2}, nil) + return newResult(ValkeyMessage{typ: ':', integer: 2}, nil) } if v := MDel(client, context.Background(), []string{"1", "2"}); v["1"] != nil || v["2"] != nil { t.Fatalf("unexpected response %v %v", v, err) @@ -234,8 +234,8 @@ func TestMDel(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoFn = func(cmd Completed) RedisResult { - return newResult(RedisMessage{}, context.Canceled) + m.DoFn = func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{}, context.Canceled) } if v := MDel(client, ctx, []string{"1", "2"}); v["1"] != context.Canceled || v["2"] != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -244,7 +244,7 @@ func TestMDel(t *testing.T) { }) t.Run("cluster client", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsResp }, } @@ -259,16 +259,16 @@ func TestMDel(t *testing.T) { for i := range keys { keys[i] = strconv.Itoa(i) } - m.DoMultiFn = func(cmd ...Completed) *redisresults { - result := make([]RedisResult, len(cmd)) + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + result := make([]ValkeyResult, len(cmd)) for i, key := range keys { if !reflect.DeepEqual(cmd[i].Commands(), []string{"DEL", key}) { t.Fatalf("unexpected command %v", cmd) return nil } - result[i] = newResult(RedisMessage{typ: ':', integer: 1}, nil) + result[i] = newResult(ValkeyMessage{typ: ':', integer: 1}, nil) } - return &redisresults{s: result} + return &valkeyresults{s: result} } v := MDel(client, context.Background(), keys) for _, key := range keys { @@ -285,8 +285,8 @@ func TestMDel(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiFn = func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} } if v := MDel(client, ctx, []string{"1", "2"}); v["1"] != context.Canceled || v["2"] != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -306,12 +306,12 @@ func TestMSet(t *testing.T) { t.Fatalf("unexpected err %v", err) } t.Run("Delegate Do", func(t *testing.T) { - m.DoFn = func(cmd Completed) RedisResult { + m.DoFn = func(cmd Completed) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), []string{"MSET", "1", "1", "2", "2"}) && !reflect.DeepEqual(cmd.Commands(), []string{"MSET", "2", "2", "1", "1"}) { t.Fatalf("unexpected command %v", cmd) } - return newResult(RedisMessage{typ: '+', string: "OK"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) } if err := MSet(client, context.Background(), map[string]string{"1": "1", "2": "2"}); err["1"] != nil || err["2"] != nil { t.Fatalf("unexpected response %v", err) @@ -325,8 +325,8 @@ func TestMSet(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoFn = func(cmd Completed) RedisResult { - return newResult(RedisMessage{}, context.Canceled) + m.DoFn = func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{}, context.Canceled) } if err := MSet(client, ctx, map[string]string{"1": "1", "2": "2"}); err["1"] != context.Canceled || err["2"] != context.Canceled { t.Fatalf("unexpected response %v", err) @@ -335,7 +335,7 @@ func TestMSet(t *testing.T) { }) t.Run("cluster client", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsResp }, } @@ -354,21 +354,21 @@ func TestMSet(t *testing.T) { for k := range keys { cpy[k] = struct{}{} } - m.DoMultiFn = func(cmd ...Completed) *redisresults { - result := make([]RedisResult, len(cmd)) + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + result := make([]ValkeyResult, len(cmd)) for i, c := range cmd { delete(cpy, c.Commands()[1]) if c.Commands()[0] != "SET" || keys[c.Commands()[1]] != c.Commands()[2] { t.Fatalf("unexpected command %v", cmd) return nil } - result[i] = newResult(RedisMessage{typ: '+', string: "OK"}, nil) + result[i] = newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) } if len(cpy) != 0 { t.Fatalf("unexpected command %v", cmd) return nil } - return &redisresults{s: result} + return &valkeyresults{s: result} } err := MSet(client, context.Background(), keys) for key := range keys { @@ -385,8 +385,8 @@ func TestMSet(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiFn = func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} } if err := MSet(client, ctx, map[string]string{"1": "1", "2": "2"}); err["1"] != context.Canceled || err["2"] != context.Canceled { t.Fatalf("unexpected response %v", err) @@ -406,12 +406,12 @@ func TestMSetNX(t *testing.T) { t.Fatalf("unexpected err %v", err) } t.Run("Delegate Do", func(t *testing.T) { - m.DoFn = func(cmd Completed) RedisResult { + m.DoFn = func(cmd Completed) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), []string{"MSETNX", "1", "1", "2", "2"}) && !reflect.DeepEqual(cmd.Commands(), []string{"MSETNX", "2", "2", "1", "1"}) { t.Fatalf("unexpected command %v", cmd) } - return newResult(RedisMessage{typ: '+', string: "OK"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) } if err := MSetNX(client, context.Background(), map[string]string{"1": "1", "2": "2"}); err["1"] != nil || err["2"] != nil { t.Fatalf("unexpected response %v", err) @@ -425,8 +425,8 @@ func TestMSetNX(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoFn = func(cmd Completed) RedisResult { - return newResult(RedisMessage{}, context.Canceled) + m.DoFn = func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{}, context.Canceled) } if err := MSetNX(client, ctx, map[string]string{"1": "1", "2": "2"}); err["1"] != context.Canceled || err["2"] != context.Canceled { t.Fatalf("unexpected response %v", err) @@ -435,7 +435,7 @@ func TestMSetNX(t *testing.T) { }) t.Run("cluster client", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsResp }, } @@ -454,21 +454,21 @@ func TestMSetNX(t *testing.T) { for k := range keys { cpy[k] = struct{}{} } - m.DoMultiFn = func(cmd ...Completed) *redisresults { - result := make([]RedisResult, len(cmd)) + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + result := make([]ValkeyResult, len(cmd)) for i, c := range cmd { delete(cpy, c.Commands()[1]) if c.Commands()[0] != "SET" || c.Commands()[3] != "NX" || keys[c.Commands()[1]] != c.Commands()[2] { t.Fatalf("unexpected command %v", cmd) return nil } - result[i] = newResult(RedisMessage{typ: '+', string: "OK"}, nil) + result[i] = newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) } if len(cpy) != 0 { t.Fatalf("unexpected command %v", cmd) return nil } - return &redisresults{s: result} + return &valkeyresults{s: result} } err := MSetNX(client, context.Background(), keys) for key := range keys { @@ -485,8 +485,8 @@ func TestMSetNX(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiFn = func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} } if err := MSetNX(client, ctx, map[string]string{"1": "1", "2": "2"}); err["1"] != context.Canceled || err["2"] != context.Canceled { t.Fatalf("unexpected response %v", err) @@ -506,8 +506,8 @@ func TestMSetNXNotSet(t *testing.T) { t.Fatalf("unexpected err %v", err) } t.Run("Delegate Do Not Set", func(t *testing.T) { - m.DoFn = func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: ':', integer: 0}, nil) + m.DoFn = func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: ':', integer: 0}, nil) } if err := MSetNX(client, context.Background(), map[string]string{"1": "1", "2": "2"}); err["1"] != ErrMSetNXNotSet || err["2"] != ErrMSetNXNotSet { t.Fatalf("unexpected response %v", err) @@ -528,12 +528,12 @@ func TestJsonMGetCache(t *testing.T) { t.Fatalf("unexpected err %v", err) } t.Run("Delegate DoCache", func(t *testing.T) { - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { if reflect.DeepEqual(multi[0].Cmd.Commands(), []string{"JSON.GET", "1", "$"}) && multi[0].TTL == 100 && reflect.DeepEqual(multi[1].Cmd.Commands(), []string{"JSON.GET", "2", "$"}) && multi[1].TTL == 100 { - return &redisresults{s: []RedisResult{ - newResult(RedisMessage{typ: '+', string: "1"}, nil), - newResult(RedisMessage{typ: '+', string: "2"}, nil), + return &valkeyresults{s: []ValkeyResult{ + newResult(ValkeyMessage{typ: '+', string: "1"}, nil), + newResult(ValkeyMessage{typ: '+', string: "2"}, nil), }} } t.Fatalf("unexpected command %v", multi) @@ -551,8 +551,8 @@ func TestJsonMGetCache(t *testing.T) { t.Run("Delegate DoCache Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{}, context.Canceled), newResult(RedisMessage{}, context.Canceled)}} + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{}, context.Canceled), newResult(ValkeyMessage{}, context.Canceled)}} } if v, err := JsonMGetCache(client, ctx, 100, []string{"1", "2"}, "$"); err != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -561,7 +561,7 @@ func TestJsonMGetCache(t *testing.T) { }) t.Run("cluster client", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsResp }, } @@ -576,16 +576,16 @@ func TestJsonMGetCache(t *testing.T) { for i := range keys { keys[i] = strconv.Itoa(i) } - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { - result := make([]RedisResult, len(multi)) + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { + result := make([]ValkeyResult, len(multi)) for i, key := range keys { if !reflect.DeepEqual(multi[i].Cmd.Commands(), []string{"JSON.GET", key, "$"}) || multi[i].TTL != 100 { t.Fatalf("unexpected command %v", multi) return nil } - result[i] = newResult(RedisMessage{typ: '+', string: key}, nil) + result[i] = newResult(ValkeyMessage{typ: '+', string: key}, nil) } - return &redisresults{s: result} + return &valkeyresults{s: result} } v, err := JsonMGetCache(client, context.Background(), 100, keys, "$") if err != nil { @@ -605,12 +605,12 @@ func TestJsonMGetCache(t *testing.T) { t.Run("Delegate DoCache Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { - result := make([]RedisResult, len(multi)) + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { + result := make([]ValkeyResult, len(multi)) for i := range result { result[i] = newErrResult(context.Canceled) } - return &redisresults{s: result} + return &valkeyresults{s: result} } if v, err := JsonMGetCache(client, ctx, 100, []string{"1", "2"}, "$"); err != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -631,11 +631,11 @@ func TestJsonMGet(t *testing.T) { t.Fatalf("unexpected err %v", err) } t.Run("Delegate Do", func(t *testing.T) { - m.DoFn = func(cmd Completed) RedisResult { + m.DoFn = func(cmd Completed) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), []string{"JSON.MGET", "1", "2", "$"}) { t.Fatalf("unexpected command %v", cmd) } - return newResult(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "1"}, {typ: '+', string: "2"}}}, nil) + return newResult(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "1"}, {typ: '+', string: "2"}}}, nil) } if v, err := JsonMGet(client, context.Background(), []string{"1", "2"}, "$"); err != nil || v["1"].string != "1" || v["2"].string != "2" { t.Fatalf("unexpected response %v %v", v, err) @@ -649,8 +649,8 @@ func TestJsonMGet(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoFn = func(cmd Completed) RedisResult { - return newResult(RedisMessage{}, context.Canceled) + m.DoFn = func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{}, context.Canceled) } if v, err := JsonMGet(client, ctx, []string{"1", "2"}, "$"); err != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -659,7 +659,7 @@ func TestJsonMGet(t *testing.T) { }) t.Run("cluster client", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsResp }, } @@ -674,16 +674,16 @@ func TestJsonMGet(t *testing.T) { for i := range keys { keys[i] = strconv.Itoa(i) } - m.DoMultiFn = func(cmd ...Completed) *redisresults { - result := make([]RedisResult, len(cmd)) + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + result := make([]ValkeyResult, len(cmd)) for i, key := range keys { if !reflect.DeepEqual(cmd[i].Commands(), []string{"JSON.GET", key, "$"}) { t.Fatalf("unexpected command %v", cmd) return nil } - result[i] = newResult(RedisMessage{typ: '+', string: key}, nil) + result[i] = newResult(ValkeyMessage{typ: '+', string: key}, nil) } - return &redisresults{s: result} + return &valkeyresults{s: result} } v, err := JsonMGet(client, context.Background(), keys, "$") if err != nil { @@ -703,8 +703,8 @@ func TestJsonMGet(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiFn = func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} } if v, err := JsonMGet(client, ctx, []string{"1", "2"}, "$"); err != context.Canceled { t.Fatalf("unexpected response %v %v", v, err) @@ -724,12 +724,12 @@ func TestJsonMSet(t *testing.T) { t.Fatalf("unexpected err %v", err) } t.Run("Delegate Do", func(t *testing.T) { - m.DoFn = func(cmd Completed) RedisResult { + m.DoFn = func(cmd Completed) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), []string{"JSON.MSET", "1", "$", "1", "2", "$", "2"}) && !reflect.DeepEqual(cmd.Commands(), []string{"JSON.MSET", "2", "$", "2", "1", "$", "1"}) { t.Fatalf("unexpected command %v", cmd) } - return newResult(RedisMessage{typ: '+', string: "OK"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) } if err := JsonMSet(client, context.Background(), map[string]string{"1": "1", "2": "2"}, "$"); err["1"] != nil || err["2"] != nil { t.Fatalf("unexpected response %v", err) @@ -743,8 +743,8 @@ func TestJsonMSet(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoFn = func(cmd Completed) RedisResult { - return newResult(RedisMessage{}, context.Canceled) + m.DoFn = func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{}, context.Canceled) } if err := JsonMSet(client, ctx, map[string]string{"1": "1", "2": "2"}, "$"); err["1"] != context.Canceled || err["2"] != context.Canceled { t.Fatalf("unexpected response %v", err) @@ -753,7 +753,7 @@ func TestJsonMSet(t *testing.T) { }) t.Run("cluster client", func(t *testing.T) { m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return slotsResp }, } @@ -772,21 +772,21 @@ func TestJsonMSet(t *testing.T) { for k := range keys { cpy[k] = struct{}{} } - m.DoMultiFn = func(cmd ...Completed) *redisresults { - result := make([]RedisResult, len(cmd)) + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + result := make([]ValkeyResult, len(cmd)) for i, c := range cmd { delete(cpy, c.Commands()[1]) if c.Commands()[0] != "JSON.SET" || keys[c.Commands()[1]] != c.Commands()[3] || c.Commands()[2] != "$" { t.Fatalf("unexpected command %v", cmd) return nil } - result[i] = newResult(RedisMessage{typ: '+', string: "OK"}, nil) + result[i] = newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) } if len(cpy) != 0 { t.Fatalf("unexpected command %v", cmd) return nil } - return &redisresults{s: result} + return &valkeyresults{s: result} } err := JsonMSet(client, context.Background(), keys, "$") for key := range keys { @@ -803,8 +803,8 @@ func TestJsonMSet(t *testing.T) { t.Run("Delegate Do Err", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - m.DoMultiFn = func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(context.Canceled), newErrResult(context.Canceled)}} } if err := JsonMSet(client, ctx, map[string]string{"1": "1", "2": "2"}, "$"); err["1"] != context.Canceled || err["2"] != context.Canceled { t.Fatalf("unexpected response %v", err) @@ -822,11 +822,11 @@ func TestDecodeSliceOfJSON(t *testing.T) { Name string Inners []*Inner } - values := []RedisMessage{ + values := []ValkeyMessage{ {string: `{"ID":1, "Name": "n1", "Inners": [{"Field": "f1"}]}`, typ: '+'}, {string: `{"ID":2, "Name": "n2", "Inners": [{"Field": "f2"}]}`, typ: '+'}, } - result := RedisResult{val: RedisMessage{typ: '*', values: values}} + result := ValkeyResult{val: ValkeyMessage{typ: '*', values: values}} t.Run("Scan []*T", func(t *testing.T) { got := make([]*T, 0) @@ -857,12 +857,12 @@ func TestDecodeSliceOfJSON(t *testing.T) { }) t.Run("Scan []*T: has nil error message", func(t *testing.T) { - hasNilValues := []RedisMessage{ + hasNilValues := []ValkeyMessage{ {string: `{"ID":1, "Name": "n1", "Inners": [{"Field": "f1"}]}`, typ: '+'}, {typ: '_'}, {string: `{"ID":2, "Name": "n2", "Inners": [{"Field": "f2"}]}`, typ: '+'}, } - hasNilResult := RedisResult{val: RedisMessage{typ: '*', values: hasNilValues}} + hasNilResult := ValkeyResult{val: ValkeyMessage{typ: '*', values: hasNilValues}} got := make([]*T, 0) want := []*T{ @@ -879,12 +879,12 @@ func TestDecodeSliceOfJSON(t *testing.T) { }) t.Run("Scan []T: has nil error message", func(t *testing.T) { - hasNilValues := []RedisMessage{ + hasNilValues := []ValkeyMessage{ {string: `{"ID":1, "Name": "n1", "Inners": [{"Field": "f1"}]}`, typ: '+'}, {typ: '_'}, {string: `{"ID":2, "Name": "n2", "Inners": [{"Field": "f2"}]}`, typ: '+'}, } - hasNilResult := RedisResult{val: RedisMessage{typ: '*', values: hasNilValues}} + hasNilResult := ValkeyResult{val: ValkeyMessage{typ: '*', values: hasNilValues}} got := make([]T, 0) want := []T{ @@ -901,17 +901,17 @@ func TestDecodeSliceOfJSON(t *testing.T) { }) t.Run("error result", func(t *testing.T) { - if err := DecodeSliceOfJSON(RedisResult{val: RedisMessage{typ: '-'}}, &[]*T{}); err == nil { + if err := DecodeSliceOfJSON(ValkeyResult{val: ValkeyMessage{typ: '-'}}, &[]*T{}); err == nil { t.Fatal("DecodeSliceOfJSON not failed as expected") } }) t.Run("has non-nil error message in result", func(t *testing.T) { - hasErrValues := []RedisMessage{ + hasErrValues := []ValkeyMessage{ {string: `{"ID":1, "Name": "n1", "Inners": [{"Field": "f1"}]}`, typ: '+'}, {string: `invalid`, typ: '-'}, } - hasErrResult := RedisResult{val: RedisMessage{typ: '*', values: hasErrValues}} + hasErrResult := ValkeyResult{val: ValkeyMessage{typ: '*', values: hasErrValues}} got := make([]*T, 0) if err := DecodeSliceOfJSON(hasErrResult, &got); err == nil { diff --git a/internal/cmds/builder.go b/internal/cmds/builder.go index 514fe0d..b04d840 100644 --- a/internal/cmds/builder.go +++ b/internal/cmds/builder.go @@ -69,10 +69,10 @@ func PutCacheable(c Cacheable) { } } -// Arbitrary allows user to build an arbitrary redis command with Builder.Arbitrary +// Arbitrary allows user to build an arbitrary valkey command with Builder.Arbitrary type Arbitrary Completed -// Arbitrary allows user to build an arbitrary redis command by following Arbitrary.Keys and Arbitrary.Args +// Arbitrary allows user to build an arbitrary valkey command by following Arbitrary.Keys and Arbitrary.Args func (b Builder) Arbitrary(token ...string) (c Arbitrary) { c = Arbitrary{cs: get(), ks: b.ks} c.cs.s = append(c.cs.s, token...) @@ -81,7 +81,7 @@ func (b Builder) Arbitrary(token ...string) (c Arbitrary) { // Keys calculate which key slot the command belongs to. // Users must use Keys to construct the key part of the command, otherwise -// the command will not be sent to correct redis node. +// the command will not be sent to correct valkey node. func (c Arbitrary) Keys(keys ...string) Arbitrary { if c.ks&NoSlot == NoSlot { for _, k := range keys { @@ -147,7 +147,7 @@ func (c Arbitrary) IsZero() bool { } var ( - arbitraryNoCommand = "Arbitrary should be provided with redis command" + arbitraryNoCommand = "Arbitrary should be provided with valkey command" arbitrarySubscribe = "Arbitrary does not support SUBSCRIBE/UNSUBSCRIBE" arbitraryMultiGet = "Arbitrary.MultiGet is only valid for MGET and JSON.MGET" ) diff --git a/internal/cmds/cmds.go b/internal/cmds/cmds.go index 33e0ed3..7761e85 100644 --- a/internal/cmds/cmds.go +++ b/internal/cmds/cmds.go @@ -9,7 +9,7 @@ const ( noRetTag = uint16(1<<12) | readonly // make noRetTag can also be retried mtGetTag = uint16(1<<11) | readonly // make mtGetTag can also be retried scrRoTag = uint16(1<<10) | readonly // make scrRoTag can also be retried - // InitSlot indicates that the command be sent to any redis node in cluster + // InitSlot indicates that the command be sent to any valkey node in cluster // When SendToReplicas is set, InitSlot command will be sent to primary node InitSlot = uint16(1 << 14) // NoSlot indicates that the command has no key slot specified @@ -83,14 +83,14 @@ func ToBlock(c *Completed) { c.cf |= blockTag } -// Incomplete represents an incomplete Redis command. It should then be completed by calling the Build(). +// Incomplete represents an incomplete Valkey command. It should then be completed by calling the Build(). type Incomplete struct { cs *CommandSlice cf int16 // use int16 instead of uint16 to make a difference with Completed ks uint16 } -// Completed represents a completed Redis command, should be created by the Build() of command builder. +// Completed represents a completed Valkey command, should be created by the Build() of command builder. type Completed struct { cs *CommandSlice cf uint16 // cmd flag @@ -155,7 +155,7 @@ func (c Completed) SetSlot(key string) Completed { return c } -// Cacheable represents a completed Redis command which supports server-assisted client side caching, +// Cacheable represents a completed Valkey command which supports server-assisted client side caching, // and it should be created by the Cache() of command builder. type Cacheable Completed diff --git a/internal/cmds/slot.go b/internal/cmds/slot.go index fef8f5a..5b8a5cf 100644 --- a/internal/cmds/slot.go +++ b/internal/cmds/slot.go @@ -25,7 +25,7 @@ func slot(key string) uint16 { /* * Copyright 2001-2010 Georges Menie (www.menie.org) - * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style) + * Copyright 2010 Salvatore Sanfilippo (adapted to Valkey coding style) * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: diff --git a/lru.go b/lru.go index 897e6e9..15b2f19 100644 --- a/lru.go +++ b/lru.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "container/list" @@ -8,7 +8,7 @@ import ( "time" "unsafe" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go/internal/cmds" ) const ( @@ -28,17 +28,17 @@ type cacheEntry struct { ch chan struct{} kc *keyCache cmd string - val RedisMessage + val ValkeyMessage size int } -func (e *cacheEntry) Wait(ctx context.Context) (RedisMessage, error) { +func (e *cacheEntry) Wait(ctx context.Context) (ValkeyMessage, error) { if ch := ctx.Done(); ch == nil { <-e.ch } else { select { case <-ch: - return RedisMessage{}, ctx.Err() + return ValkeyMessage{}, ctx.Err() case <-e.ch: } } @@ -70,7 +70,7 @@ func newLRU(opt CacheStoreOption) CacheStore { } } -func (c *lru) Flight(key, cmd string, ttl time.Duration, now time.Time) (v RedisMessage, ce CacheEntry) { +func (c *lru) Flight(key, cmd string, ttl time.Duration, now time.Time) (v ValkeyMessage, ce CacheEntry) { var ok bool var kc *keyCache var ele, back *list.Element @@ -98,7 +98,7 @@ func (c *lru) Flight(key, cmd string, ttl time.Duration, now time.Time) (v Redis return v, e } - v = RedisMessage{} + v = ValkeyMessage{} e = nil c.mu.Lock() @@ -129,7 +129,7 @@ ret: return v, ce } -func (c *lru) Flights(now time.Time, multi []CacheableTTL, results []RedisResult, entries map[int]CacheEntry) (missed []int) { +func (c *lru) Flights(now time.Time, multi []CacheableTTL, results []ValkeyResult, entries map[int]CacheEntry) (missed []int) { var moves []*list.Element c.mu.RLock() @@ -208,7 +208,7 @@ func (c *lru) Flights(now time.Time, multi []CacheableTTL, results []RedisResult } miss2: atomic.AddUint32(&kc.miss, 1) - v := RedisMessage{} + v := ValkeyMessage{} v.setExpireAt(now.Add(multi[i].TTL).UnixMilli()) kc.cache[cmd] = c.list.PushBack(&cacheEntry{cmd: cmd, kc: kc, val: v, ch: make(chan struct{})}) missed[j] = i @@ -218,7 +218,7 @@ func (c *lru) Flights(now time.Time, multi []CacheableTTL, results []RedisResult return missed[:j] } -func (c *lru) Update(key, cmd string, value RedisMessage) (pxat int64) { +func (c *lru) Update(key, cmd string, value ValkeyMessage) (pxat int64) { var ch chan struct{} c.mu.Lock() if kc, ok := c.store[key]; ok { @@ -309,7 +309,7 @@ func (c *lru) purge(key string, kc *keyCache) { } } -func (c *lru) Delete(keys []RedisMessage) { +func (c *lru) Delete(keys []ValkeyMessage) { c.mu.Lock() if keys == nil { for key, kc := range c.store { diff --git a/lru_test.go b/lru_test.go index a6745ed..000fa86 100644 --- a/lru_test.go +++ b/lru_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -9,7 +9,7 @@ import ( "testing" "time" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go/internal/cmds" ) const PTTL = 50 @@ -24,7 +24,7 @@ func TestLRU(t *testing.T) { if v, entry := store.Flight("0", "GET", TTL, time.Now()); v.typ != 0 || entry != nil { t.Fatalf("got unexpected value from the first Flight: %v %v", v, entry) } - m := RedisMessage{typ: '+', string: "0", values: []RedisMessage{{}}} + m := ValkeyMessage{typ: '+', string: "0", values: []ValkeyMessage{{}}} m.setExpireAt(time.Now().Add(PTTL * time.Millisecond).UnixMilli()) store.Update("0", "GET", m) return store.(*lru) @@ -48,7 +48,7 @@ func TestLRU(t *testing.T) { if v, entry := lru.Flight("1", "GET", TTL, time.Now()); v.typ != 0 || entry != nil { t.Fatalf("got unexpected value from the Flight after pttl: %v %v", v, entry) } - m := RedisMessage{typ: '+', string: "1"} + m := ValkeyMessage{typ: '+', string: "1"} lru.Update("1", "GET", m) if v, _ := lru.Flight("1", "GET", TTL, time.Now()); v.typ == 0 { t.Fatalf("did not get the value from the second Flight") @@ -96,7 +96,7 @@ func TestLRU(t *testing.T) { lru := setup(t) for i := 1; i <= Entries; i++ { lru.Flight(strconv.Itoa(i), "GET", TTL, time.Now()) - m := RedisMessage{typ: '+', string: strconv.Itoa(i)} + m := ValkeyMessage{typ: '+', string: strconv.Itoa(i)} m.setExpireAt(time.Now().Add(PTTL * time.Millisecond).UnixMilli()) lru.Update(strconv.Itoa(i), "GET", m) } @@ -112,7 +112,7 @@ func TestLRU(t *testing.T) { t.Run("Cache Delete", func(t *testing.T) { lru := setup(t) - lru.Delete([]RedisMessage{{string: "0"}}) + lru.Delete([]ValkeyMessage{{string: "0"}}) if v, _ := lru.Flight("0", "GET", TTL, time.Now()); v.typ != 0 { t.Fatalf("got unexpected value from the first Flight: %v", v) } @@ -122,7 +122,7 @@ func TestLRU(t *testing.T) { lru := setup(t) for i := 1; i < Entries; i++ { lru.Flight(strconv.Itoa(i), "GET", TTL, time.Now()) - m := RedisMessage{typ: '+', string: strconv.Itoa(i)} + m := ValkeyMessage{typ: '+', string: strconv.Itoa(i)} lru.Update(strconv.Itoa(i), "GET", m) } for i := 1; i < Entries; i++ { @@ -155,7 +155,7 @@ func TestLRU(t *testing.T) { t.Fatalf("got unexpected value after Close: %v", err) } - m := RedisMessage{typ: '+', string: "this Update should have no effect"} + m := ValkeyMessage{typ: '+', string: "this Update should have no effect"} m.setExpireAt(time.Now().Add(PTTL * time.Millisecond).UnixMilli()) lru.Update("1", "GET", m) for i := 0; i < 2; i++ { // entry should be always nil after the first call if Close @@ -192,7 +192,7 @@ func TestLRU(t *testing.T) { t.Fatalf("unexpected %v", v) } lru.Flight("key", "cmd", time.Second, time.Now()) - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} m.setExpireAt(time.Now().Add(time.Second).UnixMilli()) lru.Update("key", "cmd", m) if v := lru.GetTTL("key", "cmd"); !roughly(v, time.Second) { @@ -204,7 +204,7 @@ func TestLRU(t *testing.T) { t.Run("client side TTL > server side TTL", func(t *testing.T) { lru := setup(t) lru.Flight("key", "cmd", 2*time.Second, time.Now()) - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} m.setExpireAt(time.Now().Add(time.Second).UnixMilli()) lru.Update("key", "cmd", m) if v, _ := lru.Flight("key", "cmd", 2*time.Second, time.Now()); v.CacheTTL() != 1 { @@ -214,7 +214,7 @@ func TestLRU(t *testing.T) { t.Run("client side TTL < server side TTL", func(t *testing.T) { lru := setup(t) lru.Flight("key", "cmd", 2*time.Second, time.Now()) - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} m.setExpireAt(time.Now().Add(3 * time.Second).UnixMilli()) lru.Update("key", "cmd", m) if v, _ := lru.Flight("key", "cmd", 2*time.Second, time.Now()); v.CacheTTL() != 2 { @@ -224,7 +224,7 @@ func TestLRU(t *testing.T) { t.Run("no server side TTL -1", func(t *testing.T) { lru := setup(t) lru.Flight("key", "cmd", 2*time.Second, time.Now()) - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} lru.Update("key", "cmd", m) if v, _ := lru.Flight("key", "cmd", 2*time.Second, time.Now()); v.CacheTTL() != 2 { t.Fatalf("unexpected %v", v.CacheTTL()) @@ -233,7 +233,7 @@ func TestLRU(t *testing.T) { t.Run("no server side TTL -2", func(t *testing.T) { lru := setup(t) lru.Flight("key", "cmd", 2*time.Second, time.Now()) - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} lru.Update("key", "cmd", m) if v, _ := lru.Flight("key", "cmd", 2*time.Second, time.Now()); v.CacheTTL() != 2 { t.Fatalf("unexpected %v", v.CacheTTL()) @@ -259,7 +259,7 @@ func TestLRU(t *testing.T) { if v, entry := lru.Flight("1", "GET", TTL, time.Now()); v.typ != 0 || entry != nil { t.Fatalf("got unexpected value from the Flight after pttl: %v %v", v, entry) } - m := RedisMessage{typ: '+', string: "1"} + m := ValkeyMessage{typ: '+', string: "1"} lru.Update("1", "GET", m) if v, _ := flights(lru, time.Now(), TTL, "GET", "1"); v.typ == 0 { t.Fatalf("did not get the value from the second Flight") @@ -307,7 +307,7 @@ func TestLRU(t *testing.T) { lru := setup(t) for i := 1; i <= Entries; i++ { flights(lru, time.Now(), TTL, "GET", strconv.Itoa(i)) - m := RedisMessage{typ: '+', string: strconv.Itoa(i)} + m := ValkeyMessage{typ: '+', string: strconv.Itoa(i)} m.setExpireAt(time.Now().Add(PTTL * time.Millisecond).UnixMilli()) lru.Update(strconv.Itoa(i), "GET", m) } @@ -323,7 +323,7 @@ func TestLRU(t *testing.T) { t.Run("Batch Cache Delete", func(t *testing.T) { lru := setup(t) - lru.Delete([]RedisMessage{{string: "0"}}) + lru.Delete([]ValkeyMessage{{string: "0"}}) if v, _ := flights(lru, time.Now(), TTL, "GET", "0"); v.typ != 0 { t.Fatalf("got unexpected value from the first Flight: %v", v) } @@ -333,7 +333,7 @@ func TestLRU(t *testing.T) { lru := setup(t) for i := 1; i < Entries; i++ { flights(lru, time.Now(), TTL, "GET", strconv.Itoa(i)) - m := RedisMessage{typ: '+', string: strconv.Itoa(i)} + m := ValkeyMessage{typ: '+', string: strconv.Itoa(i)} lru.Update(strconv.Itoa(i), "GET", m) } for i := 1; i < Entries; i++ { @@ -366,7 +366,7 @@ func TestLRU(t *testing.T) { t.Fatalf("got unexpected value after Close: %v", err) } - m := RedisMessage{typ: '+', string: "this Update should have no effect"} + m := ValkeyMessage{typ: '+', string: "this Update should have no effect"} m.setExpireAt(time.Now().Add(PTTL * time.Millisecond).UnixMilli()) lru.Update("1", "GET", m) for i := 0; i < 2; i++ { // entry should be always nil after the first call if Close @@ -403,7 +403,7 @@ func TestLRU(t *testing.T) { t.Fatalf("unexpected %v", v) } flights(lru, time.Now(), time.Second, "cmd", "key") - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} m.setExpireAt(time.Now().Add(time.Second).UnixMilli()) lru.Update("key", "cmd", m) if v := lru.GetTTL("key", "cmd"); !roughly(v, time.Second) { @@ -415,7 +415,7 @@ func TestLRU(t *testing.T) { t.Run("client side TTL > server side TTL", func(t *testing.T) { lru := setup(t) flights(lru, time.Now(), time.Second*2, "cmd", "key") - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} m.setExpireAt(time.Now().Add(time.Second).UnixMilli()) lru.Update("key", "cmd", m) if v, _ := flights(lru, time.Now(), time.Second*2, "cmd", "key"); v.CacheTTL() != 1 { @@ -425,7 +425,7 @@ func TestLRU(t *testing.T) { t.Run("client side TTL < server side TTL", func(t *testing.T) { lru := setup(t) flights(lru, time.Now(), time.Second*2, "cmd", "key") - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} m.setExpireAt(time.Now().Add(3 * time.Second).UnixMilli()) lru.Update("key", "cmd", m) if v, _ := flights(lru, time.Now(), time.Second*2, "cmd", "key"); v.CacheTTL() != 2 { @@ -435,7 +435,7 @@ func TestLRU(t *testing.T) { t.Run("no server side TTL -1", func(t *testing.T) { lru := setup(t) flights(lru, time.Now(), time.Second*2, "cmd", "key") - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} lru.Update("key", "cmd", m) if v, _ := flights(lru, time.Now(), time.Second*2, "cmd", "key"); v.CacheTTL() != 2 { t.Fatalf("unexpected %v", v.CacheTTL()) @@ -444,7 +444,7 @@ func TestLRU(t *testing.T) { t.Run("no server side TTL -2", func(t *testing.T) { lru := setup(t) flights(lru, time.Now(), time.Second*2, "cmd", "key") - m := RedisMessage{typ: 1} + m := ValkeyMessage{typ: 1} lru.Update("key", "cmd", m) if v, _ := flights(lru, time.Now(), time.Second*2, "cmd", "key"); v.CacheTTL() != 2 { t.Fatalf("unexpected %v", v.CacheTTL()) @@ -453,8 +453,8 @@ func TestLRU(t *testing.T) { }) } -func flights(lru *lru, now time.Time, ttl time.Duration, args ...string) (RedisMessage, CacheEntry) { - results := make([]RedisResult, 1) +func flights(lru *lru, now time.Time, ttl time.Duration, args ...string) (ValkeyMessage, CacheEntry) { + results := make([]ValkeyResult, 1) entries := make(map[int]CacheEntry, 1) lru.Flights(now, commands(ttl, args...), results, entries) return results[0].val, entries[0] @@ -481,7 +481,7 @@ func BenchmarkLRU(b *testing.B) { for i := 0; i < b.N; i++ { key := strconv.Itoa(i) lru.Flight(key, "GET", TTL, time.Now()) - m := RedisMessage{} + m := ValkeyMessage{} m.setExpireAt(time.Now().Add(PTTL * time.Millisecond).UnixMilli()) lru.Update(key, "GET", m) } @@ -494,7 +494,7 @@ func TestEntry(t *testing.T) { e := cacheEntry{ch: make(chan struct{})} err := errors.New("any") go func() { - e.val = RedisMessage{typ: 1} + e.val = ValkeyMessage{typ: 1} e.err = err close(e.ch) }() @@ -507,7 +507,7 @@ func TestEntry(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { - e.val = RedisMessage{typ: 1} + e.val = ValkeyMessage{typ: 1} close(e.ch) }() if v, err := e.Wait(ctx); v.typ != 1 || err != nil { diff --git a/lua.go b/lua.go index 2b2b02a..bbab773 100644 --- a/lua.go +++ b/lua.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -7,7 +7,7 @@ import ( "runtime" "sync/atomic" - "github.com/redis/rueidis/internal/util" + "github.com/rueian/valkey-go/internal/util" ) // NewLuaScript creates a Lua instance whose Lua.Exec uses EVALSHA and EVAL. @@ -23,7 +23,7 @@ func NewLuaScriptReadOnly(script string) *Lua { return lua } -// Lua represents a redis lua script. It should be created from the NewLuaScript() or NewLuaScriptReadOnly() +// Lua represents a valkey lua script. It should be created from the NewLuaScript() or NewLuaScriptReadOnly() type Lua struct { script string sha1 string @@ -34,13 +34,13 @@ type Lua struct { // Exec the script to the given Client. // It will first try with the EVALSHA/EVALSHA_RO and then EVAL/EVAL_RO if first try failed. // Cross slot keys are prohibited if the Client is a cluster client. -func (s *Lua) Exec(ctx context.Context, c Client, keys, args []string) (resp RedisResult) { +func (s *Lua) Exec(ctx context.Context, c Client, keys, args []string) (resp ValkeyResult) { if s.readonly { resp = c.Do(ctx, c.B().EvalshaRo().Sha1(s.sha1).Numkeys(int64(len(keys))).Key(keys...).Arg(args...).Build()) } else { resp = c.Do(ctx, c.B().Evalsha().Sha1(s.sha1).Numkeys(int64(len(keys))).Key(keys...).Arg(args...).Build()) } - if err, ok := IsRedisErr(resp.Error()); ok && err.IsNoScript() { + if err, ok := IsValkeyErr(resp.Error()); ok && err.IsNoScript() { if s.readonly { resp = c.Do(ctx, c.B().EvalRo().Script(s.script).Numkeys(int64(len(keys))).Key(keys...).Arg(args...).Build()) } else { @@ -57,9 +57,9 @@ type LuaExec struct { } // ExecMulti exec the script multiple times by the provided LuaExec to the given Client. -// It will first try SCRIPT LOAD the script to all redis nodes and then exec it with the EVALSHA/EVALSHA_RO. +// It will first try SCRIPT LOAD the script to all valkey nodes and then exec it with the EVALSHA/EVALSHA_RO. // Cross slot keys within single LuaExec are prohibited if the Client is a cluster client. -func (s *Lua) ExecMulti(ctx context.Context, c Client, multi ...LuaExec) (resp []RedisResult) { +func (s *Lua) ExecMulti(ctx context.Context, c Client, multi ...LuaExec) (resp []ValkeyResult) { var e atomic.Value util.ParallelVals(s.maxp, c.Nodes(), func(n Client) { if err := n.Do(ctx, n.B().ScriptLoad().Script(s.script).Build()).Error(); err != nil { @@ -67,7 +67,7 @@ func (s *Lua) ExecMulti(ctx context.Context, c Client, multi ...LuaExec) (resp [ } }) if err := e.Load(); err != nil { - resp = make([]RedisResult, len(multi)) + resp = make([]ValkeyResult, len(multi)) for i := 0; i < len(resp); i++ { resp[i] = newErrResult(err.(*errs).error) } diff --git a/lua_test.go b/lua_test.go index 0c0987f..bd3e598 100644 --- a/lua_test.go +++ b/lua_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -10,7 +10,7 @@ import ( "testing" "time" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go/internal/cmds" ) func TestNewLuaScriptOnePass(t *testing.T) { @@ -26,11 +26,11 @@ func TestNewLuaScriptOnePass(t *testing.T) { BFn: func() Builder { return cmds.NewBuilder(cmds.NoSlot) }, - DoFn: func(ctx context.Context, cmd Completed) (resp RedisResult) { + DoFn: func(ctx context.Context, cmd Completed) (resp ValkeyResult) { if reflect.DeepEqual(cmd.Commands(), []string{"EVALSHA", sha, "2", "1", "2", "3", "4"}) { - return newResult(RedisMessage{typ: '+', string: "OK"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) } - return newResult(RedisMessage{typ: '+', string: "unexpected"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "unexpected"}, nil) }, } @@ -56,21 +56,21 @@ func TestNewLuaScript(t *testing.T) { BFn: func() Builder { return cmds.NewBuilder(cmds.NoSlot) }, - DoFn: func(ctx context.Context, cmd Completed) (resp RedisResult) { + DoFn: func(ctx context.Context, cmd Completed) (resp ValkeyResult) { if reflect.DeepEqual(cmd.Commands(), []string{"EVALSHA", sha, "2", "1", "2", "3", "4"}) { eval = true - return newResult(RedisMessage{typ: '-', string: "NOSCRIPT"}, nil) + return newResult(ValkeyMessage{typ: '-', string: "NOSCRIPT"}, nil) } if eval && reflect.DeepEqual(cmd.Commands(), []string{"EVAL", body, "2", "1", "2", "3", "4"}) { - return newResult(RedisMessage{typ: '_'}, nil) + return newResult(ValkeyMessage{typ: '_'}, nil) } - return newResult(RedisMessage{typ: '+', string: "unexpected"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "unexpected"}, nil) }, } script := NewLuaScript(body) - if err, ok := IsRedisErr(script.Exec(context.Background(), c, k, a).Error()); ok && !err.IsNil() { + if err, ok := IsValkeyErr(script.Exec(context.Background(), c, k, a).Error()); ok && !err.IsNil() { t.Fatalf("ret mistmatch") } } @@ -90,21 +90,21 @@ func TestNewLuaScriptReadOnly(t *testing.T) { BFn: func() Builder { return cmds.NewBuilder(cmds.NoSlot) }, - DoFn: func(ctx context.Context, cmd Completed) (resp RedisResult) { + DoFn: func(ctx context.Context, cmd Completed) (resp ValkeyResult) { if reflect.DeepEqual(cmd.Commands(), []string{"EVALSHA_RO", sha, "2", "1", "2", "3", "4"}) { eval = true - return newResult(RedisMessage{typ: '-', string: "NOSCRIPT"}, nil) + return newResult(ValkeyMessage{typ: '-', string: "NOSCRIPT"}, nil) } if eval && reflect.DeepEqual(cmd.Commands(), []string{"EVAL_RO", body, "2", "1", "2", "3", "4"}) { - return newResult(RedisMessage{typ: '_'}, nil) + return newResult(ValkeyMessage{typ: '_'}, nil) } - return newResult(RedisMessage{typ: '+', string: "unexpected"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "unexpected"}, nil) }, } script := NewLuaScriptReadOnly(body) - if err, ok := IsRedisErr(script.Exec(context.Background(), c, k, a).Error()); ok && !err.IsNil() { + if err, ok := IsValkeyErr(script.Exec(context.Background(), c, k, a).Error()); ok && !err.IsNil() { t.Fatalf("ret mistmatch") } } @@ -120,8 +120,8 @@ func TestNewLuaScriptExecMultiError(t *testing.T) { BFn: func() Builder { return cmds.NewBuilder(cmds.NoSlot) }, - DoFn: func(ctx context.Context, cmd Completed) (resp RedisResult) { - return newResult(RedisMessage{typ: '-', string: "ANY ERR"}, nil) + DoFn: func(ctx context.Context, cmd Completed) (resp ValkeyResult) { + return newResult(ValkeyMessage{typ: '-', string: "ANY ERR"}, nil) }, } @@ -144,13 +144,13 @@ func TestNewLuaScriptExecMulti(t *testing.T) { BFn: func() Builder { return cmds.NewBuilder(cmds.NoSlot) }, - DoFn: func(ctx context.Context, cmd Completed) (resp RedisResult) { - return newResult(RedisMessage{typ: '+', string: "OK"}, nil) + DoFn: func(ctx context.Context, cmd Completed) (resp ValkeyResult) { + return newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) }, - DoMultiFn: func(ctx context.Context, multi ...Completed) (resp []RedisResult) { + DoMultiFn: func(ctx context.Context, multi ...Completed) (resp []ValkeyResult) { for _, cmd := range multi { if reflect.DeepEqual(cmd.Commands(), []string{"EVALSHA", sha, "2", "1", "2", "3", "4"}) { - resp = append(resp, newResult(RedisMessage{typ: '+', string: "OK"}, nil)) + resp = append(resp, newResult(ValkeyMessage{typ: '+', string: "OK"}, nil)) } } return resp @@ -176,13 +176,13 @@ func TestNewLuaScriptExecMultiRo(t *testing.T) { BFn: func() Builder { return cmds.NewBuilder(cmds.NoSlot) }, - DoFn: func(ctx context.Context, cmd Completed) (resp RedisResult) { - return newResult(RedisMessage{typ: '+', string: "OK"}, nil) + DoFn: func(ctx context.Context, cmd Completed) (resp ValkeyResult) { + return newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) }, - DoMultiFn: func(ctx context.Context, multi ...Completed) (resp []RedisResult) { + DoMultiFn: func(ctx context.Context, multi ...Completed) (resp []ValkeyResult) { for _, cmd := range multi { if reflect.DeepEqual(cmd.Commands(), []string{"EVALSHA_RO", sha, "2", "1", "2", "3", "4"}) { - resp = append(resp, newResult(RedisMessage{typ: '+', string: "OK"}, nil)) + resp = append(resp, newResult(ValkeyMessage{typ: '+', string: "OK"}, nil)) } } return resp @@ -197,10 +197,10 @@ func TestNewLuaScriptExecMultiRo(t *testing.T) { type client struct { BFn func() Builder - DoFn func(ctx context.Context, cmd Completed) (resp RedisResult) - DoMultiFn func(ctx context.Context, cmd ...Completed) (resp []RedisResult) - DoCacheFn func(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp RedisResult) - DoMultiCacheFn func(ctx context.Context, cmd ...CacheableTTL) (resp []RedisResult) + DoFn func(ctx context.Context, cmd Completed) (resp ValkeyResult) + DoMultiFn func(ctx context.Context, cmd ...Completed) (resp []ValkeyResult) + DoCacheFn func(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp ValkeyResult) + DoMultiCacheFn func(ctx context.Context, cmd ...CacheableTTL) (resp []ValkeyResult) DedicatedFn func(fn func(DedicatedClient) error) (err error) DedicateFn func() (DedicatedClient, func()) CloseFn func() @@ -217,40 +217,40 @@ func (c *client) B() Builder { return Builder{} } -func (c *client) Do(ctx context.Context, cmd Completed) (resp RedisResult) { +func (c *client) Do(ctx context.Context, cmd Completed) (resp ValkeyResult) { if c.DoFn != nil { return c.DoFn(ctx, cmd) } - return RedisResult{} + return ValkeyResult{} } -func (c *client) DoMulti(ctx context.Context, cmd ...Completed) (resp []RedisResult) { +func (c *client) DoMulti(ctx context.Context, cmd ...Completed) (resp []ValkeyResult) { if c.DoMultiFn != nil { return c.DoMultiFn(ctx, cmd...) } return nil } -func (c *client) DoStream(ctx context.Context, cmd Completed) (resp RedisResultStream) { - return RedisResultStream{} +func (c *client) DoStream(ctx context.Context, cmd Completed) (resp ValkeyResultStream) { + return ValkeyResultStream{} } -func (c *client) DoMultiStream(ctx context.Context, cmd ...Completed) (resp MultiRedisResultStream) { - return MultiRedisResultStream{} +func (c *client) DoMultiStream(ctx context.Context, cmd ...Completed) (resp MultiValkeyResultStream) { + return MultiValkeyResultStream{} } -func (c *client) DoMultiCache(ctx context.Context, cmd ...CacheableTTL) (resp []RedisResult) { +func (c *client) DoMultiCache(ctx context.Context, cmd ...CacheableTTL) (resp []ValkeyResult) { if c.DoMultiCacheFn != nil { return c.DoMultiCacheFn(ctx, cmd...) } return nil } -func (c *client) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp RedisResult) { +func (c *client) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp ValkeyResult) { if c.DoCacheFn != nil { return c.DoCacheFn(ctx, cmd, ttl) } - return RedisResult{} + return ValkeyResult{} } func (c *client) Dedicated(fn func(DedicatedClient) error) (err error) { diff --git a/message.go b/message.go index f9d1090..12c0722 100644 --- a/message.go +++ b/message.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "encoding/json" @@ -9,107 +9,107 @@ import ( "time" "unsafe" - "github.com/redis/rueidis/internal/util" + "github.com/rueian/valkey-go/internal/util" ) -const messageStructSize = int(unsafe.Sizeof(RedisMessage{})) +const messageStructSize = int(unsafe.Sizeof(ValkeyMessage{})) -// Nil represents a Redis Nil message -var Nil = &RedisError{typ: typeNull} +// Nil represents a Valkey Nil message +var Nil = &ValkeyError{typ: typeNull} -// IsRedisNil is a handy method to check if error is a redis nil response. -// All redis nil response returns as an error. -func IsRedisNil(err error) bool { +// IsValkeyNil is a handy method to check if error is a valkey nil response. +// All valkey nil response returns as an error. +func IsValkeyNil(err error) bool { return err == Nil } -// IsRedisBusyGroup checks if it is a redis BUSYGROUP message. -func IsRedisBusyGroup(err error) bool { - if ret, yes := IsRedisErr(err); yes { +// IsValkeyBusyGroup checks if it is a valkey BUSYGROUP message. +func IsValkeyBusyGroup(err error) bool { + if ret, yes := IsValkeyErr(err); yes { return ret.IsBusyGroup() } return false } -// IsRedisErr is a handy method to check if error is a redis ERR response. -func IsRedisErr(err error) (ret *RedisError, ok bool) { - ret, ok = err.(*RedisError) +// IsValkeyErr is a handy method to check if error is a valkey ERR response. +func IsValkeyErr(err error) (ret *ValkeyError, ok bool) { + ret, ok = err.(*ValkeyError) return ret, ok && ret != Nil } -// RedisError is an error response or a nil message from redis instance -type RedisError RedisMessage +// ValkeyError is an error response or a nil message from valkey instance +type ValkeyError ValkeyMessage -func (r *RedisError) Error() string { +func (r *ValkeyError) Error() string { if r.IsNil() { - return "redis nil message" + return "valkey nil message" } return r.string } -// IsNil checks if it is a redis nil message. -func (r *RedisError) IsNil() bool { +// IsNil checks if it is a valkey nil message. +func (r *ValkeyError) IsNil() bool { return r.typ == typeNull } -// IsMoved checks if it is a redis MOVED message and returns moved address. -func (r *RedisError) IsMoved() (addr string, ok bool) { +// IsMoved checks if it is a valkey MOVED message and returns moved address. +func (r *ValkeyError) IsMoved() (addr string, ok bool) { if ok = strings.HasPrefix(r.string, "MOVED"); ok { addr = strings.Split(r.string, " ")[2] } return } -// IsAsk checks if it is a redis ASK message and returns ask address. -func (r *RedisError) IsAsk() (addr string, ok bool) { +// IsAsk checks if it is a valkey ASK message and returns ask address. +func (r *ValkeyError) IsAsk() (addr string, ok bool) { if ok = strings.HasPrefix(r.string, "ASK"); ok { addr = strings.Split(r.string, " ")[2] } return } -// IsTryAgain checks if it is a redis TRYAGAIN message and returns ask address. -func (r *RedisError) IsTryAgain() bool { +// IsTryAgain checks if it is a valkey TRYAGAIN message and returns ask address. +func (r *ValkeyError) IsTryAgain() bool { return strings.HasPrefix(r.string, "TRYAGAIN") } -// IsClusterDown checks if it is a redis CLUSTERDOWN message and returns ask address. -func (r *RedisError) IsClusterDown() bool { +// IsClusterDown checks if it is a valkey CLUSTERDOWN message and returns ask address. +func (r *ValkeyError) IsClusterDown() bool { return strings.HasPrefix(r.string, "CLUSTERDOWN") } -// IsNoScript checks if it is a redis NOSCRIPT message. -func (r *RedisError) IsNoScript() bool { +// IsNoScript checks if it is a valkey NOSCRIPT message. +func (r *ValkeyError) IsNoScript() bool { return strings.HasPrefix(r.string, "NOSCRIPT") } -// IsBusyGroup checks if it is a redis BUSYGROUP message. -func (r *RedisError) IsBusyGroup() bool { +// IsBusyGroup checks if it is a valkey BUSYGROUP message. +func (r *ValkeyError) IsBusyGroup() bool { return strings.HasPrefix(r.string, "BUSYGROUP") } -func newResult(val RedisMessage, err error) RedisResult { - return RedisResult{val: val, err: err} +func newResult(val ValkeyMessage, err error) ValkeyResult { + return ValkeyResult{val: val, err: err} } -func newErrResult(err error) RedisResult { - return RedisResult{err: err} +func newErrResult(err error) ValkeyResult { + return ValkeyResult{err: err} } -// RedisResult is the return struct from Client.Do or Client.DoCache -// it contains either a redis response or an underlying error (ex. network timeout). -type RedisResult struct { +// ValkeyResult is the return struct from Client.Do or Client.DoCache +// it contains either a valkey response or an underlying error (ex. network timeout). +type ValkeyResult struct { err error - val RedisMessage + val ValkeyMessage } -// NonRedisError can be used to check if there is an underlying error (ex. network timeout). -func (r RedisResult) NonRedisError() error { +// NonValkeyError can be used to check if there is an underlying error (ex. network timeout). +func (r ValkeyResult) NonValkeyError() error { return r.err } -// Error returns either underlying error or redis error or nil -func (r RedisResult) Error() (err error) { +// Error returns either underlying error or valkey error or nil +func (r ValkeyResult) Error() (err error) { if r.err != nil { err = r.err } else { @@ -118,8 +118,8 @@ func (r RedisResult) Error() (err error) { return } -// ToMessage retrieves the RedisMessage -func (r RedisResult) ToMessage() (v RedisMessage, err error) { +// ToMessage retrieves the ValkeyMessage +func (r ValkeyResult) ToMessage() (v ValkeyMessage, err error) { if r.err != nil { err = r.err } else { @@ -128,8 +128,8 @@ func (r RedisResult) ToMessage() (v RedisMessage, err error) { return r.val, err } -// ToInt64 delegates to RedisMessage.ToInt64 -func (r RedisResult) ToInt64() (v int64, err error) { +// ToInt64 delegates to ValkeyMessage.ToInt64 +func (r ValkeyResult) ToInt64() (v int64, err error) { if r.err != nil { err = r.err } else { @@ -138,8 +138,8 @@ func (r RedisResult) ToInt64() (v int64, err error) { return } -// ToBool delegates to RedisMessage.ToBool -func (r RedisResult) ToBool() (v bool, err error) { +// ToBool delegates to ValkeyMessage.ToBool +func (r ValkeyResult) ToBool() (v bool, err error) { if r.err != nil { err = r.err } else { @@ -148,8 +148,8 @@ func (r RedisResult) ToBool() (v bool, err error) { return } -// ToFloat64 delegates to RedisMessage.ToFloat64 -func (r RedisResult) ToFloat64() (v float64, err error) { +// ToFloat64 delegates to ValkeyMessage.ToFloat64 +func (r ValkeyResult) ToFloat64() (v float64, err error) { if r.err != nil { err = r.err } else { @@ -158,8 +158,8 @@ func (r RedisResult) ToFloat64() (v float64, err error) { return } -// ToString delegates to RedisMessage.ToString -func (r RedisResult) ToString() (v string, err error) { +// ToString delegates to ValkeyMessage.ToString +func (r ValkeyResult) ToString() (v string, err error) { if r.err != nil { err = r.err } else { @@ -168,8 +168,8 @@ func (r RedisResult) ToString() (v string, err error) { return } -// AsReader delegates to RedisMessage.AsReader -func (r RedisResult) AsReader() (v io.Reader, err error) { +// AsReader delegates to ValkeyMessage.AsReader +func (r ValkeyResult) AsReader() (v io.Reader, err error) { if r.err != nil { err = r.err } else { @@ -178,8 +178,8 @@ func (r RedisResult) AsReader() (v io.Reader, err error) { return } -// AsBytes delegates to RedisMessage.AsBytes -func (r RedisResult) AsBytes() (v []byte, err error) { +// AsBytes delegates to ValkeyMessage.AsBytes +func (r ValkeyResult) AsBytes() (v []byte, err error) { if r.err != nil { err = r.err } else { @@ -188,8 +188,8 @@ func (r RedisResult) AsBytes() (v []byte, err error) { return } -// DecodeJSON delegates to RedisMessage.DecodeJSON -func (r RedisResult) DecodeJSON(v any) (err error) { +// DecodeJSON delegates to ValkeyMessage.DecodeJSON +func (r ValkeyResult) DecodeJSON(v any) (err error) { if r.err != nil { err = r.err } else { @@ -198,8 +198,8 @@ func (r RedisResult) DecodeJSON(v any) (err error) { return } -// AsInt64 delegates to RedisMessage.AsInt64 -func (r RedisResult) AsInt64() (v int64, err error) { +// AsInt64 delegates to ValkeyMessage.AsInt64 +func (r ValkeyResult) AsInt64() (v int64, err error) { if r.err != nil { err = r.err } else { @@ -208,8 +208,8 @@ func (r RedisResult) AsInt64() (v int64, err error) { return } -// AsUint64 delegates to RedisMessage.AsUint64 -func (r RedisResult) AsUint64() (v uint64, err error) { +// AsUint64 delegates to ValkeyMessage.AsUint64 +func (r ValkeyResult) AsUint64() (v uint64, err error) { if r.err != nil { err = r.err } else { @@ -218,8 +218,8 @@ func (r RedisResult) AsUint64() (v uint64, err error) { return } -// AsBool delegates to RedisMessage.AsBool -func (r RedisResult) AsBool() (v bool, err error) { +// AsBool delegates to ValkeyMessage.AsBool +func (r ValkeyResult) AsBool() (v bool, err error) { if r.err != nil { err = r.err } else { @@ -228,8 +228,8 @@ func (r RedisResult) AsBool() (v bool, err error) { return } -// AsFloat64 delegates to RedisMessage.AsFloat64 -func (r RedisResult) AsFloat64() (v float64, err error) { +// AsFloat64 delegates to ValkeyMessage.AsFloat64 +func (r ValkeyResult) AsFloat64() (v float64, err error) { if r.err != nil { err = r.err } else { @@ -238,8 +238,8 @@ func (r RedisResult) AsFloat64() (v float64, err error) { return } -// ToArray delegates to RedisMessage.ToArray -func (r RedisResult) ToArray() (v []RedisMessage, err error) { +// ToArray delegates to ValkeyMessage.ToArray +func (r ValkeyResult) ToArray() (v []ValkeyMessage, err error) { if r.err != nil { err = r.err } else { @@ -248,8 +248,8 @@ func (r RedisResult) ToArray() (v []RedisMessage, err error) { return } -// AsStrSlice delegates to RedisMessage.AsStrSlice -func (r RedisResult) AsStrSlice() (v []string, err error) { +// AsStrSlice delegates to ValkeyMessage.AsStrSlice +func (r ValkeyResult) AsStrSlice() (v []string, err error) { if r.err != nil { err = r.err } else { @@ -258,8 +258,8 @@ func (r RedisResult) AsStrSlice() (v []string, err error) { return } -// AsIntSlice delegates to RedisMessage.AsIntSlice -func (r RedisResult) AsIntSlice() (v []int64, err error) { +// AsIntSlice delegates to ValkeyMessage.AsIntSlice +func (r ValkeyResult) AsIntSlice() (v []int64, err error) { if r.err != nil { err = r.err } else { @@ -268,8 +268,8 @@ func (r RedisResult) AsIntSlice() (v []int64, err error) { return } -// AsFloatSlice delegates to RedisMessage.AsFloatSlice -func (r RedisResult) AsFloatSlice() (v []float64, err error) { +// AsFloatSlice delegates to ValkeyMessage.AsFloatSlice +func (r ValkeyResult) AsFloatSlice() (v []float64, err error) { if r.err != nil { err = r.err } else { @@ -278,8 +278,8 @@ func (r RedisResult) AsFloatSlice() (v []float64, err error) { return } -// AsBoolSlice delegates to RedisMessage.AsBoolSlice -func (r RedisResult) AsBoolSlice() (v []bool, err error) { +// AsBoolSlice delegates to ValkeyMessage.AsBoolSlice +func (r ValkeyResult) AsBoolSlice() (v []bool, err error) { if r.err != nil { err = r.err } else { @@ -288,8 +288,8 @@ func (r RedisResult) AsBoolSlice() (v []bool, err error) { return } -// AsXRangeEntry delegates to RedisMessage.AsXRangeEntry -func (r RedisResult) AsXRangeEntry() (v XRangeEntry, err error) { +// AsXRangeEntry delegates to ValkeyMessage.AsXRangeEntry +func (r ValkeyResult) AsXRangeEntry() (v XRangeEntry, err error) { if r.err != nil { err = r.err } else { @@ -298,8 +298,8 @@ func (r RedisResult) AsXRangeEntry() (v XRangeEntry, err error) { return } -// AsXRange delegates to RedisMessage.AsXRange -func (r RedisResult) AsXRange() (v []XRangeEntry, err error) { +// AsXRange delegates to ValkeyMessage.AsXRange +func (r ValkeyResult) AsXRange() (v []XRangeEntry, err error) { if r.err != nil { err = r.err } else { @@ -308,8 +308,8 @@ func (r RedisResult) AsXRange() (v []XRangeEntry, err error) { return } -// AsZScore delegates to RedisMessage.AsZScore -func (r RedisResult) AsZScore() (v ZScore, err error) { +// AsZScore delegates to ValkeyMessage.AsZScore +func (r ValkeyResult) AsZScore() (v ZScore, err error) { if r.err != nil { err = r.err } else { @@ -318,8 +318,8 @@ func (r RedisResult) AsZScore() (v ZScore, err error) { return } -// AsZScores delegates to RedisMessage.AsZScores -func (r RedisResult) AsZScores() (v []ZScore, err error) { +// AsZScores delegates to ValkeyMessage.AsZScores +func (r ValkeyResult) AsZScores() (v []ZScore, err error) { if r.err != nil { err = r.err } else { @@ -328,8 +328,8 @@ func (r RedisResult) AsZScores() (v []ZScore, err error) { return } -// AsXRead delegates to RedisMessage.AsXRead -func (r RedisResult) AsXRead() (v map[string][]XRangeEntry, err error) { +// AsXRead delegates to ValkeyMessage.AsXRead +func (r ValkeyResult) AsXRead() (v map[string][]XRangeEntry, err error) { if r.err != nil { err = r.err } else { @@ -338,7 +338,7 @@ func (r RedisResult) AsXRead() (v map[string][]XRangeEntry, err error) { return } -func (r RedisResult) AsLMPop() (v KeyValues, err error) { +func (r ValkeyResult) AsLMPop() (v KeyValues, err error) { if r.err != nil { err = r.err } else { @@ -347,7 +347,7 @@ func (r RedisResult) AsLMPop() (v KeyValues, err error) { return } -func (r RedisResult) AsZMPop() (v KeyZScores, err error) { +func (r ValkeyResult) AsZMPop() (v KeyZScores, err error) { if r.err != nil { err = r.err } else { @@ -356,7 +356,7 @@ func (r RedisResult) AsZMPop() (v KeyZScores, err error) { return } -func (r RedisResult) AsFtSearch() (total int64, docs []FtSearchDoc, err error) { +func (r ValkeyResult) AsFtSearch() (total int64, docs []FtSearchDoc, err error) { if r.err != nil { err = r.err } else { @@ -365,7 +365,7 @@ func (r RedisResult) AsFtSearch() (total int64, docs []FtSearchDoc, err error) { return } -func (r RedisResult) AsFtAggregate() (total int64, docs []map[string]string, err error) { +func (r ValkeyResult) AsFtAggregate() (total int64, docs []map[string]string, err error) { if r.err != nil { err = r.err } else { @@ -374,7 +374,7 @@ func (r RedisResult) AsFtAggregate() (total int64, docs []map[string]string, err return } -func (r RedisResult) AsFtAggregateCursor() (cursor, total int64, docs []map[string]string, err error) { +func (r ValkeyResult) AsFtAggregateCursor() (cursor, total int64, docs []map[string]string, err error) { if r.err != nil { err = r.err } else { @@ -383,7 +383,7 @@ func (r RedisResult) AsFtAggregateCursor() (cursor, total int64, docs []map[stri return } -func (r RedisResult) AsGeosearch() (locations []GeoLocation, err error) { +func (r ValkeyResult) AsGeosearch() (locations []GeoLocation, err error) { if r.err != nil { err = r.err } else { @@ -392,8 +392,8 @@ func (r RedisResult) AsGeosearch() (locations []GeoLocation, err error) { return } -// AsMap delegates to RedisMessage.AsMap -func (r RedisResult) AsMap() (v map[string]RedisMessage, err error) { +// AsMap delegates to ValkeyMessage.AsMap +func (r ValkeyResult) AsMap() (v map[string]ValkeyMessage, err error) { if r.err != nil { err = r.err } else { @@ -402,8 +402,8 @@ func (r RedisResult) AsMap() (v map[string]RedisMessage, err error) { return } -// AsStrMap delegates to RedisMessage.AsStrMap -func (r RedisResult) AsStrMap() (v map[string]string, err error) { +// AsStrMap delegates to ValkeyMessage.AsStrMap +func (r ValkeyResult) AsStrMap() (v map[string]string, err error) { if r.err != nil { err = r.err } else { @@ -412,8 +412,8 @@ func (r RedisResult) AsStrMap() (v map[string]string, err error) { return } -// AsIntMap delegates to RedisMessage.AsIntMap -func (r RedisResult) AsIntMap() (v map[string]int64, err error) { +// AsIntMap delegates to ValkeyMessage.AsIntMap +func (r ValkeyResult) AsIntMap() (v map[string]int64, err error) { if r.err != nil { err = r.err } else { @@ -422,8 +422,8 @@ func (r RedisResult) AsIntMap() (v map[string]int64, err error) { return } -// AsScanEntry delegates to RedisMessage.AsScanEntry. -func (r RedisResult) AsScanEntry() (v ScanEntry, err error) { +// AsScanEntry delegates to ValkeyMessage.AsScanEntry. +func (r ValkeyResult) AsScanEntry() (v ScanEntry, err error) { if r.err != nil { err = r.err } else { @@ -432,8 +432,8 @@ func (r RedisResult) AsScanEntry() (v ScanEntry, err error) { return } -// ToMap delegates to RedisMessage.ToMap -func (r RedisResult) ToMap() (v map[string]RedisMessage, err error) { +// ToMap delegates to ValkeyMessage.ToMap +func (r ValkeyResult) ToMap() (v map[string]ValkeyMessage, err error) { if r.err != nil { err = r.err } else { @@ -442,8 +442,8 @@ func (r RedisResult) ToMap() (v map[string]RedisMessage, err error) { return } -// ToAny delegates to RedisMessage.ToAny -func (r RedisResult) ToAny() (v any, err error) { +// ToAny delegates to ValkeyMessage.ToAny +func (r ValkeyResult) ToAny() (v any, err error) { if r.err != nil { err = r.err } else { @@ -452,122 +452,122 @@ func (r RedisResult) ToAny() (v any, err error) { return } -// IsCacheHit delegates to RedisMessage.IsCacheHit -func (r RedisResult) IsCacheHit() bool { +// IsCacheHit delegates to ValkeyMessage.IsCacheHit +func (r ValkeyResult) IsCacheHit() bool { return r.val.IsCacheHit() } -// CacheTTL delegates to RedisMessage.CacheTTL -func (r RedisResult) CacheTTL() int64 { +// CacheTTL delegates to ValkeyMessage.CacheTTL +func (r ValkeyResult) CacheTTL() int64 { return r.val.CacheTTL() } -// CachePTTL delegates to RedisMessage.CachePTTL -func (r RedisResult) CachePTTL() int64 { +// CachePTTL delegates to ValkeyMessage.CachePTTL +func (r ValkeyResult) CachePTTL() int64 { return r.val.CachePTTL() } -// CachePXAT delegates to RedisMessage.CachePXAT -func (r RedisResult) CachePXAT() int64 { +// CachePXAT delegates to ValkeyMessage.CachePXAT +func (r ValkeyResult) CachePXAT() int64 { return r.val.CachePXAT() } -// String returns human-readable representation of RedisResult -func (r *RedisResult) String() string { - v, _ := (*prettyRedisResult)(r).MarshalJSON() +// String returns human-readable representation of ValkeyResult +func (r *ValkeyResult) String() string { + v, _ := (*prettyValkeyResult)(r).MarshalJSON() return string(v) } -type prettyRedisResult RedisResult +type prettyValkeyResult ValkeyResult // MarshalJSON implements json.Marshaler interface -func (r *prettyRedisResult) MarshalJSON() ([]byte, error) { - type PrettyRedisResult struct { - Message *prettyRedisMessage `json:"Message,omitempty"` - Error string `json:"Error,omitempty"` +func (r *prettyValkeyResult) MarshalJSON() ([]byte, error) { + type PrettyValkeyResult struct { + Message *prettyValkeyMessage `json:"Message,omitempty"` + Error string `json:"Error,omitempty"` } - obj := PrettyRedisResult{} + obj := PrettyValkeyResult{} if r.err != nil { obj.Error = r.err.Error() } else { - obj.Message = (*prettyRedisMessage)(&r.val) + obj.Message = (*prettyValkeyMessage)(&r.val) } return json.Marshal(obj) } -// RedisMessage is a redis response message, it may be a nil response -type RedisMessage struct { - attrs *RedisMessage +// ValkeyMessage is a valkey response message, it may be a nil response +type ValkeyMessage struct { + attrs *ValkeyMessage string string - values []RedisMessage + values []ValkeyMessage integer int64 typ byte ttl [7]byte } -// IsNil check if message is a redis nil response -func (m *RedisMessage) IsNil() bool { +// IsNil check if message is a valkey nil response +func (m *ValkeyMessage) IsNil() bool { return m.typ == typeNull } -// IsInt64 check if message is a redis RESP3 int response -func (m *RedisMessage) IsInt64() bool { +// IsInt64 check if message is a valkey RESP3 int response +func (m *ValkeyMessage) IsInt64() bool { return m.typ == typeInteger } -// IsFloat64 check if message is a redis RESP3 double response -func (m *RedisMessage) IsFloat64() bool { +// IsFloat64 check if message is a valkey RESP3 double response +func (m *ValkeyMessage) IsFloat64() bool { return m.typ == typeFloat } -// IsString check if message is a redis string response -func (m *RedisMessage) IsString() bool { +// IsString check if message is a valkey string response +func (m *ValkeyMessage) IsString() bool { return m.typ == typeBlobString || m.typ == typeSimpleString } -// IsBool check if message is a redis RESP3 bool response -func (m *RedisMessage) IsBool() bool { +// IsBool check if message is a valkey RESP3 bool response +func (m *ValkeyMessage) IsBool() bool { return m.typ == typeBool } -// IsArray check if message is a redis array response -func (m *RedisMessage) IsArray() bool { +// IsArray check if message is a valkey array response +func (m *ValkeyMessage) IsArray() bool { return m.typ == typeArray || m.typ == typeSet } -// IsMap check if message is a redis RESP3 map response -func (m *RedisMessage) IsMap() bool { +// IsMap check if message is a valkey RESP3 map response +func (m *ValkeyMessage) IsMap() bool { return m.typ == typeMap } -// Error check if message is a redis error response, including nil response -func (m *RedisMessage) Error() error { +// Error check if message is a valkey error response, including nil response +func (m *ValkeyMessage) Error() error { if m.typ == typeNull { return Nil } if m.typ == typeSimpleErr || m.typ == typeBlobErr { - // kvrocks: https://github.com/redis/rueidis/issues/152#issuecomment-1333923750 + // kvrocks: https://github.com/valkey/rueidis/issues/152#issuecomment-1333923750 mm := *m mm.string = strings.TrimPrefix(m.string, "ERR ") - return (*RedisError)(&mm) + return (*ValkeyError)(&mm) } return nil } -// ToString check if message is a redis string response, and return it -func (m *RedisMessage) ToString() (val string, err error) { +// ToString check if message is a valkey string response, and return it +func (m *ValkeyMessage) ToString() (val string, err error) { if m.IsString() { return m.string, nil } if m.IsInt64() || m.values != nil { typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a string", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a string", typeNames[typ])) } return m.string, m.Error() } -// AsReader check if message is a redis string response and wrap it with the strings.NewReader -func (m *RedisMessage) AsReader() (reader io.Reader, err error) { +// AsReader check if message is a valkey string response and wrap it with the strings.NewReader +func (m *ValkeyMessage) AsReader() (reader io.Reader, err error) { str, err := m.ToString() if err != nil { return nil, err @@ -575,8 +575,8 @@ func (m *RedisMessage) AsReader() (reader io.Reader, err error) { return strings.NewReader(str), nil } -// AsBytes check if message is a redis string response and return it as an immutable []byte -func (m *RedisMessage) AsBytes() (bs []byte, err error) { +// AsBytes check if message is a valkey string response and return it as an immutable []byte +func (m *ValkeyMessage) AsBytes() (bs []byte, err error) { str, err := m.ToString() if err != nil { return nil, err @@ -584,8 +584,8 @@ func (m *RedisMessage) AsBytes() (bs []byte, err error) { return unsafe.Slice(unsafe.StringData(str), len(str)), nil } -// DecodeJSON check if message is a redis string response and treat it as json, then unmarshal it into provided value -func (m *RedisMessage) DecodeJSON(v any) (err error) { +// DecodeJSON check if message is a valkey string response and treat it as json, then unmarshal it into provided value +func (m *ValkeyMessage) DecodeJSON(v any) (err error) { str, err := m.ToString() if err != nil { return err @@ -594,8 +594,8 @@ func (m *RedisMessage) DecodeJSON(v any) (err error) { return decoder.Decode(v) } -// AsInt64 check if message is a redis string response, and parse it as int64 -func (m *RedisMessage) AsInt64() (val int64, err error) { +// AsInt64 check if message is a valkey string response, and parse it as int64 +func (m *ValkeyMessage) AsInt64() (val int64, err error) { if m.IsInt64() { return m.integer, nil } @@ -606,8 +606,8 @@ func (m *RedisMessage) AsInt64() (val int64, err error) { return strconv.ParseInt(v, 10, 64) } -// AsUint64 check if message is a redis string response, and parse it as uint64 -func (m *RedisMessage) AsUint64() (val uint64, err error) { +// AsUint64 check if message is a valkey string response, and parse it as uint64 +func (m *ValkeyMessage) AsUint64() (val uint64, err error) { if m.IsInt64() { return uint64(m.integer), nil } @@ -618,8 +618,8 @@ func (m *RedisMessage) AsUint64() (val uint64, err error) { return strconv.ParseUint(v, 10, 64) } -// AsBool checks if message is non-nil redis response, and parses it as bool -func (m *RedisMessage) AsBool() (val bool, err error) { +// AsBool checks if message is non-nil valkey response, and parses it as bool +func (m *ValkeyMessage) AsBool() (val bool, err error) { if err = m.Error(); err != nil { return } @@ -635,12 +635,12 @@ func (m *RedisMessage) AsBool() (val bool, err error) { return default: typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a int, string or bool", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a int, string or bool", typeNames[typ])) } } -// AsFloat64 check if message is a redis string response, and parse it as float64 -func (m *RedisMessage) AsFloat64() (val float64, err error) { +// AsFloat64 check if message is a valkey string response, and parse it as float64 +func (m *ValkeyMessage) AsFloat64() (val float64, err error) { if m.IsFloat64() { return util.ToFloat64(m.string) } @@ -651,8 +651,8 @@ func (m *RedisMessage) AsFloat64() (val float64, err error) { return util.ToFloat64(v) } -// ToInt64 check if message is a redis RESP3 int response, and return it -func (m *RedisMessage) ToInt64() (val int64, err error) { +// ToInt64 check if message is a valkey RESP3 int response, and return it +func (m *ValkeyMessage) ToInt64() (val int64, err error) { if m.IsInt64() { return m.integer, nil } @@ -660,11 +660,11 @@ func (m *RedisMessage) ToInt64() (val int64, err error) { return 0, err } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a RESP3 int64", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a RESP3 int64", typeNames[typ])) } -// ToBool check if message is a redis RESP3 bool response, and return it -func (m *RedisMessage) ToBool() (val bool, err error) { +// ToBool check if message is a valkey RESP3 bool response, and return it +func (m *ValkeyMessage) ToBool() (val bool, err error) { if m.IsBool() { return m.integer == 1, nil } @@ -672,11 +672,11 @@ func (m *RedisMessage) ToBool() (val bool, err error) { return false, err } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a RESP3 bool", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a RESP3 bool", typeNames[typ])) } -// ToFloat64 check if message is a redis RESP3 double response, and return it -func (m *RedisMessage) ToFloat64() (val float64, err error) { +// ToFloat64 check if message is a valkey RESP3 double response, and return it +func (m *ValkeyMessage) ToFloat64() (val float64, err error) { if m.IsFloat64() { return util.ToFloat64(m.string) } @@ -684,11 +684,11 @@ func (m *RedisMessage) ToFloat64() (val float64, err error) { return 0, err } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a RESP3 float64", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a RESP3 float64", typeNames[typ])) } -// ToArray check if message is a redis array/set response, and return it -func (m *RedisMessage) ToArray() ([]RedisMessage, error) { +// ToArray check if message is a valkey array/set response, and return it +func (m *ValkeyMessage) ToArray() ([]ValkeyMessage, error) { if m.IsArray() { return m.values, nil } @@ -696,12 +696,12 @@ func (m *RedisMessage) ToArray() ([]RedisMessage, error) { return nil, err } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a array", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a array", typeNames[typ])) } -// AsStrSlice check if message is a redis array/set response, and convert to []string. -// redis nil element and other non string element will be present as zero. -func (m *RedisMessage) AsStrSlice() ([]string, error) { +// AsStrSlice check if message is a valkey array/set response, and convert to []string. +// valkey nil element and other non string element will be present as zero. +func (m *ValkeyMessage) AsStrSlice() ([]string, error) { values, err := m.ToArray() if err != nil { return nil, err @@ -713,9 +713,9 @@ func (m *RedisMessage) AsStrSlice() ([]string, error) { return s, nil } -// AsIntSlice check if message is a redis array/set response, and convert to []int64. -// redis nil element and other non integer element will be present as zero. -func (m *RedisMessage) AsIntSlice() ([]int64, error) { +// AsIntSlice check if message is a valkey array/set response, and convert to []int64. +// valkey nil element and other non integer element will be present as zero. +func (m *ValkeyMessage) AsIntSlice() ([]int64, error) { values, err := m.ToArray() if err != nil { return nil, err @@ -733,9 +733,9 @@ func (m *RedisMessage) AsIntSlice() ([]int64, error) { return s, nil } -// AsFloatSlice check if message is a redis array/set response, and convert to []float64. -// redis nil element and other non float element will be present as zero. -func (m *RedisMessage) AsFloatSlice() ([]float64, error) { +// AsFloatSlice check if message is a valkey array/set response, and convert to []float64. +// valkey nil element and other non float element will be present as zero. +func (m *ValkeyMessage) AsFloatSlice() ([]float64, error) { values, err := m.ToArray() if err != nil { return nil, err @@ -753,9 +753,9 @@ func (m *RedisMessage) AsFloatSlice() ([]float64, error) { return s, nil } -// AsBoolSlice checks if message is a redis array/set response, and converts it to []bool. -// Redis nil elements and other non-boolean elements will be represented as false. -func (m *RedisMessage) AsBoolSlice() ([]bool, error) { +// AsBoolSlice checks if message is a valkey array/set response, and converts it to []bool. +// Valkey nil elements and other non-boolean elements will be represented as false. +func (m *ValkeyMessage) AsBoolSlice() ([]bool, error) { values, err := m.ToArray() if err != nil { return nil, err @@ -773,8 +773,8 @@ type XRangeEntry struct { ID string } -// AsXRangeEntry check if message is a redis array/set response of length 2, and convert to XRangeEntry -func (m *RedisMessage) AsXRangeEntry() (XRangeEntry, error) { +// AsXRangeEntry check if message is a valkey array/set response of length 2, and convert to XRangeEntry +func (m *ValkeyMessage) AsXRangeEntry() (XRangeEntry, error) { values, err := m.ToArray() if err != nil { return XRangeEntry{}, err @@ -788,7 +788,7 @@ func (m *RedisMessage) AsXRangeEntry() (XRangeEntry, error) { } fieldValues, err := values[1].AsStrMap() if err != nil { - if IsRedisNil(err) { + if IsValkeyNil(err) { return XRangeEntry{ID: id, FieldValues: nil}, nil } return XRangeEntry{}, err @@ -799,8 +799,8 @@ func (m *RedisMessage) AsXRangeEntry() (XRangeEntry, error) { }, nil } -// AsXRange check if message is a redis array/set response, and convert to []XRangeEntry -func (m *RedisMessage) AsXRange() ([]XRangeEntry, error) { +// AsXRange check if message is a valkey array/set response, and convert to []XRangeEntry +func (m *ValkeyMessage) AsXRange() ([]XRangeEntry, error) { values, err := m.ToArray() if err != nil { return nil, err @@ -817,7 +817,7 @@ func (m *RedisMessage) AsXRange() ([]XRangeEntry, error) { } // AsXRead converts XREAD/XREADGRUOP response to map[string][]XRangeEntry -func (m *RedisMessage) AsXRead() (ret map[string][]XRangeEntry, err error) { +func (m *ValkeyMessage) AsXRead() (ret map[string][]XRangeEntry, err error) { if err = m.Error(); err != nil { return nil, err } @@ -843,7 +843,7 @@ func (m *RedisMessage) AsXRead() (ret map[string][]XRangeEntry, err error) { return ret, nil } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a map/array/set or its length is not even", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a map/array/set or its length is not even", typeNames[typ])) } // ZScore is the element type of ZRANGE WITHSCORES, ZDIFF WITHSCORES and ZPOPMAX command response @@ -852,18 +852,18 @@ type ZScore struct { Score float64 } -func toZScore(values []RedisMessage) (s ZScore, err error) { +func toZScore(values []ValkeyMessage) (s ZScore, err error) { if len(values) == 2 { if s.Member, err = values[0].ToString(); err == nil { s.Score, err = values[1].AsFloat64() } return s, err } - panic("redis message is not a map/array/set or its length is not 2") + panic("valkey message is not a map/array/set or its length is not 2") } // AsZScore converts ZPOPMAX and ZPOPMIN command with count 1 response to a single ZScore -func (m *RedisMessage) AsZScore() (s ZScore, err error) { +func (m *ValkeyMessage) AsZScore() (s ZScore, err error) { arr, err := m.ToArray() if err != nil { return s, err @@ -872,7 +872,7 @@ func (m *RedisMessage) AsZScore() (s ZScore, err error) { } // AsZScores converts ZRANGE WITHSCROES, ZDIFF WITHSCROES and ZPOPMAX/ZPOPMIN command with count > 1 responses to []ZScore -func (m *RedisMessage) AsZScores() ([]ZScore, error) { +func (m *ValkeyMessage) AsZScores() ([]ZScore, error) { arr, err := m.ToArray() if err != nil { return nil, err @@ -902,8 +902,8 @@ type ScanEntry struct { Cursor uint64 } -// AsScanEntry check if message is a redis array/set response of length 2, and convert to ScanEntry. -func (m *RedisMessage) AsScanEntry() (e ScanEntry, err error) { +// AsScanEntry check if message is a valkey array/set response of length 2, and convert to ScanEntry. +func (m *ValkeyMessage) AsScanEntry() (e ScanEntry, err error) { msgs, err := m.ToArray() if err != nil { return ScanEntry{}, err @@ -915,11 +915,11 @@ func (m *RedisMessage) AsScanEntry() (e ScanEntry, err error) { return e, err } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a scan response or its length is not at least 2", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a scan response or its length is not at least 2", typeNames[typ])) } -// AsMap check if message is a redis array/set response, and convert to map[string]RedisMessage -func (m *RedisMessage) AsMap() (map[string]RedisMessage, error) { +// AsMap check if message is a valkey array/set response, and convert to map[string]ValkeyMessage +func (m *ValkeyMessage) AsMap() (map[string]ValkeyMessage, error) { if err := m.Error(); err != nil { return nil, err } @@ -927,12 +927,12 @@ func (m *RedisMessage) AsMap() (map[string]RedisMessage, error) { return toMap(m.values), nil } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a map/array/set or its length is not even", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a map/array/set or its length is not even", typeNames[typ])) } -// AsStrMap check if message is a redis map/array/set response, and convert to map[string]string. -// redis nil element and other non string element will be present as zero. -func (m *RedisMessage) AsStrMap() (map[string]string, error) { +// AsStrMap check if message is a valkey map/array/set response, and convert to map[string]string. +// valkey nil element and other non string element will be present as zero. +func (m *ValkeyMessage) AsStrMap() (map[string]string, error) { if err := m.Error(); err != nil { return nil, err } @@ -946,12 +946,12 @@ func (m *RedisMessage) AsStrMap() (map[string]string, error) { return r, nil } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a map/array/set or its length is not even", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a map/array/set or its length is not even", typeNames[typ])) } -// AsIntMap check if message is a redis map/array/set response, and convert to map[string]int64. -// redis nil element and other non integer element will be present as zero. -func (m *RedisMessage) AsIntMap() (map[string]int64, error) { +// AsIntMap check if message is a valkey map/array/set response, and convert to map[string]int64. +// valkey nil element and other non integer element will be present as zero. +func (m *ValkeyMessage) AsIntMap() (map[string]int64, error) { if err := m.Error(); err != nil { return nil, err } @@ -974,7 +974,7 @@ func (m *RedisMessage) AsIntMap() (map[string]int64, error) { return r, nil } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a map/array/set or its length is not even", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a map/array/set or its length is not even", typeNames[typ])) } type KeyValues struct { @@ -982,7 +982,7 @@ type KeyValues struct { Values []string } -func (m *RedisMessage) AsLMPop() (kvs KeyValues, err error) { +func (m *ValkeyMessage) AsLMPop() (kvs KeyValues, err error) { if err = m.Error(); err != nil { return KeyValues{}, err } @@ -992,7 +992,7 @@ func (m *RedisMessage) AsLMPop() (kvs KeyValues, err error) { return } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a LMPOP response", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a LMPOP response", typeNames[typ])) } type KeyZScores struct { @@ -1000,7 +1000,7 @@ type KeyZScores struct { Values []ZScore } -func (m *RedisMessage) AsZMPop() (kvs KeyZScores, err error) { +func (m *ValkeyMessage) AsZMPop() (kvs KeyZScores, err error) { if err = m.Error(); err != nil { return KeyZScores{}, err } @@ -1010,7 +1010,7 @@ func (m *RedisMessage) AsZMPop() (kvs KeyZScores, err error) { return } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a ZMPOP response", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a ZMPOP response", typeNames[typ])) } type FtSearchDoc struct { @@ -1019,7 +1019,7 @@ type FtSearchDoc struct { Score float64 } -func (m *RedisMessage) AsFtSearch() (total int64, docs []FtSearchDoc, err error) { +func (m *ValkeyMessage) AsFtSearch() (total int64, docs []FtSearchDoc, err error) { if err = m.Error(); err != nil { return 0, nil, err } @@ -1046,7 +1046,7 @@ func (m *RedisMessage) AsFtSearch() (total int64, docs []FtSearchDoc, err error) case "error": for _, e := range m.values[i+1].values { e := e - return 0, nil, (*RedisError)(&e) + return 0, nil, (*ValkeyError)(&e) } } } @@ -1088,10 +1088,10 @@ func (m *RedisMessage) AsFtSearch() (total int64, docs []FtSearchDoc, err error) return } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a FT.SEARCH response", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a FT.SEARCH response", typeNames[typ])) } -func (m *RedisMessage) AsFtAggregate() (total int64, docs []map[string]string, err error) { +func (m *ValkeyMessage) AsFtAggregate() (total int64, docs []map[string]string, err error) { if err = m.Error(); err != nil { return 0, nil, err } @@ -1114,7 +1114,7 @@ func (m *RedisMessage) AsFtAggregate() (total int64, docs []map[string]string, e case "error": for _, e := range m.values[i+1].values { e := e - return 0, nil, (*RedisError)(&e) + return 0, nil, (*ValkeyError)(&e) } } } @@ -1129,10 +1129,10 @@ func (m *RedisMessage) AsFtAggregate() (total int64, docs []map[string]string, e return } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a FT.AGGREGATE response", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a FT.AGGREGATE response", typeNames[typ])) } -func (m *RedisMessage) AsFtAggregateCursor() (cursor, total int64, docs []map[string]string, err error) { +func (m *ValkeyMessage) AsFtAggregateCursor() (cursor, total int64, docs []map[string]string, err error) { if m.IsArray() && len(m.values) == 2 && (m.values[0].IsArray() || m.values[0].IsMap()) { total, docs, err = m.values[0].AsFtAggregate() cursor = m.values[1].integer @@ -1148,7 +1148,7 @@ type GeoLocation struct { GeoHash int64 } -func (m *RedisMessage) AsGeosearch() ([]GeoLocation, error) { +func (m *ValkeyMessage) AsGeosearch() ([]GeoLocation, error) { arr, err := m.ToArray() if err != nil { return nil, err @@ -1193,8 +1193,8 @@ func (m *RedisMessage) AsGeosearch() ([]GeoLocation, error) { return geoLocations, nil } -// ToMap check if message is a redis RESP3 map response, and return it -func (m *RedisMessage) ToMap() (map[string]RedisMessage, error) { +// ToMap check if message is a valkey RESP3 map response, and return it +func (m *ValkeyMessage) ToMap() (map[string]ValkeyMessage, error) { if m.IsMap() { return toMap(m.values), nil } @@ -1202,11 +1202,11 @@ func (m *RedisMessage) ToMap() (map[string]RedisMessage, error) { return nil, err } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a RESP3 map", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a RESP3 map", typeNames[typ])) } // ToAny turns message into go any value -func (m *RedisMessage) ToAny() (any, error) { +func (m *ValkeyMessage) ToAny() (any, error) { if err := m.Error(); err != nil { return nil, err } @@ -1222,7 +1222,7 @@ func (m *RedisMessage) ToAny() (any, error) { case typeMap: vs := make(map[string]any, len(m.values)/2) for i := 0; i < len(m.values); i += 2 { - if v, err := m.values[i+1].ToAny(); err != nil && !IsRedisNil(err) { + if v, err := m.values[i+1].ToAny(); err != nil && !IsValkeyNil(err) { vs[m.values[i].string] = err } else { vs[m.values[i].string] = v @@ -1232,7 +1232,7 @@ func (m *RedisMessage) ToAny() (any, error) { case typeSet, typeArray: vs := make([]any, len(m.values)) for i := 0; i < len(m.values); i++ { - if v, err := m.values[i].ToAny(); err != nil && !IsRedisNil(err) { + if v, err := m.values[i].ToAny(); err != nil && !IsValkeyNil(err) { vs[i] = err } else { vs[i] = v @@ -1241,16 +1241,16 @@ func (m *RedisMessage) ToAny() (any, error) { return vs, nil } typ := m.typ - panic(fmt.Sprintf("redis message type %s is not a supported in ToAny", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s is not a supported in ToAny", typeNames[typ])) } // IsCacheHit check if message is from client side cache -func (m *RedisMessage) IsCacheHit() bool { +func (m *ValkeyMessage) IsCacheHit() bool { return m.attrs == cacheMark } // CacheTTL returns the remaining TTL in seconds of client side cache -func (m *RedisMessage) CacheTTL() (ttl int64) { +func (m *ValkeyMessage) CacheTTL() (ttl int64) { milli := m.CachePTTL() if milli > 0 { if ttl = milli / 1000; milli > ttl*1000 { @@ -1262,7 +1262,7 @@ func (m *RedisMessage) CacheTTL() (ttl int64) { } // CachePTTL returns the remaining PTTL in seconds of client side cache -func (m *RedisMessage) CachePTTL() int64 { +func (m *ValkeyMessage) CachePTTL() int64 { milli := m.getExpireAt() if milli == 0 { return -1 @@ -1274,7 +1274,7 @@ func (m *RedisMessage) CachePTTL() int64 { } // CachePXAT returns the remaining PXAT in seconds of client side cache -func (m *RedisMessage) CachePXAT() int64 { +func (m *ValkeyMessage) CachePXAT() int64 { milli := m.getExpireAt() if milli == 0 { return -1 @@ -1282,16 +1282,16 @@ func (m *RedisMessage) CachePXAT() int64 { return milli } -func (m *RedisMessage) relativePTTL(now time.Time) int64 { +func (m *ValkeyMessage) relativePTTL(now time.Time) int64 { return m.getExpireAt() - now.UnixMilli() } -func (m *RedisMessage) getExpireAt() int64 { +func (m *ValkeyMessage) getExpireAt() int64 { return int64(m.ttl[0]) | int64(m.ttl[1])<<8 | int64(m.ttl[2])<<16 | int64(m.ttl[3])<<24 | int64(m.ttl[4])<<32 | int64(m.ttl[5])<<40 | int64(m.ttl[6])<<48 } -func (m *RedisMessage) setExpireAt(pttl int64) { +func (m *ValkeyMessage) setExpireAt(pttl int64) { m.ttl[0] = byte(pttl) m.ttl[1] = byte(pttl >> 8) m.ttl[2] = byte(pttl >> 16) @@ -1301,20 +1301,20 @@ func (m *RedisMessage) setExpireAt(pttl int64) { m.ttl[6] = byte(pttl >> 48) } -func toMap(values []RedisMessage) map[string]RedisMessage { - r := make(map[string]RedisMessage, len(values)/2) +func toMap(values []ValkeyMessage) map[string]ValkeyMessage { + r := make(map[string]ValkeyMessage, len(values)/2) for i := 0; i < len(values); i += 2 { if values[i].typ == typeBlobString || values[i].typ == typeSimpleString { r[values[i].string] = values[i+1] continue } typ := values[i].typ - panic(fmt.Sprintf("redis message type %s as map key is not supported", typeNames[typ])) + panic(fmt.Sprintf("valkey message type %s as map key is not supported", typeNames[typ])) } return r } -func (m *RedisMessage) approximateSize() (s int) { +func (m *ValkeyMessage) approximateSize() (s int) { s += messageStructSize s += len(m.string) for _, v := range m.values { @@ -1323,28 +1323,28 @@ func (m *RedisMessage) approximateSize() (s int) { return } -// String returns human-readable representation of RedisMessage -func (m *RedisMessage) String() string { - v, _ := (*prettyRedisMessage)(m).MarshalJSON() +// String returns human-readable representation of ValkeyMessage +func (m *ValkeyMessage) String() string { + v, _ := (*prettyValkeyMessage)(m).MarshalJSON() return string(v) } -type prettyRedisMessage RedisMessage +type prettyValkeyMessage ValkeyMessage // MarshalJSON implements json.Marshaler interface -func (m *prettyRedisMessage) MarshalJSON() ([]byte, error) { - type PrettyRedisMessage struct { +func (m *prettyValkeyMessage) MarshalJSON() ([]byte, error) { + type PrettyValkeyMessage struct { Value any `json:"Value,omitempty"` Type string `json:"Type,omitempty"` Error string `json:"Error,omitempty"` Ttl string `json:"TTL,omitempty"` } - org := (*RedisMessage)(m) + org := (*ValkeyMessage)(m) strType, ok := typeNames[m.typ] if !ok { strType = "unknown" } - obj := PrettyRedisMessage{Type: strType} + obj := PrettyValkeyMessage{Type: strType} if m.ttl != [7]byte{} { obj.Ttl = time.UnixMilli(org.CachePXAT()).UTC().String() } @@ -1359,9 +1359,9 @@ func (m *prettyRedisMessage) MarshalJSON() ([]byte, error) { case typeInteger: obj.Value = m.integer case typeMap, typeSet, typeArray: - values := make([]prettyRedisMessage, len(m.values)) + values := make([]prettyValkeyMessage, len(m.values)) for i, value := range m.values { - values[i] = prettyRedisMessage(value) + values[i] = prettyValkeyMessage(value) } obj.Value = values } diff --git a/message_test.go b/message_test.go index 6d8dad0..9b87978 100644 --- a/message_test.go +++ b/message_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "bytes" @@ -21,137 +21,137 @@ type wrapped struct { func (e wrapped) Error() string { return e.msg } func (e wrapped) Unwrap() error { return e.err } -func TestIsRedisNil(t *testing.T) { +func TestIsValkeyNil(t *testing.T) { err := Nil - if !IsRedisNil(err) { - t.Fatal("IsRedisNil fail") + if !IsValkeyNil(err) { + t.Fatal("IsValkeyNil fail") } - if IsRedisNil(errors.New("other")) { - t.Fatal("IsRedisNil fail") + if IsValkeyNil(errors.New("other")) { + t.Fatal("IsValkeyNil fail") } - if err.Error() != "redis nil message" { - t.Fatal("IsRedisNil fail") + if err.Error() != "valkey nil message" { + t.Fatal("IsValkeyNil fail") } wrappedErr := wrapped{msg: "wrapped", err: Nil} - if IsRedisNil(wrappedErr) { - t.Fatal("IsRedisNil fail : wrapped error") + if IsValkeyNil(wrappedErr) { + t.Fatal("IsValkeyNil fail : wrapped error") } } -func TestIsRedisErr(t *testing.T) { +func TestIsValkeyErr(t *testing.T) { err := Nil - if ret, ok := IsRedisErr(err); ok || ret != Nil { - t.Fatal("TestIsRedisErr fail") + if ret, ok := IsValkeyErr(err); ok || ret != Nil { + t.Fatal("TestIsValkeyErr fail") } - if ret, ok := IsRedisErr(nil); ok || ret != nil { - t.Fatal("TestIsRedisErr fail") + if ret, ok := IsValkeyErr(nil); ok || ret != nil { + t.Fatal("TestIsValkeyErr fail") } - if ret, ok := IsRedisErr(errors.New("other")); ok || ret != nil { - t.Fatal("TestIsRedisErr fail") + if ret, ok := IsValkeyErr(errors.New("other")); ok || ret != nil { + t.Fatal("TestIsValkeyErr fail") } - if ret, ok := IsRedisErr(&RedisError{typ: '-'}); !ok || ret.typ != '-' { - t.Fatal("TestIsRedisErr fail") + if ret, ok := IsValkeyErr(&ValkeyError{typ: '-'}); !ok || ret.typ != '-' { + t.Fatal("TestIsValkeyErr fail") } wrappedErr := wrapped{msg: "wrapped", err: Nil} - if ret, ok := IsRedisErr(wrappedErr); ok || ret == Nil { - t.Fatal("TestIsRedisErr fail : wrapped error") + if ret, ok := IsValkeyErr(wrappedErr); ok || ret == Nil { + t.Fatal("TestIsValkeyErr fail : wrapped error") } } -func TestIsRedisBusyGroup(t *testing.T) { +func TestIsValkeyBusyGroup(t *testing.T) { err := errors.New("other") - if IsRedisBusyGroup(err) { - t.Fatal("TestIsRedisBusyGroup fail") + if IsValkeyBusyGroup(err) { + t.Fatal("TestIsValkeyBusyGroup fail") } - err = &RedisError{string: "BUSYGROUP Consumer Group name already exists"} - if !IsRedisBusyGroup(err) { - t.Fatal("TestIsRedisBusyGroup fail") + err = &ValkeyError{string: "BUSYGROUP Consumer Group name already exists"} + if !IsValkeyBusyGroup(err) { + t.Fatal("TestIsValkeyBusyGroup fail") } } //gocyclo:ignore -func TestRedisResult(t *testing.T) { +func TestValkeyResult(t *testing.T) { //Add erroneous type typeNames['t'] = "t" t.Run("ToInt64", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).ToInt64(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).ToInt64(); err == nil { t.Fatal("ToInt64 not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).ToInt64(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).ToInt64(); err == nil { t.Fatal("ToInt64 not failed as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: ':', integer: 1}}).ToInt64(); v != 1 { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: ':', integer: 1}}).ToInt64(); v != 1 { t.Fatal("ToInt64 not get value as expected") } }) t.Run("ToBool", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).ToBool(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).ToBool(); err == nil { t.Fatal("ToBool not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).ToBool(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).ToBool(); err == nil { t.Fatal("ToBool not failed as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: '#', integer: 1}}).ToBool(); !v { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: '#', integer: 1}}).ToBool(); !v { t.Fatal("ToBool not get value as expected") } }) t.Run("AsBool", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsBool(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsBool(); err == nil { t.Fatal("ToBool not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsBool(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsBool(); err == nil { t.Fatal("ToBool not failed as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: '#', integer: 1}}).AsBool(); !v { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: '#', integer: 1}}).AsBool(); !v { t.Fatal("ToBool not get value as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: ':', integer: 1}}).AsBool(); !v { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: ':', integer: 1}}).AsBool(); !v { t.Fatal("ToBool not get value as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: '+', string: "OK"}}).AsBool(); !v { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: '+', string: "OK"}}).AsBool(); !v { t.Fatal("ToBool not get value as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: '$', string: "OK"}}).AsBool(); !v { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: '$', string: "OK"}}).AsBool(); !v { t.Fatal("ToBool not get value as expected") } }) t.Run("ToFloat64", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).ToFloat64(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).ToFloat64(); err == nil { t.Fatal("ToFloat64 not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).ToFloat64(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).ToFloat64(); err == nil { t.Fatal("ToFloat64 not failed as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: ',', string: "0.1"}}).ToFloat64(); v != 0.1 { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: ',', string: "0.1"}}).ToFloat64(); v != 0.1 { t.Fatal("ToFloat64 not get value as expected") } }) t.Run("ToString", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).ToString(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).ToString(); err == nil { t.Fatal("ToString not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).ToString(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).ToString(); err == nil { t.Fatal("ToString not failed as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: '+', string: "0.1"}}).ToString(); v != "0.1" { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: '+', string: "0.1"}}).ToString(); v != "0.1" { t.Fatal("ToString not get value as expected") } }) t.Run("AsReader", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsReader(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsReader(); err == nil { t.Fatal("AsReader not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsReader(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsReader(); err == nil { t.Fatal("AsReader not failed as expected") } - r, _ := (RedisResult{val: RedisMessage{typ: '+', string: "0.1"}}).AsReader() + r, _ := (ValkeyResult{val: ValkeyMessage{typ: '+', string: "0.1"}}).AsReader() bs, _ := io.ReadAll(r) if !bytes.Equal(bs, []byte("0.1")) { t.Fatalf("AsReader not get value as expected %v", bs) @@ -159,13 +159,13 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsBytes", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsBytes(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsBytes(); err == nil { t.Fatal("AsBytes not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsBytes(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsBytes(); err == nil { t.Fatal("AsBytes not failed as expected") } - bs, _ := (RedisResult{val: RedisMessage{typ: '+', string: "0.1"}}).AsBytes() + bs, _ := (ValkeyResult{val: ValkeyMessage{typ: '+', string: "0.1"}}).AsBytes() if !bytes.Equal(bs, []byte("0.1")) { t.Fatalf("AsBytes not get value as expected %v", bs) } @@ -173,147 +173,147 @@ func TestRedisResult(t *testing.T) { t.Run("DecodeJSON", func(t *testing.T) { v := map[string]string{} - if err := (RedisResult{err: errors.New("other")}).DecodeJSON(&v); err == nil { + if err := (ValkeyResult{err: errors.New("other")}).DecodeJSON(&v); err == nil { t.Fatal("DecodeJSON not failed as expected") } - if err := (RedisResult{val: RedisMessage{typ: '-'}}).DecodeJSON(&v); err == nil { + if err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).DecodeJSON(&v); err == nil { t.Fatal("DecodeJSON not failed as expected") } - if _ = (RedisResult{val: RedisMessage{typ: '+', string: `{"k":"v"}`}}).DecodeJSON(&v); v["k"] != "v" { + if _ = (ValkeyResult{val: ValkeyMessage{typ: '+', string: `{"k":"v"}`}}).DecodeJSON(&v); v["k"] != "v" { t.Fatalf("DecodeJSON not get value as expected %v", v) } }) t.Run("AsInt64", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsInt64(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsInt64(); err == nil { t.Fatal("AsInt64 not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsInt64(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsInt64(); err == nil { t.Fatal("AsInt64 not failed as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: '+', string: "1"}}).AsInt64(); v != 1 { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: '+', string: "1"}}).AsInt64(); v != 1 { t.Fatal("AsInt64 not get value as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: ':', integer: 2}}).AsInt64(); v != 2 { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: ':', integer: 2}}).AsInt64(); v != 2 { t.Fatal("AsInt64 not get value as expected") } }) t.Run("AsUint64", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsUint64(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsUint64(); err == nil { t.Fatal("AsUint64 not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsUint64(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsUint64(); err == nil { t.Fatal("AsUint64 not failed as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: '+', string: "1"}}).AsUint64(); v != 1 { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: '+', string: "1"}}).AsUint64(); v != 1 { t.Fatal("AsUint64 not get value as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: ':', integer: 2}}).AsUint64(); v != 2 { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: ':', integer: 2}}).AsUint64(); v != 2 { t.Fatal("AsUint64 not get value as expected") } }) t.Run("AsFloat64", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsFloat64(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsFloat64(); err == nil { t.Fatal("AsFloat64 not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsFloat64(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsFloat64(); err == nil { t.Fatal("AsFloat64 not failed as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: '+', string: "1.1"}}).AsFloat64(); v != 1.1 { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: '+', string: "1.1"}}).AsFloat64(); v != 1.1 { t.Fatal("AsFloat64 not get value as expected") } - if v, _ := (RedisResult{val: RedisMessage{typ: ',', string: "2.2"}}).AsFloat64(); v != 2.2 { + if v, _ := (ValkeyResult{val: ValkeyMessage{typ: ',', string: "2.2"}}).AsFloat64(); v != 2.2 { t.Fatal("AsFloat64 not get value as expected") } }) t.Run("ToArray", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).ToArray(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).ToArray(); err == nil { t.Fatal("ToArray not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).ToArray(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).ToArray(); err == nil { t.Fatal("ToArray not failed as expected") } - values := []RedisMessage{{string: "item", typ: '+'}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).ToArray(); !reflect.DeepEqual(ret, values) { + values := []ValkeyMessage{{string: "item", typ: '+'}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).ToArray(); !reflect.DeepEqual(ret, values) { t.Fatal("ToArray not get value as expected") } }) t.Run("AsStrSlice", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsStrSlice(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsStrSlice(); err == nil { t.Fatal("AsStrSlice not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsStrSlice(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsStrSlice(); err == nil { t.Fatal("AsStrSlice not failed as expected") } - values := []RedisMessage{{string: "item", typ: '+'}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsStrSlice(); !reflect.DeepEqual(ret, []string{"item"}) { + values := []ValkeyMessage{{string: "item", typ: '+'}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).AsStrSlice(); !reflect.DeepEqual(ret, []string{"item"}) { t.Fatal("AsStrSlice not get value as expected") } }) t.Run("AsIntSlice", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsIntSlice(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsIntSlice(); err == nil { t.Fatal("AsIntSlice not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsIntSlice(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsIntSlice(); err == nil { t.Fatal("AsIntSlice not failed as expected") } - values := []RedisMessage{{integer: 2, typ: ':'}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsIntSlice(); !reflect.DeepEqual(ret, []int64{2}) { + values := []ValkeyMessage{{integer: 2, typ: ':'}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).AsIntSlice(); !reflect.DeepEqual(ret, []int64{2}) { t.Fatal("AsIntSlice not get value as expected") } - values = []RedisMessage{{string: "3", typ: '+'}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsIntSlice(); !reflect.DeepEqual(ret, []int64{3}) { + values = []ValkeyMessage{{string: "3", typ: '+'}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).AsIntSlice(); !reflect.DeepEqual(ret, []int64{3}) { t.Fatal("AsIntSlice not get value as expected") } - values = []RedisMessage{{string: "ab", typ: '+'}} - if _, err := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsIntSlice(); err == nil { + values = []ValkeyMessage{{string: "ab", typ: '+'}} + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).AsIntSlice(); err == nil { t.Fatal("AsIntSlice not failed as expected") } }) t.Run("AsFloatSlice", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsFloatSlice(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsFloatSlice(); err == nil { t.Fatal("AsFloatSlice not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsFloatSlice(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsFloatSlice(); err == nil { t.Fatal("AsFloatSlice not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{string: "fff", typ: ','}}}}).AsFloatSlice(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{string: "fff", typ: ','}}}}).AsFloatSlice(); err == nil { t.Fatal("AsFloatSlice not failed as expected") } - values := []RedisMessage{{integer: 1, typ: ':'}, {string: "2", typ: '+'}, {string: "3", typ: '$'}, {string: "4", typ: ','}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsFloatSlice(); !reflect.DeepEqual(ret, []float64{1, 2, 3, 4}) { + values := []ValkeyMessage{{integer: 1, typ: ':'}, {string: "2", typ: '+'}, {string: "3", typ: '$'}, {string: "4", typ: ','}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).AsFloatSlice(); !reflect.DeepEqual(ret, []float64{1, 2, 3, 4}) { t.Fatal("AsFloatSlice not get value as expected") } }) t.Run("AsBoolSlice", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsBoolSlice(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsBoolSlice(); err == nil { t.Fatal("AsBoolSlice not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsBoolSlice(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsBoolSlice(); err == nil { t.Fatal("AsBoolSlice not failed as expected") } - values := []RedisMessage{{integer: 1, typ: ':'}, {string: "0", typ: '+'}, {integer: 1, typ: typeBool}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsBoolSlice(); !reflect.DeepEqual(ret, []bool{true, false, true}) { + values := []ValkeyMessage{{integer: 1, typ: ':'}, {string: "0", typ: '+'}, {integer: 1, typ: typeBool}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).AsBoolSlice(); !reflect.DeepEqual(ret, []bool{true, false, true}) { t.Fatal("AsBoolSlice not get value as expected") } }) t.Run("AsMap", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsMap(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsMap(); err == nil { t.Fatal("AsMap not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsMap(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsMap(); err == nil { t.Fatal("AsMap not failed as expected") } - values := []RedisMessage{{string: "key", typ: '+'}, {string: "value", typ: '+'}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsMap(); !reflect.DeepEqual(map[string]RedisMessage{ + values := []ValkeyMessage{{string: "key", typ: '+'}, {string: "value", typ: '+'}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).AsMap(); !reflect.DeepEqual(map[string]ValkeyMessage{ values[0].string: values[1], }, ret) { t.Fatal("AsMap not get value as expected") @@ -321,14 +321,14 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsStrMap", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsStrMap(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsStrMap(); err == nil { t.Fatal("AsStrMap not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsStrMap(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsStrMap(); err == nil { t.Fatal("AsStrMap not failed as expected") } - values := []RedisMessage{{string: "key", typ: '+'}, {string: "value", typ: '+'}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsStrMap(); !reflect.DeepEqual(map[string]string{ + values := []ValkeyMessage{{string: "key", typ: '+'}, {string: "value", typ: '+'}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).AsStrMap(); !reflect.DeepEqual(map[string]string{ values[0].string: values[1].string, }, ret) { t.Fatal("AsStrMap not get value as expected") @@ -336,17 +336,17 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsIntMap", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsIntMap(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsIntMap(); err == nil { t.Fatal("AsIntMap not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsIntMap(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsIntMap(); err == nil { t.Fatal("AsIntMap not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{string: "key", typ: '+'}, {string: "value", typ: '+'}}}}).AsIntMap(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{string: "key", typ: '+'}, {string: "value", typ: '+'}}}}).AsIntMap(); err == nil { t.Fatal("AsIntMap not failed as expected") } - values := []RedisMessage{{string: "k1", typ: '+'}, {string: "1", typ: '+'}, {string: "k2", typ: '+'}, {integer: 2, typ: ':'}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsIntMap(); !reflect.DeepEqual(map[string]int64{ + values := []ValkeyMessage{{string: "k1", typ: '+'}, {string: "1", typ: '+'}, {string: "k2", typ: '+'}, {integer: 2, typ: ':'}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: values}}).AsIntMap(); !reflect.DeepEqual(map[string]int64{ "k1": 1, "k2": 2, }, ret) { @@ -355,14 +355,14 @@ func TestRedisResult(t *testing.T) { }) t.Run("ToMap", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).ToMap(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).ToMap(); err == nil { t.Fatal("ToMap not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).ToMap(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).ToMap(); err == nil { t.Fatal("ToMap not failed as expected") } - values := []RedisMessage{{string: "key", typ: '+'}, {string: "value", typ: '+'}} - if ret, _ := (RedisResult{val: RedisMessage{typ: '%', values: values}}).ToMap(); !reflect.DeepEqual(map[string]RedisMessage{ + values := []ValkeyMessage{{string: "key", typ: '+'}, {string: "value", typ: '+'}} + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '%', values: values}}).ToMap(); !reflect.DeepEqual(map[string]ValkeyMessage{ values[0].string: values[1], }, ret) { t.Fatal("ToMap not get value as expected") @@ -370,16 +370,16 @@ func TestRedisResult(t *testing.T) { }) t.Run("ToAny", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).ToAny(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).ToAny(); err == nil { t.Fatal("ToAny not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).ToAny(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).ToAny(); err == nil { t.Fatal("ToAny not failed as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{{typ: '+', string: "key"}, {typ: ':', integer: 1}}}, - {typ: '%', values: []RedisMessage{{typ: '+', string: "nil"}, {typ: '_'}}}, - {typ: '%', values: []RedisMessage{{typ: '+', string: "err"}, {typ: '-', string: "err"}}}, + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{{typ: '+', string: "key"}, {typ: ':', integer: 1}}}, + {typ: '%', values: []ValkeyMessage{{typ: '+', string: "nil"}, {typ: '_'}}}, + {typ: '%', values: []ValkeyMessage{{typ: '+', string: "err"}, {typ: '-', string: "err"}}}, {typ: ',', string: "1.2"}, {typ: '+', string: "str"}, {typ: '#', integer: 0}, @@ -388,11 +388,11 @@ func TestRedisResult(t *testing.T) { }}}).ToAny(); !reflect.DeepEqual([]any{ map[string]any{"key": int64(1)}, map[string]any{"nil": nil}, - map[string]any{"err": &RedisError{typ: '-', string: "err"}}, + map[string]any{"err": &ValkeyError{typ: '-', string: "err"}}, 1.2, "str", false, - &RedisError{typ: '-', string: "err"}, + &ValkeyError{typ: '-', string: "err"}, nil, }, ret) { t.Fatal("ToAny not get value as expected") @@ -400,19 +400,19 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsXRangeEntry", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsXRangeEntry(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsXRangeEntry(); err == nil { t.Fatal("AsXRangeEntry not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsXRangeEntry(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsXRangeEntry(); err == nil { t.Fatal("AsXRangeEntry not failed as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{string: "id", typ: '+'}, {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}}).AsXRangeEntry(); !reflect.DeepEqual(XRangeEntry{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{string: "id", typ: '+'}, {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}}).AsXRangeEntry(); !reflect.DeepEqual(XRangeEntry{ ID: "id", FieldValues: map[string]string{"a": "b"}, }, ret) { t.Fatal("AsXRangeEntry not get value as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{string: "id", typ: '+'}, {typ: '_'}}}}).AsXRangeEntry(); !reflect.DeepEqual(XRangeEntry{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{string: "id", typ: '+'}, {typ: '_'}}}}).AsXRangeEntry(); !reflect.DeepEqual(XRangeEntry{ ID: "id", FieldValues: nil, }, ret) { @@ -421,15 +421,15 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsXRange", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsXRange(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsXRange(); err == nil { t.Fatal("AsXRange not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsXRange(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsXRange(); err == nil { t.Fatal("AsXRange not failed as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{{string: "id1", typ: '+'}, {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}, - {typ: '*', values: []RedisMessage{{string: "id2", typ: '+'}, {typ: '_'}}}, + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{{string: "id1", typ: '+'}, {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}, + {typ: '*', values: []ValkeyMessage{{string: "id2", typ: '+'}, {typ: '_'}}}, }}}).AsXRange(); !reflect.DeepEqual([]XRangeEntry{{ ID: "id1", FieldValues: map[string]string{"a": "b"}, @@ -442,21 +442,21 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsXRead", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsXRead(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsXRead(); err == nil { t.Fatal("AsXRead not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsXRead(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsXRead(); err == nil { t.Fatal("AsXRead not failed as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '%', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '%', values: []ValkeyMessage{ {typ: '+', string: "stream1"}, - {typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{{string: "id1", typ: '+'}, {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}, - {typ: '*', values: []RedisMessage{{string: "id2", typ: '+'}, {typ: '_'}}}, + {typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{{string: "id1", typ: '+'}, {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}, + {typ: '*', values: []ValkeyMessage{{string: "id2", typ: '+'}, {typ: '_'}}}, }}, {typ: '+', string: "stream2"}, - {typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{{string: "id3", typ: '+'}, {typ: '*', values: []RedisMessage{{typ: '+', string: "c"}, {typ: '+', string: "d"}}}}}, + {typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{{string: "id3", typ: '+'}, {typ: '*', values: []ValkeyMessage{{typ: '+', string: "c"}, {typ: '+', string: "d"}}}}}, }}, }}}).AsXRead(); !reflect.DeepEqual(map[string][]XRangeEntry{ "stream1": { @@ -468,18 +468,18 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsXRead not get value as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "stream1"}, - {typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{{string: "id1", typ: '+'}, {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}, - {typ: '*', values: []RedisMessage{{string: "id2", typ: '+'}, {typ: '_'}}}, + {typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{{string: "id1", typ: '+'}, {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}, + {typ: '*', values: []ValkeyMessage{{string: "id2", typ: '+'}, {typ: '_'}}}, }}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "stream2"}, - {typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{{string: "id3", typ: '+'}, {typ: '*', values: []RedisMessage{{typ: '+', string: "c"}, {typ: '+', string: "d"}}}}}, + {typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{{string: "id3", typ: '+'}, {typ: '*', values: []ValkeyMessage{{typ: '+', string: "c"}, {typ: '+', string: "d"}}}}}, }}, }}, }}}).AsXRead(); !reflect.DeepEqual(map[string][]XRangeEntry{ @@ -495,19 +495,19 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsZScore", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsZScore(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsZScore(); err == nil { t.Fatal("AsZScore not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsZScore(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsZScore(); err == nil { t.Fatal("AsZScore not failed as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "m1"}, {typ: '+', string: "1"}, }}}).AsZScore(); !reflect.DeepEqual(ZScore{Member: "m1", Score: 1}, ret) { t.Fatal("AsZScore not get value as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "m1"}, {typ: ',', string: "1"}, }}}).AsZScore(); !reflect.DeepEqual(ZScore{Member: "m1", Score: 1}, ret) { @@ -516,13 +516,13 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsZScores", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsZScores(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsZScores(); err == nil { t.Fatal("AsZScores not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsZScores(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsZScores(); err == nil { t.Fatal("AsZScores not failed as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "m1"}, {typ: '+', string: "1"}, {typ: '+', string: "m2"}, @@ -533,12 +533,12 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsZScores not get value as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "m1"}, {typ: ',', string: "1"}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "m2"}, {typ: ',', string: "2"}, }}, @@ -551,15 +551,15 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsLMPop", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsLMPop(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsLMPop(); err == nil { t.Fatal("AsLMPop not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsLMPop(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsLMPop(); err == nil { t.Fatal("AsLMPop not failed as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "1"}, {typ: '+', string: "2"}, }}, @@ -572,20 +572,20 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsZMPop", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsZMPop(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsZMPop(); err == nil { t.Fatal("AsZMPop not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsZMPop(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsZMPop(); err == nil { t.Fatal("AsZMPop not failed as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k"}, - {typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "1"}, {typ: ',', string: "1"}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "2"}, {typ: ',', string: "2"}, }}, @@ -602,23 +602,23 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsFtSearch", func(t *testing.T) { - if _, _, err := (RedisResult{err: errors.New("other")}).AsFtSearch(); err == nil { + if _, _, err := (ValkeyResult{err: errors.New("other")}).AsFtSearch(); err == nil { t.Fatal("AsFtSearch not failed as expected") } - if _, _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsFtSearch(); err == nil { + if _, _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsFtSearch(); err == nil { t.Fatal("AsFtSearch not failed as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, {typ: '+', string: "a"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k1"}, {typ: '+', string: "v1"}, {typ: '+', string: "kk"}, {typ: '+', string: "vv"}, }}, {typ: '+', string: "b"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k2"}, {typ: '+', string: "v2"}, {typ: '+', string: "kk"}, @@ -630,17 +630,17 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtSearch not get value as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, {typ: '+', string: "a"}, {typ: '+', string: "1"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k1"}, {typ: '+', string: "v1"}, }}, {typ: '+', string: "b"}, {typ: '+', string: "2"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k2"}, {typ: '+', string: "v2"}, }}, @@ -650,10 +650,10 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtSearch not get value as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, {typ: '+', string: "a"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k1"}, {typ: '+', string: "v1"}, {typ: '+', string: "kk"}, @@ -664,7 +664,7 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtSearch not get value as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, {typ: '+', string: "a"}, {typ: '+', string: "b"}, @@ -674,7 +674,7 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtSearch not get value as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, {typ: '+', string: "a"}, {typ: '+', string: "1"}, @@ -686,7 +686,7 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtSearch not get value as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, {typ: '+', string: "1"}, {typ: '+', string: "2"}, @@ -696,7 +696,7 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtSearch not get value as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, {typ: '+', string: "a"}, }}}).AsFtSearch(); n != 3 || !reflect.DeepEqual([]FtSearchDoc{ @@ -704,7 +704,7 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtSearch not get value as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, }}}).AsFtSearch(); n != 3 || !reflect.DeepEqual([]FtSearchDoc{}, ret) { t.Fatal("AsFtSearch not get value as expected") @@ -712,27 +712,27 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsFtSearch RESP3", func(t *testing.T) { - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '%', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '%', values: []ValkeyMessage{ {typ: '+', string: "total_results"}, {typ: ':', integer: 3}, {typ: '+', string: "results"}, - {typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "id"}, {typ: '+', string: "1"}, {typ: '+', string: "extra_attributes"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "$"}, {typ: '+', string: "1"}, }}, {typ: '+', string: "score"}, {typ: ',', string: "1"}, }}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "id"}, {typ: '+', string: "2"}, {typ: '+', string: "extra_attributes"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "$"}, {typ: '+', string: "2"}, }}, @@ -741,23 +741,23 @@ func TestRedisResult(t *testing.T) { }}, }}, {typ: '+', string: "error"}, - {typ: '*', values: []RedisMessage{}}, + {typ: '*', values: []ValkeyMessage{}}, }}}).AsFtSearch(); n != 3 || !reflect.DeepEqual([]FtSearchDoc{ {Key: "1", Doc: map[string]string{"$": "1"}, Score: 1}, {Key: "2", Doc: map[string]string{"$": "2"}, Score: 2}, }, ret) { t.Fatal("AsFtSearch not get value as expected") } - if _, _, err := (RedisResult{val: RedisMessage{typ: '%', values: []RedisMessage{ + if _, _, err := (ValkeyResult{val: ValkeyMessage{typ: '%', values: []ValkeyMessage{ {typ: '+', string: "total_results"}, {typ: ':', integer: 3}, {typ: '+', string: "results"}, - {typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "id"}, {typ: '+', string: "1"}, {typ: '+', string: "extra_attributes"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "$"}, {typ: '+', string: "1"}, }}, @@ -766,7 +766,7 @@ func TestRedisResult(t *testing.T) { }}, }}, {typ: '+', string: "error"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "mytimeout"}, }}, }}}).AsFtSearch(); err == nil || err.Error() != "mytimeout" { @@ -775,21 +775,21 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsFtAggregate", func(t *testing.T) { - if _, _, err := (RedisResult{err: errors.New("other")}).AsFtAggregate(); err == nil { + if _, _, err := (ValkeyResult{err: errors.New("other")}).AsFtAggregate(); err == nil { t.Fatal("AsFtAggregate not failed as expected") } - if _, _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsFtAggregate(); err == nil { + if _, _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsFtAggregate(); err == nil { t.Fatal("AsFtAggregate not failed as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k1"}, {typ: '+', string: "v1"}, {typ: '+', string: "kk"}, {typ: '+', string: "vv"}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k2"}, {typ: '+', string: "v2"}, {typ: '+', string: "kk"}, @@ -801,9 +801,9 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtAggregate not get value as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k1"}, {typ: '+', string: "v1"}, {typ: '+', string: "kk"}, @@ -814,7 +814,7 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtAggregate not get value as expected") } - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, }}}).AsFtAggregate(); n != 3 || !reflect.DeepEqual([]map[string]string{}, ret) { t.Fatal("AsFtAggregate not get value as expected") @@ -822,49 +822,49 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsFtAggregate RESP3", func(t *testing.T) { - if n, ret, _ := (RedisResult{val: RedisMessage{typ: '%', values: []RedisMessage{ + if n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '%', values: []ValkeyMessage{ {typ: '+', string: "total_results"}, {typ: ':', integer: 3}, {typ: '+', string: "results"}, - {typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "extra_attributes"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "$"}, {typ: '+', string: "1"}, }}, }}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "extra_attributes"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "$"}, {typ: '+', string: "2"}, }}, }}, }}, {typ: '+', string: "error"}, - {typ: '*', values: []RedisMessage{}}, + {typ: '*', values: []ValkeyMessage{}}, }}}).AsFtAggregate(); n != 3 || !reflect.DeepEqual([]map[string]string{ {"$": "1"}, {"$": "2"}, }, ret) { t.Fatal("AsFtAggregate not get value as expected") } - if _, _, err := (RedisResult{val: RedisMessage{typ: '%', values: []RedisMessage{ + if _, _, err := (ValkeyResult{val: ValkeyMessage{typ: '%', values: []ValkeyMessage{ {typ: '+', string: "total_results"}, {typ: ':', integer: 3}, {typ: '+', string: "results"}, - {typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "extra_attributes"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "$"}, {typ: '+', string: "1"}, }}, }}, }}, {typ: '+', string: "error"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "mytimeout"}, }}, }}}).AsFtAggregate(); err == nil || err.Error() != "mytimeout" { @@ -873,22 +873,22 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsFtAggregate Cursor", func(t *testing.T) { - if _, _, _, err := (RedisResult{err: errors.New("other")}).AsFtAggregateCursor(); err == nil { + if _, _, _, err := (ValkeyResult{err: errors.New("other")}).AsFtAggregateCursor(); err == nil { t.Fatal("AsFtAggregate not failed as expected") } - if _, _, _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsFtAggregateCursor(); err == nil { + if _, _, _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsFtAggregateCursor(); err == nil { t.Fatal("AsFtAggregate not failed as expected") } - if c, n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if c, n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k1"}, {typ: '+', string: "v1"}, {typ: '+', string: "kk"}, {typ: '+', string: "vv"}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k2"}, {typ: '+', string: "v2"}, {typ: '+', string: "kk"}, @@ -902,10 +902,10 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtAggregate not get value as expected") } - if c, n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if c, n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k1"}, {typ: '+', string: "v1"}, {typ: '+', string: "kk"}, @@ -918,8 +918,8 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtAggregate not get value as expected") } - if c, n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if c, n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3}, }}, {typ: ':', integer: 1}, @@ -929,29 +929,29 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsFtAggregate Cursor RESP3", func(t *testing.T) { - if c, n, ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + if c, n, ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "total_results"}, {typ: ':', integer: 3}, {typ: '+', string: "results"}, - {typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "extra_attributes"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "$"}, {typ: '+', string: "1"}, }}, }}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "extra_attributes"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "$"}, {typ: '+', string: "2"}, }}, }}, }}, {typ: '+', string: "error"}, - {typ: '*', values: []RedisMessage{}}, + {typ: '*', values: []ValkeyMessage{}}, }}, {typ: ':', integer: 1}, }}}).AsFtAggregateCursor(); c != 1 || n != 3 || !reflect.DeepEqual([]map[string]string{ @@ -960,22 +960,22 @@ func TestRedisResult(t *testing.T) { }, ret) { t.Fatal("AsFtAggregate not get value as expected") } - if _, _, _, err := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + if _, _, _, err := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "total_results"}, {typ: ':', integer: 3}, {typ: '+', string: "results"}, - {typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "extra_attributes"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "$"}, {typ: '+', string: "1"}, }}, }}, }}, {typ: '+', string: "error"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "mytimeout"}, }}, }}, @@ -986,28 +986,28 @@ func TestRedisResult(t *testing.T) { }) t.Run("AsGeosearch", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsGeosearch(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsGeosearch(); err == nil { t.Fatal("AsGeosearch not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsGeosearch(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsGeosearch(); err == nil { t.Fatal("AsGeosearch not failed as expected") } //WithDist, WithHash, WithCoord - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k1"}, {typ: ',', string: "2.5"}, {typ: ':', integer: 1}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ',', string: "28.0473"}, {typ: ',', string: "26.2041"}, }}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k2"}, {typ: ',', string: "4.5"}, {typ: ':', integer: 4}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ',', string: "72.4973"}, {typ: ',', string: "13.2263"}, }}, @@ -1019,19 +1019,19 @@ func TestRedisResult(t *testing.T) { t.Fatal("AsGeosearch not get value as expected") } //WithHash, WithCoord - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k1"}, {typ: ':', integer: 1}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ',', string: "84.3877"}, {typ: ',', string: "33.7488"}, }}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k2"}, {typ: ':', integer: 4}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ',', string: "115.8613"}, {typ: ',', string: "31.9523"}, }}, @@ -1043,19 +1043,19 @@ func TestRedisResult(t *testing.T) { t.Fatal("AsGeosearch not get value as expected") } //WithDist, WithCoord - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k1"}, {typ: ',', string: "2.50076"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ',', string: "84.3877"}, {typ: ',', string: "33.7488"}, }}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k2"}, {typ: ',', string: "1024.96"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ',', string: "115.8613"}, {typ: ',', string: "31.9523"}, }}, @@ -1067,17 +1067,17 @@ func TestRedisResult(t *testing.T) { t.Fatal("AsGeosearch not get value as expected") } //WithCoord - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k1"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ',', string: "122.4194"}, {typ: ',', string: "37.7749"}, }}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k2"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ',', string: "35.6762"}, {typ: ',', string: "139.6503"}, }}, @@ -1089,12 +1089,12 @@ func TestRedisResult(t *testing.T) { t.Fatal("AsGeosearch not get value as expected") } //WithDist - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k1"}, {typ: ',', string: "2.50076"}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k2"}, {typ: ',', string: strconv.FormatFloat(math.MaxFloat64, 'E', -1, 64)}, }}, @@ -1105,12 +1105,12 @@ func TestRedisResult(t *testing.T) { t.Fatal("AsGeosearch not get value as expected") } //WithHash - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k1"}, {typ: ':', integer: math.MaxInt64}, }}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k2"}, {typ: ':', integer: 22296}, }}, @@ -1121,7 +1121,7 @@ func TestRedisResult(t *testing.T) { t.Fatal("AsGeosearch not get value as expected") } //With no additional options - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k1"}, {typ: '$', string: "k2"}, }}}).AsGeosearch(); !reflect.DeepEqual([]GeoLocation{ @@ -1131,8 +1131,8 @@ func TestRedisResult(t *testing.T) { t.Fatal("AsGeosearch not get value as expected") } //With wrong distance - if _, err := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k1"}, {typ: ',', string: "wrong distance"}, }}, @@ -1140,10 +1140,10 @@ func TestRedisResult(t *testing.T) { t.Fatal("AsGeosearch not failed as expected") } //With wrong coordinates - if _, err := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '$', string: "k2"}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ',', string: "35.6762"}, }}, }}, @@ -1153,67 +1153,67 @@ func TestRedisResult(t *testing.T) { }) t.Run("IsCacheHit", func(t *testing.T) { - if (RedisResult{err: errors.New("other")}).IsCacheHit() { + if (ValkeyResult{err: errors.New("other")}).IsCacheHit() { t.Fatal("IsCacheHit not as expected") } - if !(RedisResult{val: RedisMessage{attrs: cacheMark}}).IsCacheHit() { + if !(ValkeyResult{val: ValkeyMessage{attrs: cacheMark}}).IsCacheHit() { t.Fatal("IsCacheHit not as expected") } }) t.Run("CacheTTL", func(t *testing.T) { - if (RedisResult{err: errors.New("other")}).CacheTTL() != -1 { + if (ValkeyResult{err: errors.New("other")}).CacheTTL() != -1 { t.Fatal("CacheTTL != -1") } - m := RedisMessage{} + m := ValkeyMessage{} m.setExpireAt(time.Now().Add(time.Millisecond * 100).UnixMilli()) - if (RedisResult{val: m}).CacheTTL() <= 0 { + if (ValkeyResult{val: m}).CacheTTL() <= 0 { t.Fatal("CacheTTL <= 0") } time.Sleep(150 * time.Millisecond) - if (RedisResult{val: m}).CacheTTL() != 0 { + if (ValkeyResult{val: m}).CacheTTL() != 0 { t.Fatal("CacheTTL != 0") } }) t.Run("CachePTTL", func(t *testing.T) { - if (RedisResult{err: errors.New("other")}).CachePTTL() != -1 { + if (ValkeyResult{err: errors.New("other")}).CachePTTL() != -1 { t.Fatal("CachePTTL != -1") } - m := RedisMessage{} + m := ValkeyMessage{} m.setExpireAt(time.Now().Add(time.Millisecond * 100).UnixMilli()) - if (RedisResult{val: m}).CachePTTL() <= 0 { + if (ValkeyResult{val: m}).CachePTTL() <= 0 { t.Fatal("CachePTTL <= 0") } time.Sleep(150 * time.Millisecond) - if (RedisResult{val: m}).CachePTTL() != 0 { + if (ValkeyResult{val: m}).CachePTTL() != 0 { t.Fatal("CachePTTL != 0") } }) t.Run("CachePXAT", func(t *testing.T) { - if (RedisResult{err: errors.New("other")}).CachePXAT() != -1 { + if (ValkeyResult{err: errors.New("other")}).CachePXAT() != -1 { t.Fatal("CachePTTL != -1") } - m := RedisMessage{} + m := ValkeyMessage{} m.setExpireAt(time.Now().Add(time.Millisecond * 100).UnixMilli()) - if (RedisResult{val: m}).CachePXAT() <= 0 { + if (ValkeyResult{val: m}).CachePXAT() <= 0 { t.Fatal("CachePXAT <= 0") } }) t.Run("Stringer", func(t *testing.T) { tests := []struct { - input RedisResult + input ValkeyResult expected string }{ { - input: RedisResult{ - val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + input: ValkeyResult{ + val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 0}, - {typ: '*', values: []RedisMessage{ // master + {typ: '*', values: []ValkeyMessage{ // master {typ: '+', string: "127.0.3.1"}, {typ: ':', integer: 3}, {typ: '+', string: ""}, @@ -1224,7 +1224,7 @@ func TestRedisResult(t *testing.T) { expected: `{"Message":{"Value":[{"Value":[{"Value":0,"Type":"int64"},{"Value":0,"Type":"int64"},{"Value":[{"Value":"127.0.3.1","Type":"simple string"},{"Value":3,"Type":"int64"},{"Value":"","Type":"simple string"}],"Type":"array"}],"Type":"array"}],"Type":"array"}}`, }, { - input: RedisResult{err: errors.New("foo")}, + input: ValkeyResult{err: errors.New("foo")}, expected: `{"Error":"foo"}`, }, } @@ -1238,401 +1238,401 @@ func TestRedisResult(t *testing.T) { } //gocyclo:ignore -func TestRedisMessage(t *testing.T) { +func TestValkeyMessage(t *testing.T) { //Add erroneous type typeNames['t'] = "t" t.Run("IsNil", func(t *testing.T) { - if !(&RedisMessage{typ: '_'}).IsNil() { + if !(&ValkeyMessage{typ: '_'}).IsNil() { t.Fatal("IsNil fail") } }) t.Run("Trim ERR prefix", func(t *testing.T) { // kvrocks: https://github.com/redis/rueidis/issues/152#issuecomment-1333923750 - if (&RedisMessage{typ: '-', string: "ERR no_prefix"}).Error().Error() != "no_prefix" { + if (&ValkeyMessage{typ: '-', string: "ERR no_prefix"}).Error().Error() != "no_prefix" { t.Fatal("fail to trim ERR") } }) t.Run("ToInt64", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).ToInt64(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).ToInt64(); err == nil { t.Fatal("ToInt64 not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a RESP3 int64") { + if !strings.Contains(recover().(string), "valkey message type t is not a RESP3 int64") { t.Fatal("ToInt64 not panic as expected") } }() - (&RedisMessage{typ: 't'}).ToInt64() + (&ValkeyMessage{typ: 't'}).ToInt64() }) t.Run("ToBool", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).ToBool(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).ToBool(); err == nil { t.Fatal("ToBool not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a RESP3 bool") { + if !strings.Contains(recover().(string), "valkey message type t is not a RESP3 bool") { t.Fatal("ToBool not panic as expected") } }() - (&RedisMessage{typ: 't'}).ToBool() + (&ValkeyMessage{typ: 't'}).ToBool() }) t.Run("AsBool", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsBool(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsBool(); err == nil { t.Fatal("AsBool not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a int, string or bool") { + if !strings.Contains(recover().(string), "valkey message type t is not a int, string or bool") { t.Fatal("AsBool not panic as expected") } }() - (&RedisMessage{typ: 't'}).AsBool() + (&ValkeyMessage{typ: 't'}).AsBool() }) t.Run("ToFloat64", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).ToFloat64(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).ToFloat64(); err == nil { t.Fatal("ToFloat64 not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a RESP3 float64") { + if !strings.Contains(recover().(string), "valkey message type t is not a RESP3 float64") { t.Fatal("ToFloat64 not panic as expected") } }() - (&RedisMessage{typ: 't'}).ToFloat64() + (&ValkeyMessage{typ: 't'}).ToFloat64() }) t.Run("ToString", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).ToString(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).ToString(); err == nil { t.Fatal("ToString not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a string", typeNames[':'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a string", typeNames[':'])) { t.Fatal("ToString not panic as expected") } }() - (&RedisMessage{typ: ':'}).ToString() + (&ValkeyMessage{typ: ':'}).ToString() }) t.Run("AsReader", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsReader(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsReader(); err == nil { t.Fatal("AsReader not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a string", typeNames[':'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a string", typeNames[':'])) { t.Fatal("AsReader not panic as expected") } }() - (&RedisMessage{typ: ':'}).AsReader() + (&ValkeyMessage{typ: ':'}).AsReader() }) t.Run("AsBytes", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsBytes(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsBytes(); err == nil { t.Fatal("AsBytes not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a string", typeNames[':'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a string", typeNames[':'])) { t.Fatal("AsBytes not panic as expected") } }() - (&RedisMessage{typ: ':'}).AsBytes() + (&ValkeyMessage{typ: ':'}).AsBytes() }) t.Run("DecodeJSON", func(t *testing.T) { - if err := (&RedisMessage{typ: '_'}).DecodeJSON(nil); err == nil { + if err := (&ValkeyMessage{typ: '_'}).DecodeJSON(nil); err == nil { t.Fatal("DecodeJSON not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a string", typeNames[':'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a string", typeNames[':'])) { t.Fatal("DecodeJSON not panic as expected") } }() - (&RedisMessage{typ: ':'}).DecodeJSON(nil) + (&ValkeyMessage{typ: ':'}).DecodeJSON(nil) }) t.Run("AsInt64", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsInt64(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsInt64(); err == nil { t.Fatal("AsInt64 not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a string", typeNames['*'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a string", typeNames['*'])) { t.Fatal("AsInt64 not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{{}}}).AsInt64() + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{{}}}).AsInt64() }) t.Run("AsUint64", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsUint64(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsUint64(); err == nil { t.Fatal("AsUint64 not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a string", typeNames['*'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a string", typeNames['*'])) { t.Fatal("AsUint64 not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{{}}}).AsUint64() + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{{}}}).AsUint64() }) t.Run("AsFloat64", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsFloat64(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsFloat64(); err == nil { t.Fatal("AsFloat64 not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a string", typeNames[':'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a string", typeNames[':'])) { t.Fatal("AsFloat64 not panic as expected") } }() - (&RedisMessage{typ: ':'}).AsFloat64() + (&ValkeyMessage{typ: ':'}).AsFloat64() }) t.Run("ToArray", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).ToArray(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).ToArray(); err == nil { t.Fatal("ToArray not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a array") { + if !strings.Contains(recover().(string), "valkey message type t is not a array") { t.Fatal("ToArray not panic as expected") } }() - (&RedisMessage{typ: 't'}).ToArray() + (&ValkeyMessage{typ: 't'}).ToArray() }) t.Run("AsStrSlice", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsStrSlice(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsStrSlice(); err == nil { t.Fatal("AsStrSlice not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a array") { + if !strings.Contains(recover().(string), "valkey message type t is not a array") { t.Fatal("AsStrSlice not panic as expected") } }() - (&RedisMessage{typ: 't'}).AsStrSlice() + (&ValkeyMessage{typ: 't'}).AsStrSlice() }) t.Run("AsIntSlice", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsIntSlice(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsIntSlice(); err == nil { t.Fatal("AsIntSlice not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a array") { + if !strings.Contains(recover().(string), "valkey message type t is not a array") { t.Fatal("AsIntSlice not panic as expected") } }() - (&RedisMessage{typ: 't'}).AsIntSlice() + (&ValkeyMessage{typ: 't'}).AsIntSlice() }) t.Run("AsFloatSlice", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsFloatSlice(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsFloatSlice(); err == nil { t.Fatal("AsFloatSlice not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a array") { + if !strings.Contains(recover().(string), "valkey message type t is not a array") { t.Fatal("AsFloatSlice not panic as expected") } }() - (&RedisMessage{typ: 't'}).AsFloatSlice() + (&ValkeyMessage{typ: 't'}).AsFloatSlice() }) t.Run("AsBoolSlice", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsBoolSlice(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsBoolSlice(); err == nil { t.Fatal("AsBoolSlice not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a array") { + if !strings.Contains(recover().(string), "valkey message type t is not a array") { t.Fatal("AsBoolSlice not panic as expected") } }() - (&RedisMessage{typ: 't'}).AsBoolSlice() + (&ValkeyMessage{typ: 't'}).AsBoolSlice() }) t.Run("AsMap", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsMap(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsMap(); err == nil { t.Fatal("AsMap not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a map/array/set or its length is not even") { + if !strings.Contains(recover().(string), "valkey message type t is not a map/array/set or its length is not even") { t.Fatal("AsMap not panic as expected") } }() - (&RedisMessage{typ: 't'}).AsMap() + (&ValkeyMessage{typ: 't'}).AsMap() }) t.Run("AsStrMap", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsStrMap(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsStrMap(); err == nil { t.Fatal("AsStrMap not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a map/array/set") { + if !strings.Contains(recover().(string), "valkey message type t is not a map/array/set") { t.Fatal("AsMap not panic as expected") } }() - (&RedisMessage{typ: 't'}).AsStrMap() + (&ValkeyMessage{typ: 't'}).AsStrMap() }) t.Run("AsIntMap", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsIntMap(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsIntMap(); err == nil { t.Fatal("AsIntMap not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a map/array/set") { + if !strings.Contains(recover().(string), "valkey message type t is not a map/array/set") { t.Fatal("AsMap not panic as expected") } }() - (&RedisMessage{typ: 't'}).AsIntMap() + (&ValkeyMessage{typ: 't'}).AsIntMap() }) t.Run("ToMap", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).ToMap(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).ToMap(); err == nil { t.Fatal("ToMap not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a RESP3 map") { + if !strings.Contains(recover().(string), "valkey message type t is not a RESP3 map") { t.Fatal("ToMap not panic as expected") } }() - (&RedisMessage{typ: 't'}).ToMap() + (&ValkeyMessage{typ: 't'}).ToMap() }) t.Run("ToAny", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).ToAny(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).ToAny(); err == nil { t.Fatal("ToAny not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a supported in ToAny") { + if !strings.Contains(recover().(string), "valkey message type t is not a supported in ToAny") { t.Fatal("ToAny not panic as expected") } }() - (&RedisMessage{typ: 't'}).ToAny() + (&ValkeyMessage{typ: 't'}).ToAny() }) t.Run("AsXRangeEntry - no range id", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsXRangeEntry(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsXRangeEntry(); err == nil { t.Fatal("AsXRangeEntry not failed as expected") } - if _, err := (&RedisMessage{typ: '*'}).AsXRangeEntry(); err == nil { + if _, err := (&ValkeyMessage{typ: '*'}).AsXRangeEntry(); err == nil { t.Fatal("AsXRangeEntry not failed as expected") } - if _, err := (&RedisMessage{typ: '*', values: []RedisMessage{{typ: '_'}, {typ: '%'}}}).AsXRangeEntry(); err == nil { + if _, err := (&ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '_'}, {typ: '%'}}}).AsXRangeEntry(); err == nil { t.Fatal("AsXRangeEntry not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a string", typeNames[':'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a string", typeNames[':'])) { t.Fatal("AsXRangeEntry not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{{typ: ':'}, {typ: '%'}}}).AsXRangeEntry() + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: ':'}, {typ: '%'}}}).AsXRangeEntry() }) t.Run("AsXRangeEntry - no range field values", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsXRangeEntry(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsXRangeEntry(); err == nil { t.Fatal("AsXRangeEntry not failed as expected") } - if _, err := (&RedisMessage{typ: '*'}).AsXRangeEntry(); err == nil { + if _, err := (&ValkeyMessage{typ: '*'}).AsXRangeEntry(); err == nil { t.Fatal("AsXRangeEntry not failed as expected") } - if _, err := (&RedisMessage{typ: '*', values: []RedisMessage{{typ: '+'}, {typ: '-'}}}).AsXRangeEntry(); err == nil { + if _, err := (&ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+'}, {typ: '-'}}}).AsXRangeEntry(); err == nil { t.Fatal("AsXRangeEntry not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a map/array/set") { + if !strings.Contains(recover().(string), "valkey message type t is not a map/array/set") { t.Fatal("AsXRangeEntry not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{{typ: '+'}, {typ: 't'}}}).AsXRangeEntry() + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+'}, {typ: 't'}}}).AsXRangeEntry() }) t.Run("AsXRange", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsXRange(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsXRange(); err == nil { t.Fatal("AsXRange not failed as expected") } - if _, err := (&RedisMessage{typ: '*', values: []RedisMessage{{typ: '_'}}}).AsXRange(); err == nil { + if _, err := (&ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '_'}}}).AsXRange(); err == nil { t.Fatal("AsXRange not failed as expected") } }) t.Run("AsXRead", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsXRead(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsXRead(); err == nil { t.Fatal("AsXRead not failed as expected") } - if _, err := (&RedisMessage{typ: '%', values: []RedisMessage{ + if _, err := (&ValkeyMessage{typ: '%', values: []ValkeyMessage{ {typ: '+', string: "stream1"}, - {typ: '*', values: []RedisMessage{{typ: '*', values: []RedisMessage{{string: "id1", typ: '+'}}}}}, + {typ: '*', values: []ValkeyMessage{{typ: '*', values: []ValkeyMessage{{string: "id1", typ: '+'}}}}}, }}).AsXRead(); err == nil { t.Fatal("AsXRead not failed as expected") } - if _, err := (&RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if _, err := (&ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "stream1"}, }}, }}).AsXRead(); err == nil { t.Fatal("AsXRead not failed as expected") } - if _, err := (&RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if _, err := (&ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "stream1"}, - {typ: '*', values: []RedisMessage{{typ: '*', values: []RedisMessage{{string: "id1", typ: '+'}}}}}, + {typ: '*', values: []ValkeyMessage{{typ: '*', values: []ValkeyMessage{{string: "id1", typ: '+'}}}}}, }}, }}).AsXRead(); err == nil { t.Fatal("AsXRead not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message type t is not a map/array/set") { + if !strings.Contains(recover().(string), "valkey message type t is not a map/array/set") { t.Fatal("AsXRangeEntry not panic as expected") } }() - (&RedisMessage{typ: 't'}).AsXRead() + (&ValkeyMessage{typ: 't'}).AsXRead() }) t.Run("AsZScore", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsZScore(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsZScore(); err == nil { t.Fatal("AsZScore not failed as expected") } defer func() { - if !strings.Contains(recover().(string), "redis message is not a map/array/set or its length is not 2") { + if !strings.Contains(recover().(string), "valkey message is not a map/array/set or its length is not 2") { t.Fatal("AsZScore not panic as expected") } }() - (&RedisMessage{typ: '*'}).AsZScore() + (&ValkeyMessage{typ: '*'}).AsZScore() }) t.Run("AsZScores", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsZScores(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsZScores(); err == nil { t.Fatal("AsZScore not failed as expected") } - if _, err := (&RedisMessage{typ: '*', values: []RedisMessage{ + if _, err := (&ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "m1"}, {typ: '+', string: "m2"}, }}).AsZScores(); err == nil { t.Fatal("AsZScores not fails as expected") } - if _, err := (&RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + if _, err := (&ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "m1"}, {typ: '+', string: "m2"}, }}, @@ -1642,129 +1642,129 @@ func TestRedisMessage(t *testing.T) { }) t.Run("AsLMPop", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsLMPop(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsLMPop(); err == nil { t.Fatal("AsLMPop not failed as expected") } - if _, err := (&RedisMessage{typ: '*', values: []RedisMessage{ + if _, err := (&ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k"}, {typ: '_'}, }}).AsLMPop(); err == nil { t.Fatal("AsLMPop not fails as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a LMPOP response", typeNames['*'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a LMPOP response", typeNames['*'])) { t.Fatal("AsLMPop not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{ + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k"}, }}).AsLMPop() }) t.Run("AsZMPop", func(t *testing.T) { - if _, err := (&RedisMessage{typ: '_'}).AsZMPop(); err == nil { + if _, err := (&ValkeyMessage{typ: '_'}).AsZMPop(); err == nil { t.Fatal("AsZMPop not failed as expected") } - if _, err := (&RedisMessage{typ: '*', values: []RedisMessage{ + if _, err := (&ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k"}, {typ: '_'}, }}).AsZMPop(); err == nil { t.Fatal("AsZMPop not fails as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a ZMPOP response", typeNames['*'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a ZMPOP response", typeNames['*'])) { t.Fatal("AsZMPop not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{ + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "k"}, }}).AsZMPop() }) t.Run("AsFtSearch", func(t *testing.T) { - if _, _, err := (&RedisMessage{typ: '_'}).AsFtSearch(); err == nil { + if _, _, err := (&ValkeyMessage{typ: '_'}).AsFtSearch(); err == nil { t.Fatal("AsFtSearch not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a FT.SEARCH response", typeNames['*'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a FT.SEARCH response", typeNames['*'])) { t.Fatal("AsFtSearch not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{}}).AsFtSearch() + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{}}).AsFtSearch() }) t.Run("AsFtAggregate", func(t *testing.T) { - if _, _, err := (&RedisMessage{typ: '_'}).AsFtAggregate(); err == nil { + if _, _, err := (&ValkeyMessage{typ: '_'}).AsFtAggregate(); err == nil { t.Fatal("AsFtAggregate not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a FT.AGGREGATE response", typeNames['*'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a FT.AGGREGATE response", typeNames['*'])) { t.Fatal("AsFtAggregate not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{}}).AsFtAggregate() + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{}}).AsFtAggregate() }) t.Run("AsFtAggregateCursor", func(t *testing.T) { - if _, _, _, err := (&RedisMessage{typ: '_'}).AsFtAggregateCursor(); err == nil { + if _, _, _, err := (&ValkeyMessage{typ: '_'}).AsFtAggregateCursor(); err == nil { t.Fatal("AsFtAggregate not failed as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a FT.AGGREGATE response", typeNames['*'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a FT.AGGREGATE response", typeNames['*'])) { t.Fatal("AsFtAggregate not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{}}).AsFtAggregateCursor() + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{}}).AsFtAggregateCursor() }) t.Run("AsScanEntry", func(t *testing.T) { - if _, err := (RedisResult{err: errors.New("other")}).AsScanEntry(); err == nil { + if _, err := (ValkeyResult{err: errors.New("other")}).AsScanEntry(); err == nil { t.Fatal("AsScanEntry not failed as expected") } - if _, err := (RedisResult{val: RedisMessage{typ: '-'}}).AsScanEntry(); err == nil { + if _, err := (ValkeyResult{val: ValkeyMessage{typ: '-'}}).AsScanEntry(); err == nil { t.Fatal("AsScanEntry not failed as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{string: "1", typ: '+'}, {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}}).AsScanEntry(); !reflect.DeepEqual(ScanEntry{ + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{string: "1", typ: '+'}, {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}, {typ: '+', string: "b"}}}}}}).AsScanEntry(); !reflect.DeepEqual(ScanEntry{ Cursor: 1, Elements: []string{"a", "b"}, }, ret) { t.Fatal("AsScanEntry not get value as expected") } - if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{string: "0", typ: '+'}, {typ: '_'}}}}).AsScanEntry(); !reflect.DeepEqual(ScanEntry{}, ret) { + if ret, _ := (ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{string: "0", typ: '+'}, {typ: '_'}}}}).AsScanEntry(); !reflect.DeepEqual(ScanEntry{}, ret) { t.Fatal("AsScanEntry not get value as expected") } defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s is not a scan response or its length is not at least 2", typeNames['*'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s is not a scan response or its length is not at least 2", typeNames['*'])) { t.Fatal("AsScanEntry not panic as expected") } }() - (&RedisMessage{typ: '*', values: []RedisMessage{{typ: ':'}}}).AsScanEntry() + (&ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: ':'}}}).AsScanEntry() }) t.Run("ToMap with non string key", func(t *testing.T) { defer func() { - if !strings.Contains(recover().(string), fmt.Sprintf("redis message type %s as map key is not supported", typeNames[':'])) { + if !strings.Contains(recover().(string), fmt.Sprintf("valkey message type %s as map key is not supported", typeNames[':'])) { t.Fatal("ToMap not panic as expected") } }() - (&RedisMessage{typ: '%', values: []RedisMessage{{typ: ':'}, {typ: ':'}}}).ToMap() + (&ValkeyMessage{typ: '%', values: []ValkeyMessage{{typ: ':'}, {typ: ':'}}}).ToMap() }) t.Run("IsCacheHit", func(t *testing.T) { - if (&RedisMessage{typ: '_'}).IsCacheHit() { + if (&ValkeyMessage{typ: '_'}).IsCacheHit() { t.Fatal("IsCacheHit not as expected") } - if !(&RedisMessage{typ: '_', attrs: cacheMark}).IsCacheHit() { + if !(&ValkeyMessage{typ: '_', attrs: cacheMark}).IsCacheHit() { t.Fatal("IsCacheHit not as expected") } }) t.Run("CacheTTL", func(t *testing.T) { - if (&RedisMessage{typ: '_'}).CacheTTL() != -1 { + if (&ValkeyMessage{typ: '_'}).CacheTTL() != -1 { t.Fatal("CacheTTL != -1") } - m := &RedisMessage{typ: '_'} + m := &ValkeyMessage{typ: '_'} m.setExpireAt(time.Now().Add(time.Millisecond * 100).UnixMilli()) if m.CacheTTL() <= 0 { t.Fatal("CacheTTL <= 0") @@ -1776,10 +1776,10 @@ func TestRedisMessage(t *testing.T) { }) t.Run("CachePTTL", func(t *testing.T) { - if (&RedisMessage{typ: '_'}).CachePTTL() != -1 { + if (&ValkeyMessage{typ: '_'}).CachePTTL() != -1 { t.Fatal("CachePTTL != -1") } - m := &RedisMessage{typ: '_'} + m := &ValkeyMessage{typ: '_'} m.setExpireAt(time.Now().Add(time.Millisecond * 100).UnixMilli()) if m.CachePTTL() <= 0 { t.Fatal("CachePTTL <= 0") @@ -1791,10 +1791,10 @@ func TestRedisMessage(t *testing.T) { }) t.Run("CachePXAT", func(t *testing.T) { - if (&RedisMessage{typ: '_'}).CachePXAT() != -1 { + if (&ValkeyMessage{typ: '_'}).CachePXAT() != -1 { t.Fatal("CachePXAT != -1") } - m := &RedisMessage{typ: '_'} + m := &ValkeyMessage{typ: '_'} m.setExpireAt(time.Now().Add(time.Millisecond * 100).UnixMilli()) if m.CachePXAT() <= 0 { t.Fatal("CachePXAT <= 0") @@ -1803,15 +1803,15 @@ func TestRedisMessage(t *testing.T) { t.Run("Stringer", func(t *testing.T) { tests := []struct { - input RedisMessage + input ValkeyMessage expected string }{ { - input: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '*', values: []RedisMessage{ + input: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 0}, {typ: ':', integer: 0}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "127.0.3.1"}, {typ: ':', integer: 3}, {typ: '+', string: ""}, @@ -1821,27 +1821,27 @@ func TestRedisMessage(t *testing.T) { expected: `{"Value":[{"Value":[{"Value":0,"Type":"int64"},{"Value":0,"Type":"int64"},{"Value":[{"Value":"127.0.3.1","Type":"simple string"},{"Value":3,"Type":"int64"},{"Value":"","Type":"simple string"}],"Type":"array"}],"Type":"array"}],"Type":"array"}`, }, { - input: RedisMessage{typ: '+', string: "127.0.3.1", ttl: [7]byte{97, 77, 74, 61, 138, 1, 0}}, + input: ValkeyMessage{typ: '+', string: "127.0.3.1", ttl: [7]byte{97, 77, 74, 61, 138, 1, 0}}, expected: `{"Value":"127.0.3.1","Type":"simple string","TTL":"2023-08-28 17:56:34.273 +0000 UTC"}`, }, { - input: RedisMessage{typ: '0'}, + input: ValkeyMessage{typ: '0'}, expected: `{"Type":"unknown"}`, }, { - input: RedisMessage{typ: typeBool, integer: 1}, + input: ValkeyMessage{typ: typeBool, integer: 1}, expected: `{"Value":true,"Type":"boolean"}`, }, { - input: RedisMessage{typ: typeNull}, - expected: `{"Type":"null","Error":"redis nil message"}`, + input: ValkeyMessage{typ: typeNull}, + expected: `{"Type":"null","Error":"valkey nil message"}`, }, { - input: RedisMessage{typ: typeSimpleErr, string: "ERR foo"}, + input: ValkeyMessage{typ: typeSimpleErr, string: "ERR foo"}, expected: `{"Type":"simple error","Error":"foo"}`, }, { - input: RedisMessage{typ: typeBlobErr, string: "ERR foo"}, + input: ValkeyMessage{typ: typeBlobErr, string: "ERR foo"}, expected: `{"Type":"blob error","Error":"foo"}`, }, } diff --git a/mock/README.md b/mock/README.md index d84d937..c35b456 100644 --- a/mock/README.md +++ b/mock/README.md @@ -1,9 +1,9 @@ -# rueidis mock +# valkey mock -Due to the design of the command builder, it is impossible for users to mock `rueidis.Client` for testing. +Due to the design of the command builder, it is impossible for users to mock `valkey.Client` for testing. -Therefore, rueidis provides an implemented one, based on the `gomock`, with some helpers -to make user writing tests more easily, including command matcher `mock.Match`, `mock.MatchFn` and `mock.Result` for faking redis responses. +Therefore, valkey provides an implemented one, based on the `gomock`, with some helpers +to make user writing tests more easily, including command matcher `mock.Match`, `mock.MatchFn` and `mock.Result` for faking valkey responses. ## Examples @@ -17,26 +17,26 @@ import ( "testing" "go.uber.org/mock/gomock" - "github.com/redis/rueidis/mock" + "github.com/rueian/valkey-go/mock" ) -func TestWithRueidis(t *testing.T) { +func TestWithValkey(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() ctx := context.Background() client := mock.NewClient(ctrl) - client.EXPECT().Do(ctx, mock.Match("GET", "key")).Return(mock.Result(mock.RedisString("val"))) + client.EXPECT().Do(ctx, mock.Match("GET", "key")).Return(mock.Result(mock.ValkeyString("val"))) if v, _ := client.Do(ctx, client.B().Get().Key("key").Build()).ToString(); v != "val" { t.Fatalf("unexpected val %v", v) } - client.EXPECT().DoMulti(ctx, mock.Match("GET", "c"), mock.Match("GET", "d")).Return([]rueidis.RedisResult{ - mock.Result(mock.RedisNil()), - mock.Result(mock.RedisNil()), + client.EXPECT().DoMulti(ctx, mock.Match("GET", "c"), mock.Match("GET", "d")).Return([]valkey.ValkeyResult{ + mock.Result(mock.ValkeyNil()), + mock.Result(mock.ValkeyNil()), }) for _, resp := range client.DoMulti(ctx, client.B().Get().Key("c").Build(), client.B().Get().Key("d").Build()) { - if err := resp.Error(); !rueidis.IsRedisNil(err) { + if err := resp.Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } @@ -53,21 +53,21 @@ import ( "testing" "go.uber.org/mock/gomock" - "github.com/redis/rueidis/mock" + "github.com/rueian/valkey-go/mock" ) -func TestWithRueidisReceive(t *testing.T) { +func TestWithValkeyReceive(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() ctx := context.Background() client := mock.NewClient(ctrl) - client.EXPECT().Receive(ctx, mock.Match("SUBSCRIBE", "ch"), gomock.Any()).Do(func(_, _ any, fn func(message rueidis.PubSubMessage)) { - fn(rueidis.PubSubMessage{Message: "msg"}) + client.EXPECT().Receive(ctx, mock.Match("SUBSCRIBE", "ch"), gomock.Any()).Do(func(_, _ any, fn func(message valkey.PubSubMessage)) { + fn(valkey.PubSubMessage{Message: "msg"}) }) - client.Receive(ctx, client.B().Subscribe().Channel("ch").Build(), func(msg rueidis.PubSubMessage) { + client.Receive(ctx, client.B().Subscribe().Channel("ch").Build(), func(msg valkey.PubSubMessage) { if msg.Message != "msg" { t.Fatalf("unexpected val %v", msg.Message) } diff --git a/mock/client.go b/mock/client.go index 7da4f78..a27abd1 100644 --- a/mock/client.go +++ b/mock/client.go @@ -5,13 +5,13 @@ import ( "reflect" "time" - "github.com/redis/rueidis" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/internal/cmds" "go.uber.org/mock/gomock" ) -var _ rueidis.Client = (*Client)(nil) -var _ rueidis.DedicatedClient = (*DedicatedClient)(nil) +var _ valkey.Client = (*Client)(nil) +var _ valkey.DedicatedClient = (*DedicatedClient)(nil) // ClientOption is optional function parameter for NewClient type ClientOption func(c any) @@ -56,7 +56,7 @@ func (m *Client) EXPECT() *ClientMockRecorder { } // B mocks base method. -func (m *Client) B() rueidis.Builder { +func (m *Client) B() valkey.Builder { return cmds.NewBuilder(m.slot) } @@ -73,10 +73,10 @@ func (mr *ClientMockRecorder) Close() *gomock.Call { } // Dedicate mocks base method. -func (m *Client) Dedicate() (rueidis.DedicatedClient, func()) { +func (m *Client) Dedicate() (valkey.DedicatedClient, func()) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Dedicate") - ret0, _ := ret[0].(rueidis.DedicatedClient) + ret0, _ := ret[0].(valkey.DedicatedClient) ret1, _ := ret[1].(func()) return ret0, ret1 } @@ -88,7 +88,7 @@ func (mr *ClientMockRecorder) Dedicate() *gomock.Call { } // Dedicated mocks base method. -func (m *Client) Dedicated(arg0 func(rueidis.DedicatedClient) error) error { +func (m *Client) Dedicated(arg0 func(valkey.DedicatedClient) error) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Dedicated", arg0) ret0, _ := ret[0].(error) @@ -102,10 +102,10 @@ func (mr *ClientMockRecorder) Dedicated(arg0 any) *gomock.Call { } // Do mocks base method. -func (m *Client) Do(arg0 context.Context, arg1 rueidis.Completed) rueidis.RedisResult { +func (m *Client) Do(arg0 context.Context, arg1 valkey.Completed) valkey.ValkeyResult { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Do", arg0, arg1) - ret0, _ := ret[0].(rueidis.RedisResult) + ret0, _ := ret[0].(valkey.ValkeyResult) return ret0 } @@ -116,10 +116,10 @@ func (mr *ClientMockRecorder) Do(arg0, arg1 any) *gomock.Call { } // DoStream mocks base method. -func (m *Client) DoStream(arg0 context.Context, arg1 rueidis.Completed) rueidis.RedisResultStream { +func (m *Client) DoStream(arg0 context.Context, arg1 valkey.Completed) valkey.ValkeyResultStream { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DoStream", arg0, arg1) - ret0, _ := ret[0].(rueidis.RedisResultStream) + ret0, _ := ret[0].(valkey.ValkeyResultStream) return ret0 } @@ -130,10 +130,10 @@ func (mr *ClientMockRecorder) DoStream(arg0, arg1 any) *gomock.Call { } // DoCache mocks base method. -func (m *Client) DoCache(arg0 context.Context, arg1 rueidis.Cacheable, arg2 time.Duration) rueidis.RedisResult { +func (m *Client) DoCache(arg0 context.Context, arg1 valkey.Cacheable, arg2 time.Duration) valkey.ValkeyResult { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DoCache", arg0, arg1, arg2) - ret0, _ := ret[0].(rueidis.RedisResult) + ret0, _ := ret[0].(valkey.ValkeyResult) return ret0 } @@ -144,14 +144,14 @@ func (mr *ClientMockRecorder) DoCache(arg0, arg1, arg2 any) *gomock.Call { } // DoMulti mocks base method. -func (m *Client) DoMulti(arg0 context.Context, arg1 ...rueidis.Completed) []rueidis.RedisResult { +func (m *Client) DoMulti(arg0 context.Context, arg1 ...valkey.Completed) []valkey.ValkeyResult { m.ctrl.T.Helper() varargs := []any{arg0} for _, a := range arg1 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DoMulti", varargs...) - ret0, _ := ret[0].([]rueidis.RedisResult) + ret0, _ := ret[0].([]valkey.ValkeyResult) return ret0 } @@ -163,14 +163,14 @@ func (mr *ClientMockRecorder) DoMulti(arg0 any, arg1 ...any) *gomock.Call { } // DoMultiStream mocks base method. -func (m *Client) DoMultiStream(arg0 context.Context, arg1 ...rueidis.Completed) rueidis.MultiRedisResultStream { +func (m *Client) DoMultiStream(arg0 context.Context, arg1 ...valkey.Completed) valkey.MultiValkeyResultStream { m.ctrl.T.Helper() varargs := []any{arg0} for _, a := range arg1 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DoMultiStream", varargs...) - ret0, _ := ret[0].(rueidis.MultiRedisResultStream) + ret0, _ := ret[0].(valkey.MultiValkeyResultStream) return ret0 } @@ -182,14 +182,14 @@ func (mr *ClientMockRecorder) DoMultiStream(arg0 any, arg1 ...any) *gomock.Call } // DoMultiCache mocks base method. -func (m *Client) DoMultiCache(arg0 context.Context, arg1 ...rueidis.CacheableTTL) []rueidis.RedisResult { +func (m *Client) DoMultiCache(arg0 context.Context, arg1 ...valkey.CacheableTTL) []valkey.ValkeyResult { m.ctrl.T.Helper() varargs := []any{arg0} for _, a := range arg1 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DoMultiCache", varargs...) - ret0, _ := ret[0].([]rueidis.RedisResult) + ret0, _ := ret[0].([]valkey.ValkeyResult) return ret0 } @@ -201,10 +201,10 @@ func (mr *ClientMockRecorder) DoMultiCache(arg0 any, arg1 ...any) *gomock.Call { } // Nodes mocks base method. -func (m *Client) Nodes() map[string]rueidis.Client { +func (m *Client) Nodes() map[string]valkey.Client { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Nodes") - ret0, _ := ret[0].(map[string]rueidis.Client) + ret0, _ := ret[0].(map[string]valkey.Client) return ret0 } @@ -215,7 +215,7 @@ func (mr *ClientMockRecorder) Nodes() *gomock.Call { } // Receive mocks base method. -func (m *Client) Receive(arg0 context.Context, arg1 rueidis.Completed, arg2 func(rueidis.PubSubMessage)) error { +func (m *Client) Receive(arg0 context.Context, arg1 valkey.Completed, arg2 func(valkey.PubSubMessage)) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Receive", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -256,7 +256,7 @@ func (m *DedicatedClient) EXPECT() *DedicatedClientMockRecorder { } // B mocks base method. -func (m *DedicatedClient) B() rueidis.Builder { +func (m *DedicatedClient) B() valkey.Builder { return cmds.NewBuilder(m.slot) } @@ -273,10 +273,10 @@ func (mr *DedicatedClientMockRecorder) Close() *gomock.Call { } // Do mocks base method. -func (m *DedicatedClient) Do(arg0 context.Context, arg1 rueidis.Completed) rueidis.RedisResult { +func (m *DedicatedClient) Do(arg0 context.Context, arg1 valkey.Completed) valkey.ValkeyResult { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Do", arg0, arg1) - ret0, _ := ret[0].(rueidis.RedisResult) + ret0, _ := ret[0].(valkey.ValkeyResult) return ret0 } @@ -287,14 +287,14 @@ func (mr *DedicatedClientMockRecorder) Do(arg0, arg1 any) *gomock.Call { } // DoMulti mocks base method. -func (m *DedicatedClient) DoMulti(arg0 context.Context, arg1 ...rueidis.Completed) []rueidis.RedisResult { +func (m *DedicatedClient) DoMulti(arg0 context.Context, arg1 ...valkey.Completed) []valkey.ValkeyResult { m.ctrl.T.Helper() varargs := []any{arg0} for _, a := range arg1 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DoMulti", varargs...) - ret0, _ := ret[0].([]rueidis.RedisResult) + ret0, _ := ret[0].([]valkey.ValkeyResult) return ret0 } @@ -306,7 +306,7 @@ func (mr *DedicatedClientMockRecorder) DoMulti(arg0 any, arg1 ...any) *gomock.Ca } // Receive mocks base method. -func (m *DedicatedClient) Receive(arg0 context.Context, arg1 rueidis.Completed, arg2 func(rueidis.PubSubMessage)) error { +func (m *DedicatedClient) Receive(arg0 context.Context, arg1 valkey.Completed, arg2 func(valkey.PubSubMessage)) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Receive", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -320,7 +320,7 @@ func (mr *DedicatedClientMockRecorder) Receive(arg0, arg1, arg2 any) *gomock.Cal } // SetPubSubHooks mocks base method. -func (m *DedicatedClient) SetPubSubHooks(arg0 rueidis.PubSubHooks) <-chan error { +func (m *DedicatedClient) SetPubSubHooks(arg0 valkey.PubSubHooks) <-chan error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetPubSubHooks", arg0) ret0, _ := ret[0].(<-chan error) diff --git a/mock/client_test.go b/mock/client_test.go index a916609..fd96a32 100644 --- a/mock/client_test.go +++ b/mock/client_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" "go.uber.org/mock/gomock" ) @@ -18,27 +18,27 @@ func TestNewClient(t *testing.T) { ctx := context.Background() client := NewClient(ctrl) { - client.EXPECT().Do(ctx, Match("GET", "a")).Return(Result(RedisNil())) - if err := client.Do(ctx, client.B().Get().Key("a").Build()).Error(); !rueidis.IsRedisNil(err) { + client.EXPECT().Do(ctx, Match("GET", "a")).Return(Result(ValkeyNil())) + if err := client.Do(ctx, client.B().Get().Key("a").Build()).Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { - client.EXPECT().DoCache(ctx, Match("GET", "b"), time.Second).Return(Result(RedisNil())) - if err := client.DoCache(ctx, client.B().Get().Key("b").Cache(), time.Second).Error(); !rueidis.IsRedisNil(err) { + client.EXPECT().DoCache(ctx, Match("GET", "b"), time.Second).Return(Result(ValkeyNil())) + if err := client.DoCache(ctx, client.B().Get().Key("b").Cache(), time.Second).Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { client.EXPECT().DoMulti(ctx, Match("GET", "c"), - Match("GET", "d")).Return([]rueidis.RedisResult{ - Result(RedisNil()), - Result(RedisNil())}) + Match("GET", "d")).Return([]valkey.ValkeyResult{ + Result(ValkeyNil()), + Result(ValkeyNil())}) for _, resp := range client.DoMulti(ctx, client.B().Get().Key("c").Build(), client.B().Get().Key("d").Build()) { - if err := resp.Error(); !rueidis.IsRedisNil(err) { + if err := resp.Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } @@ -46,33 +46,33 @@ func TestNewClient(t *testing.T) { { client.EXPECT().DoMultiCache(ctx, Match("GET", "e"), - Match("GET", "f")).Return([]rueidis.RedisResult{ - Result(RedisNil()), - Result(RedisNil())}) + Match("GET", "f")).Return([]valkey.ValkeyResult{ + Result(ValkeyNil()), + Result(ValkeyNil())}) for _, resp := range client.DoMultiCache(ctx, - rueidis.CT(client.B().Get().Key("e").Cache(), time.Second), - rueidis.CT(client.B().Get().Key("f").Cache(), time.Second)) { - if err := resp.Error(); !rueidis.IsRedisNil(err) { + valkey.CT(client.B().Get().Key("e").Cache(), time.Second), + valkey.CT(client.B().Get().Key("f").Cache(), time.Second)) { + if err := resp.Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } } { - client.EXPECT().DoStream(ctx, Match("GET", "e")).Return(RedisResultStream(RedisNil())) + client.EXPECT().DoStream(ctx, Match("GET", "e")).Return(ValkeyResultStream(ValkeyNil())) s := client.DoStream(ctx, client.B().Get().Key("e").Build()) - if _, err := s.WriteTo(io.Discard); !rueidis.IsRedisNil(err) { + if _, err := s.WriteTo(io.Discard); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { - client.EXPECT().DoMultiStream(ctx, Match("GET", "e"), Match("GET", "f")).Return(MultiRedisResultStream(RedisNil())) + client.EXPECT().DoMultiStream(ctx, Match("GET", "e"), Match("GET", "f")).Return(MultiValkeyResultStream(ValkeyNil())) s := client.DoMultiStream(ctx, client.B().Get().Key("e").Build(), client.B().Get().Key("f").Build()) - if _, err := s.WriteTo(io.Discard); !rueidis.IsRedisNil(err) { + if _, err := s.WriteTo(io.Discard); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { - client.EXPECT().Nodes().Return(map[string]rueidis.Client{"addr": client}) + client.EXPECT().Nodes().Return(map[string]valkey.Client{"addr": client}) if nodes := client.Nodes(); nodes["addr"] != client { t.Fatalf("unexpected val %v", nodes) } @@ -84,14 +84,14 @@ func TestNewClient(t *testing.T) { <-ch } { - client.EXPECT().Receive(ctx, Match("SUBSCRIBE", "a"), gomock.Any()).DoAndReturn(func(ctx context.Context, cmd any, fn func(msg rueidis.PubSubMessage)) error { - fn(rueidis.PubSubMessage{ + client.EXPECT().Receive(ctx, Match("SUBSCRIBE", "a"), gomock.Any()).DoAndReturn(func(ctx context.Context, cmd any, fn func(msg valkey.PubSubMessage)) error { + fn(valkey.PubSubMessage{ Channel: "s", Message: "s", }) return errors.New("any") }) - if err := client.Receive(ctx, client.B().Subscribe().Channel("a").Build(), func(msg rueidis.PubSubMessage) { + if err := client.Receive(ctx, client.B().Subscribe().Channel("a").Build(), func(msg valkey.PubSubMessage) { if msg.Message != "s" && msg.Channel != "s" { t.Fatalf("unexpected val %v", msg) } @@ -108,13 +108,13 @@ func TestNewClient(t *testing.T) { } { dc := NewDedicatedClient(ctrl) - cb := func(c rueidis.DedicatedClient) error { + cb := func(c valkey.DedicatedClient) error { if c != dc { t.Fatalf("unexpected val %v", c) } return errors.New("any") } - client.EXPECT().Dedicated(gomock.Any()).DoAndReturn(func(fn func(c rueidis.DedicatedClient) error) error { + client.EXPECT().Dedicated(gomock.Any()).DoAndReturn(func(fn func(c valkey.DedicatedClient) error) error { return fn(dc) }) if err := client.Dedicated(cb); err.Error() != "any" { @@ -130,21 +130,21 @@ func TestNewDedicatedClient(t *testing.T) { ctx := context.Background() client := NewDedicatedClient(ctrl) { - client.EXPECT().Do(ctx, Match("GET", "a")).Return(Result(RedisNil())) - if err := client.Do(ctx, client.B().Get().Key("a").Build()).Error(); !rueidis.IsRedisNil(err) { + client.EXPECT().Do(ctx, Match("GET", "a")).Return(Result(ValkeyNil())) + if err := client.Do(ctx, client.B().Get().Key("a").Build()).Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { client.EXPECT().DoMulti(ctx, Match("GET", "c"), - Match("GET", "d")).Return([]rueidis.RedisResult{ - Result(RedisNil()), - Result(RedisNil())}) + Match("GET", "d")).Return([]valkey.ValkeyResult{ + Result(ValkeyNil()), + Result(ValkeyNil())}) for _, resp := range client.DoMulti(ctx, client.B().Get().Key("c").Build(), client.B().Get().Key("d").Build()) { - if err := resp.Error(); !rueidis.IsRedisNil(err) { + if err := resp.Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } @@ -156,14 +156,14 @@ func TestNewDedicatedClient(t *testing.T) { <-ch } { - client.EXPECT().Receive(ctx, Match("SUBSCRIBE", "a"), gomock.Any()).DoAndReturn(func(ctx context.Context, cmd any, fn func(msg rueidis.PubSubMessage)) error { - fn(rueidis.PubSubMessage{ + client.EXPECT().Receive(ctx, Match("SUBSCRIBE", "a"), gomock.Any()).DoAndReturn(func(ctx context.Context, cmd any, fn func(msg valkey.PubSubMessage)) error { + fn(valkey.PubSubMessage{ Channel: "s", Message: "s", }) return errors.New("any") }) - if err := client.Receive(ctx, client.B().Subscribe().Channel("a").Build(), func(msg rueidis.PubSubMessage) { + if err := client.Receive(ctx, client.B().Subscribe().Channel("a").Build(), func(msg valkey.PubSubMessage) { if msg.Message != "s" && msg.Channel != "s" { t.Fatalf("unexpected val %v", msg) } @@ -172,14 +172,14 @@ func TestNewDedicatedClient(t *testing.T) { } } { - client.EXPECT().SetPubSubHooks(gomock.Any()).Do(func(hooks rueidis.PubSubHooks) { + client.EXPECT().SetPubSubHooks(gomock.Any()).Do(func(hooks valkey.PubSubHooks) { if hooks.OnMessage == nil || hooks.OnSubscription == nil { t.Fatalf("unexpected val %v", hooks) } }) - client.SetPubSubHooks(rueidis.PubSubHooks{ - OnMessage: func(m rueidis.PubSubMessage) {}, - OnSubscription: func(s rueidis.PubSubSubscription) {}, + client.SetPubSubHooks(valkey.PubSubHooks{ + OnMessage: func(m valkey.PubSubMessage) {}, + OnSubscription: func(s valkey.PubSubSubscription) {}, }) } } diff --git a/mock/go.mod b/mock/go.mod index e3df94e..f026069 100644 --- a/mock/go.mod +++ b/mock/go.mod @@ -1,11 +1,11 @@ -module github.com/redis/rueidis/mock +module github.com/rueian/valkey-go/mock go 1.20 -replace github.com/redis/rueidis => ../ +replace github.com/rueian/valkey-go => ../ require ( - github.com/redis/rueidis v1.0.34 + github.com/rueian/valkey-go v1.0.34 go.uber.org/mock v0.3.0 ) diff --git a/mock/match.go b/mock/match.go index dee9721..c58b5f7 100644 --- a/mock/match.go +++ b/mock/match.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" "go.uber.org/mock/gomock" ) @@ -26,7 +26,7 @@ func (c *cmdMatcher) Matches(x any) bool { } func (c *cmdMatcher) String() string { - return fmt.Sprintf("redis command %v", c.expect) + return fmt.Sprintf("valkey command %v", c.expect) } func MatchFn(fn func(cmd []string) bool, description ...string) gomock.Matcher { @@ -61,19 +61,19 @@ func format(v any) string { sb := &strings.Builder{} sb.WriteString("\n") for i, c := range v.([]any) { - fmt.Fprintf(sb, "index %d redis command %v\n", i+1, commands(c)) + fmt.Fprintf(sb, "index %d valkey command %v\n", i+1, commands(c)) } return sb.String() } func commands(x any) any { - if cmd, ok := x.(rueidis.Completed); ok { + if cmd, ok := x.(valkey.Completed); ok { return cmd.Commands() } - if cmd, ok := x.(rueidis.Cacheable); ok { + if cmd, ok := x.(valkey.Cacheable); ok { return cmd.Commands() } - if cmd, ok := x.(rueidis.CacheableTTL); ok { + if cmd, ok := x.(valkey.CacheableTTL); ok { return cmd.Cmd.Commands() } return x diff --git a/mock/match_test.go b/mock/match_test.go index b56cfc7..eb8b4fb 100644 --- a/mock/match_test.go +++ b/mock/match_test.go @@ -5,8 +5,8 @@ import ( "strings" "testing" - "github.com/redis/rueidis" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/internal/cmds" "go.uber.org/mock/gomock" ) @@ -44,7 +44,7 @@ func TestMatchFn_Cacheable(t *testing.T) { func TestMatch_CacheableTTL(t *testing.T) { cmd := cmds.NewBuilder(cmds.NoSlot).Get().Key("k").Cache() - if m := Match("GET", "k"); !m.Matches(rueidis.CacheableTTL{Cmd: cmd}) { + if m := Match("GET", "k"); !m.Matches(valkey.CacheableTTL{Cmd: cmd}) { t.Fatalf("not matched %s", m.String()) } } @@ -62,7 +62,7 @@ func TestMatch_Other(t *testing.T) { if m := Match("GET", "k"); m.Matches(1) { t.Fatalf("unexpected matched %s", m.String()) } - if m := Match("GET", "k"); m.Matches([]rueidis.Completed{ + if m := Match("GET", "k"); m.Matches([]valkey.Completed{ cmds.NewBuilder(cmds.NoSlot).Get().Key("k").Build(), // https://github.com/redis/rueidis/issues/120 }) { t.Fatalf("unexpected matched %s", m.String()) @@ -77,7 +77,7 @@ func TestMatchFn_Other(t *testing.T) { } if m := MatchFn(func(cmd []string) bool { return reflect.DeepEqual(cmd, []string{"GET", "k"}) - }, "GET k"); m.Matches([]rueidis.Completed{ + }, "GET k"); m.Matches([]valkey.Completed{ cmds.NewBuilder(cmds.NoSlot).Get().Key("k").Build(), // https://github.com/redis/rueidis/issues/120 }) { t.Fatalf("unexpected matched %s", m.String()) diff --git a/mock/result.go b/mock/result.go index 687cad1..ae08be2 100644 --- a/mock/result.go +++ b/mock/result.go @@ -11,70 +11,70 @@ import ( "time" "unsafe" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) -func Result(val rueidis.RedisMessage) rueidis.RedisResult { +func Result(val valkey.ValkeyMessage) valkey.ValkeyResult { r := result{val: val} - return *(*rueidis.RedisResult)(unsafe.Pointer(&r)) + return *(*valkey.ValkeyResult)(unsafe.Pointer(&r)) } -func ErrorResult(err error) rueidis.RedisResult { +func ErrorResult(err error) valkey.ValkeyResult { r := result{err: err} - return *(*rueidis.RedisResult)(unsafe.Pointer(&r)) + return *(*valkey.ValkeyResult)(unsafe.Pointer(&r)) } -func RedisString(v string) rueidis.RedisMessage { +func ValkeyString(v string) valkey.ValkeyMessage { m := message{typ: '+', string: v} - return *(*rueidis.RedisMessage)(unsafe.Pointer(&m)) + return *(*valkey.ValkeyMessage)(unsafe.Pointer(&m)) } -func RedisBlobString(v string) rueidis.RedisMessage { +func ValkeyBlobString(v string) valkey.ValkeyMessage { m := message{typ: '$', string: v} - return *(*rueidis.RedisMessage)(unsafe.Pointer(&m)) + return *(*valkey.ValkeyMessage)(unsafe.Pointer(&m)) } -func RedisError(v string) rueidis.RedisMessage { +func ValkeyError(v string) valkey.ValkeyMessage { m := message{typ: '-', string: v} - return *(*rueidis.RedisMessage)(unsafe.Pointer(&m)) + return *(*valkey.ValkeyMessage)(unsafe.Pointer(&m)) } -func RedisInt64(v int64) rueidis.RedisMessage { +func ValkeyInt64(v int64) valkey.ValkeyMessage { m := message{typ: ':', integer: v} - return *(*rueidis.RedisMessage)(unsafe.Pointer(&m)) + return *(*valkey.ValkeyMessage)(unsafe.Pointer(&m)) } -func RedisFloat64(v float64) rueidis.RedisMessage { +func ValkeyFloat64(v float64) valkey.ValkeyMessage { m := message{typ: ',', string: strconv.FormatFloat(v, 'f', -1, 64)} - return *(*rueidis.RedisMessage)(unsafe.Pointer(&m)) + return *(*valkey.ValkeyMessage)(unsafe.Pointer(&m)) } -func RedisBool(v bool) rueidis.RedisMessage { +func ValkeyBool(v bool) valkey.ValkeyMessage { m := message{typ: '#'} if v { m.integer = 1 } - return *(*rueidis.RedisMessage)(unsafe.Pointer(&m)) + return *(*valkey.ValkeyMessage)(unsafe.Pointer(&m)) } -func RedisNil() rueidis.RedisMessage { +func ValkeyNil() valkey.ValkeyMessage { m := message{typ: '_'} - return *(*rueidis.RedisMessage)(unsafe.Pointer(&m)) + return *(*valkey.ValkeyMessage)(unsafe.Pointer(&m)) } -func RedisArray(values ...rueidis.RedisMessage) rueidis.RedisMessage { +func ValkeyArray(values ...valkey.ValkeyMessage) valkey.ValkeyMessage { m := message{typ: '*', values: values} - return *(*rueidis.RedisMessage)(unsafe.Pointer(&m)) + return *(*valkey.ValkeyMessage)(unsafe.Pointer(&m)) } -func RedisMap(kv map[string]rueidis.RedisMessage) rueidis.RedisMessage { - values := make([]rueidis.RedisMessage, 0, 2*len(kv)) +func ValkeyMap(kv map[string]valkey.ValkeyMessage) valkey.ValkeyMessage { + values := make([]valkey.ValkeyMessage, 0, 2*len(kv)) for k, v := range kv { - values = append(values, RedisString(k)) + values = append(values, ValkeyString(k)) values = append(values, v) } m := message{typ: '%', values: values} - return *(*rueidis.RedisMessage)(unsafe.Pointer(&m)) + return *(*valkey.ValkeyMessage)(unsafe.Pointer(&m)) } func serialize(m message, buf *bytes.Buffer) { @@ -102,33 +102,33 @@ func serialize(m message, buf *bytes.Buffer) { } } -func RedisResultStreamError(err error) rueidis.RedisResultStream { +func ValkeyResultStreamError(err error) valkey.ValkeyResultStream { s := stream{e: err} - return *(*rueidis.RedisResultStream)(unsafe.Pointer(&s)) + return *(*valkey.ValkeyResultStream)(unsafe.Pointer(&s)) } -func RedisResultStream(ms ...rueidis.RedisMessage) rueidis.RedisResultStream { +func ValkeyResultStream(ms ...valkey.ValkeyMessage) valkey.ValkeyResultStream { buf := bytes.NewBuffer(nil) for _, m := range ms { pm := *(*message)(unsafe.Pointer(&m)) serialize(pm, buf) } s := stream{n: len(ms), p: &pool{size: 1, cond: sync.NewCond(&sync.Mutex{})}, w: &pipe{r: bufio.NewReader(buf)}} - return *(*rueidis.RedisResultStream)(unsafe.Pointer(&s)) + return *(*valkey.ValkeyResultStream)(unsafe.Pointer(&s)) } -func MultiRedisResultStream(ms ...rueidis.RedisMessage) rueidis.MultiRedisResultStream { - return RedisResultStream(ms...) +func MultiValkeyResultStream(ms ...valkey.ValkeyMessage) valkey.MultiValkeyResultStream { + return ValkeyResultStream(ms...) } -func MultiRedisResultStreamError(err error) rueidis.RedisResultStream { - return RedisResultStreamError(err) +func MultiValkeyResultStreamError(err error) valkey.ValkeyResultStream { + return ValkeyResultStreamError(err) } type message struct { - attrs *rueidis.RedisMessage + attrs *valkey.ValkeyMessage string string - values []rueidis.RedisMessage + values []valkey.ValkeyMessage integer int64 typ byte ttl [7]byte @@ -136,7 +136,7 @@ type message struct { type result struct { err error - val rueidis.RedisMessage + val valkey.ValkeyMessage } type pool struct { @@ -154,17 +154,17 @@ type pipe struct { clhks atomic.Value // closed hook, invoked after the conn is closed pshks atomic.Value // pubsub hook, registered by the SetPubSubHooks queue any - cache rueidis.CacheStore + cache valkey.CacheStore r *bufio.Reader w *bufio.Writer close chan struct{} - onInvalidations func([]rueidis.RedisMessage) + onInvalidations func([]valkey.ValkeyMessage) r2psFn func() (p *pipe, err error) // func to build pipe for resp2 pubsub r2pipe *pipe // internal pipe for resp2 pubsub only ssubs *any // pubsub smessage subscriptions nsubs *any // pubsub message subscriptions psubs *any // pubsub pmessage subscriptions - info map[string]rueidis.RedisMessage + info map[string]valkey.ValkeyMessage timeout time.Duration pinggap time.Duration maxFlushDelay time.Duration diff --git a/mock/result_test.go b/mock/result_test.go index 6e447fc..a79bf79 100644 --- a/mock/result_test.go +++ b/mock/result_test.go @@ -8,25 +8,25 @@ import ( "strings" "testing" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) -func TestRedisString(t *testing.T) { - m := RedisString("s") +func TestValkeyString(t *testing.T) { + m := ValkeyString("s") if v, err := m.ToString(); err != nil || v != "s" { t.Fatalf("unexpected value %v", v) } } -func TestRedisError(t *testing.T) { - m := RedisError("s") +func TestValkeyError(t *testing.T) { + m := ValkeyError("s") if err := m.Error(); err == nil || err.Error() != "s" { t.Fatalf("unexpected value %v", err) } } -func TestRedisInt64(t *testing.T) { - m := RedisInt64(1) +func TestValkeyInt64(t *testing.T) { + m := ValkeyInt64(1) if v, err := m.ToInt64(); err != nil || v != int64(1) { t.Fatalf("unexpected value %v", v) } @@ -35,8 +35,8 @@ func TestRedisInt64(t *testing.T) { } } -func TestRedisFloat64(t *testing.T) { - m := RedisFloat64(1) +func TestValkeyFloat64(t *testing.T) { + m := ValkeyFloat64(1) if v, err := m.ToFloat64(); err != nil || v != float64(1) { t.Fatalf("unexpected value %v", v) } @@ -45,8 +45,8 @@ func TestRedisFloat64(t *testing.T) { } } -func TestRedisBool(t *testing.T) { - m := RedisBool(true) +func TestValkeyBool(t *testing.T) { + m := ValkeyBool(true) if v, err := m.ToBool(); err != nil || v != true { t.Fatalf("unexpected value %v", v) } @@ -55,8 +55,8 @@ func TestRedisBool(t *testing.T) { } } -func TestRedisNil(t *testing.T) { - m := RedisNil() +func TestValkeyNil(t *testing.T) { + m := ValkeyNil() if err := m.Error(); err == nil { t.Fatalf("unexpected value %v", err) } @@ -65,17 +65,17 @@ func TestRedisNil(t *testing.T) { } } -func TestRedisArray(t *testing.T) { - m := RedisArray(RedisString("0"), RedisString("1"), RedisString("2")) +func TestValkeyArray(t *testing.T) { + m := ValkeyArray(ValkeyString("0"), ValkeyString("1"), ValkeyString("2")) if arr, err := m.AsStrSlice(); err != nil || !reflect.DeepEqual(arr, []string{"0", "1", "2"}) { t.Fatalf("unexpected value %v", err) } } -func TestRedisMap(t *testing.T) { - m := RedisMap(map[string]rueidis.RedisMessage{ - "a": RedisString("0"), - "b": RedisString("1"), +func TestValkeyMap(t *testing.T) { + m := ValkeyMap(map[string]valkey.ValkeyMessage{ + "a": ValkeyString("0"), + "b": ValkeyString("1"), }) if arr, err := m.AsStrMap(); err != nil || !reflect.DeepEqual(arr, map[string]string{ "a": "0", @@ -83,17 +83,17 @@ func TestRedisMap(t *testing.T) { }) { t.Fatalf("unexpected value %v", err) } - if arr, err := m.ToMap(); err != nil || !reflect.DeepEqual(arr, map[string]rueidis.RedisMessage{ - "a": RedisString("0"), - "b": RedisString("1"), + if arr, err := m.ToMap(); err != nil || !reflect.DeepEqual(arr, map[string]valkey.ValkeyMessage{ + "a": ValkeyString("0"), + "b": ValkeyString("1"), }) { t.Fatalf("unexpected value %v", err) } } -func TestRedisResult(t *testing.T) { - r := Result(RedisNil()) - if err := r.Error(); !rueidis.IsRedisNil(err) { +func TestValkeyResult(t *testing.T) { + r := Result(ValkeyNil()) + if err := r.Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected value %v", err) } } @@ -106,14 +106,14 @@ func TestErrorResult(t *testing.T) { } func TestErrorResultStream(t *testing.T) { - s := RedisResultStreamError(errors.New("any")) + s := ValkeyResultStreamError(errors.New("any")) if err := s.Error(); err.Error() != "any" { t.Fatalf("unexpected value %v", err) } } func TestErrorMultiResultStream(t *testing.T) { - s := MultiRedisResultStreamError(errors.New("any")) + s := MultiValkeyResultStreamError(errors.New("any")) if err := s.Error(); err.Error() != "any" { t.Fatalf("unexpected value %v", err) } @@ -121,19 +121,19 @@ func TestErrorMultiResultStream(t *testing.T) { func TestResultStream(t *testing.T) { type test struct { - msg []rueidis.RedisMessage + msg []valkey.ValkeyMessage out []string err []string } tests := []test{ - {msg: []rueidis.RedisMessage{RedisString("")}, out: []string{""}, err: []string{""}}, - {msg: []rueidis.RedisMessage{RedisString("0"), RedisBlobString("12345")}, out: []string{"0", "12345"}, err: []string{"", ""}}, - {msg: []rueidis.RedisMessage{RedisInt64(123), RedisInt64(-456)}, out: []string{"123", "-456"}, err: []string{"", ""}}, - {msg: []rueidis.RedisMessage{RedisString(""), RedisNil()}, out: []string{"", ""}, err: []string{"", "nil"}}, - {msg: []rueidis.RedisMessage{RedisArray(RedisString("n")), RedisString("ok"), RedisNil(), RedisMap(map[string]rueidis.RedisMessage{"b": RedisBlobString("b")})}, out: []string{"", "ok", "", ""}, err: []string{"unsupported", "", "nil", "unsupported"}}, + {msg: []valkey.ValkeyMessage{ValkeyString("")}, out: []string{""}, err: []string{""}}, + {msg: []valkey.ValkeyMessage{ValkeyString("0"), ValkeyBlobString("12345")}, out: []string{"0", "12345"}, err: []string{"", ""}}, + {msg: []valkey.ValkeyMessage{ValkeyInt64(123), ValkeyInt64(-456)}, out: []string{"123", "-456"}, err: []string{"", ""}}, + {msg: []valkey.ValkeyMessage{ValkeyString(""), ValkeyNil()}, out: []string{"", ""}, err: []string{"", "nil"}}, + {msg: []valkey.ValkeyMessage{ValkeyArray(ValkeyString("n")), ValkeyString("ok"), ValkeyNil(), ValkeyMap(map[string]valkey.ValkeyMessage{"b": ValkeyBlobString("b")})}, out: []string{"", "ok", "", ""}, err: []string{"unsupported", "", "nil", "unsupported"}}, } for _, tc := range tests { - s := RedisResultStream(tc.msg...) + s := ValkeyResultStream(tc.msg...) if err := s.Error(); err != nil { t.Fatalf("unexpected value %v", err) } @@ -170,19 +170,19 @@ func TestResultStream(t *testing.T) { func TestMultiResultStream(t *testing.T) { type test struct { - msg []rueidis.RedisMessage + msg []valkey.ValkeyMessage out []string err []string } tests := []test{ - {msg: []rueidis.RedisMessage{RedisString("")}, out: []string{""}, err: []string{""}}, - {msg: []rueidis.RedisMessage{RedisString("0"), RedisBlobString("12345")}, out: []string{"0", "12345"}, err: []string{"", ""}}, - {msg: []rueidis.RedisMessage{RedisInt64(123), RedisInt64(-456)}, out: []string{"123", "-456"}, err: []string{"", ""}}, - {msg: []rueidis.RedisMessage{RedisString(""), RedisNil()}, out: []string{"", ""}, err: []string{"", "nil"}}, - {msg: []rueidis.RedisMessage{RedisArray(RedisString("n")), RedisString("ok"), RedisNil(), RedisMap(map[string]rueidis.RedisMessage{"b": RedisBlobString("b")})}, out: []string{"", "ok", "", ""}, err: []string{"unsupported", "", "nil", "unsupported"}}, + {msg: []valkey.ValkeyMessage{ValkeyString("")}, out: []string{""}, err: []string{""}}, + {msg: []valkey.ValkeyMessage{ValkeyString("0"), ValkeyBlobString("12345")}, out: []string{"0", "12345"}, err: []string{"", ""}}, + {msg: []valkey.ValkeyMessage{ValkeyInt64(123), ValkeyInt64(-456)}, out: []string{"123", "-456"}, err: []string{"", ""}}, + {msg: []valkey.ValkeyMessage{ValkeyString(""), ValkeyNil()}, out: []string{"", ""}, err: []string{"", "nil"}}, + {msg: []valkey.ValkeyMessage{ValkeyArray(ValkeyString("n")), ValkeyString("ok"), ValkeyNil(), ValkeyMap(map[string]valkey.ValkeyMessage{"b": ValkeyBlobString("b")})}, out: []string{"", "ok", "", ""}, err: []string{"unsupported", "", "nil", "unsupported"}}, } for _, tc := range tests { - s := MultiRedisResultStream(tc.msg...) + s := MultiValkeyResultStream(tc.msg...) if err := s.Error(); err != nil { t.Fatalf("unexpected value %v", err) } diff --git a/mux.go b/mux.go index 33fe8c6..dc4c735 100644 --- a/mux.go +++ b/mux.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -9,8 +9,8 @@ import ( "sync/atomic" "time" - "github.com/redis/rueidis/internal/cmds" - "github.com/redis/rueidis/internal/util" + "github.com/rueian/valkey-go/internal/cmds" + "github.com/rueian/valkey-go/internal/util" ) type connFn func(dst string, opt *ClientOption) conn @@ -45,14 +45,14 @@ var batchcachep = util.NewPool(func(capacity int) *batchcache { }) type conn interface { - Do(ctx context.Context, cmd Completed) RedisResult - DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) RedisResult - DoMulti(ctx context.Context, multi ...Completed) *redisresults - DoMultiCache(ctx context.Context, multi ...CacheableTTL) *redisresults + Do(ctx context.Context, cmd Completed) ValkeyResult + DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) ValkeyResult + DoMulti(ctx context.Context, multi ...Completed) *valkeyresults + DoMultiCache(ctx context.Context, multi ...CacheableTTL) *valkeyresults Receive(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error - DoStream(ctx context.Context, cmd Completed) RedisResultStream - DoMultiStream(ctx context.Context, multi ...Completed) MultiRedisResultStream - Info() map[string]RedisMessage + DoStream(ctx context.Context, cmd Completed) ValkeyResultStream + DoMultiStream(ctx context.Context, multi ...Completed) MultiValkeyResultStream + Info() map[string]ValkeyMessage Version() int Error() error Close() @@ -197,7 +197,7 @@ func (m *mux) Dial() error { return err } -func (m *mux) Info() map[string]RedisMessage { +func (m *mux) Info() map[string]ValkeyMessage { return m.pipe(0).Info() } @@ -209,17 +209,17 @@ func (m *mux) Error() error { return m.pipe(0).Error() } -func (m *mux) DoStream(ctx context.Context, cmd Completed) RedisResultStream { +func (m *mux) DoStream(ctx context.Context, cmd Completed) ValkeyResultStream { wire := m.spool.Acquire() return wire.DoStream(ctx, m.spool, cmd) } -func (m *mux) DoMultiStream(ctx context.Context, multi ...Completed) MultiRedisResultStream { +func (m *mux) DoMultiStream(ctx context.Context, multi ...Completed) MultiValkeyResultStream { wire := m.spool.Acquire() return wire.DoMultiStream(ctx, m.spool, multi...) } -func (m *mux) Do(ctx context.Context, cmd Completed) (resp RedisResult) { +func (m *mux) Do(ctx context.Context, cmd Completed) (resp ValkeyResult) { if cmd.IsBlock() { resp = m.blocking(ctx, cmd) } else { @@ -228,7 +228,7 @@ func (m *mux) Do(ctx context.Context, cmd Completed) (resp RedisResult) { return resp } -func (m *mux) DoMulti(ctx context.Context, multi ...Completed) (resp *redisresults) { +func (m *mux) DoMulti(ctx context.Context, multi ...Completed) (resp *valkeyresults) { for _, cmd := range multi { if cmd.IsBlock() { goto block @@ -240,21 +240,21 @@ block: return m.blockingMulti(ctx, multi) } -func (m *mux) blocking(ctx context.Context, cmd Completed) (resp RedisResult) { +func (m *mux) blocking(ctx context.Context, cmd Completed) (resp ValkeyResult) { wire := m.dpool.Acquire() resp = wire.Do(ctx, cmd) - if resp.NonRedisError() != nil { // abort the wire if blocking command return early (ex. context.DeadlineExceeded) + if resp.NonValkeyError() != nil { // abort the wire if blocking command return early (ex. context.DeadlineExceeded) wire.Close() } m.dpool.Store(wire) return resp } -func (m *mux) blockingMulti(ctx context.Context, cmd []Completed) (resp *redisresults) { +func (m *mux) blockingMulti(ctx context.Context, cmd []Completed) (resp *valkeyresults) { wire := m.dpool.Acquire() resp = wire.DoMulti(ctx, cmd...) for _, res := range resp.s { - if res.NonRedisError() != nil { // abort the wire if blocking command return early (ex. context.DeadlineExceeded) + if res.NonValkeyError() != nil { // abort the wire if blocking command return early (ex. context.DeadlineExceeded) wire.Close() break } @@ -263,21 +263,21 @@ func (m *mux) blockingMulti(ctx context.Context, cmd []Completed) (resp *redisre return resp } -func (m *mux) pipeline(ctx context.Context, cmd Completed) (resp RedisResult) { +func (m *mux) pipeline(ctx context.Context, cmd Completed) (resp ValkeyResult) { slot := slotfn(len(m.wire), cmd.Slot(), cmd.NoReply()) wire := m.pipe(slot) - if resp = wire.Do(ctx, cmd); isBroken(resp.NonRedisError(), wire) { + if resp = wire.Do(ctx, cmd); isBroken(resp.NonValkeyError(), wire) { m.wire[slot].CompareAndSwap(wire, m.init) } return resp } -func (m *mux) pipelineMulti(ctx context.Context, cmd []Completed) (resp *redisresults) { +func (m *mux) pipelineMulti(ctx context.Context, cmd []Completed) (resp *valkeyresults) { slot := slotfn(len(m.wire), cmd[0].Slot(), cmd[0].NoReply()) wire := m.pipe(slot) resp = wire.DoMulti(ctx, cmd...) for _, r := range resp.s { - if isBroken(r.NonRedisError(), wire) { + if isBroken(r.NonValkeyError(), wire) { m.wire[slot].CompareAndSwap(wire, m.init) return resp } @@ -285,17 +285,17 @@ func (m *mux) pipelineMulti(ctx context.Context, cmd []Completed) (resp *redisre return resp } -func (m *mux) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) RedisResult { +func (m *mux) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) ValkeyResult { slot := cmd.Slot() & uint16(len(m.wire)-1) wire := m.pipe(slot) resp := wire.DoCache(ctx, cmd, ttl) - if isBroken(resp.NonRedisError(), wire) { + if isBroken(resp.NonValkeyError(), wire) { m.wire[slot].CompareAndSwap(wire, m.init) } return resp } -func (m *mux) DoMultiCache(ctx context.Context, multi ...CacheableTTL) (results *redisresults) { +func (m *mux) DoMultiCache(ctx context.Context, multi ...CacheableTTL) (results *valkeyresults) { var slots *muxslots var mask = uint16(len(m.wire) - 1) @@ -344,11 +344,11 @@ func (m *mux) DoMultiCache(ctx context.Context, multi ...CacheableTTL) (results return results } -func (m *mux) doMultiCache(ctx context.Context, slot uint16, multi []CacheableTTL) (resps *redisresults) { +func (m *mux) doMultiCache(ctx context.Context, slot uint16, multi []CacheableTTL) (resps *valkeyresults) { wire := m.pipe(slot) resps = wire.DoMultiCache(ctx, multi...) for _, r := range resps.s { - if isBroken(r.NonRedisError(), wire) { + if isBroken(r.NonValkeyError(), wire) { m.wire[slot].CompareAndSwap(wire, m.init) return resps } diff --git a/mux_test.go b/mux_test.go index 0f53d12..2378fa7 100644 --- a/mux_test.go +++ b/mux_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "bufio" @@ -13,7 +13,7 @@ import ( "testing" "time" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go/internal/cmds" ) func setupMux(wires []*mockWire) (conn *mux, checkClean func(t *testing.T)) { @@ -67,12 +67,12 @@ func TestNewMuxDailErr(t *testing.T) { func TestNewMux(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) n1, n2 := net.Pipe() - mock := &redisMock{t: t, buf: bufio.NewReader(n2), conn: n2} + mock := &valkeyMock{t: t, buf: bufio.NewReader(n2), conn: n2} go func() { mock.Expect("HELLO", "3"). - Reply(RedisMessage{ + Reply(ValkeyMessage{ typ: '%', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "proto"}, {typ: ':', integer: 3}, }, @@ -159,8 +159,8 @@ func TestMuxReuseWire(t *testing.T) { t.Run("reuse wire if no error", func(t *testing.T) { m, checkClean := setupMux([]*mockWire{ { - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "PONG"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "PONG"}, nil) }, }, }) @@ -176,18 +176,18 @@ func TestMuxReuseWire(t *testing.T) { t.Run("reuse blocking pool", func(t *testing.T) { blocking := make(chan struct{}) - response := make(chan RedisResult) + response := make(chan ValkeyResult) m, checkClean := setupMux([]*mockWire{ { // leave first wire for pipeline calls }, { - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "ACQUIRED"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "ACQUIRED"}, nil) }, }, { - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { blocking <- struct{}{} return <-response }, @@ -220,7 +220,7 @@ func TestMuxReuseWire(t *testing.T) { t.Fatalf("unexpected response %v", val) } - response <- newResult(RedisMessage{typ: '+', string: "BLOCK_RESPONSE"}, nil) + response <- newResult(ValkeyMessage{typ: '+', string: "BLOCK_RESPONSE"}, nil) <-blocking }) @@ -258,8 +258,8 @@ func TestMuxDelegation(t *testing.T) { t.Run("wire info", func(t *testing.T) { m, checkClean := setupMux([]*mockWire{ { - InfoFn: func() map[string]RedisMessage { - return map[string]RedisMessage{"key": {typ: '+', string: "value"}} + InfoFn: func() map[string]ValkeyMessage { + return map[string]ValkeyMessage{"key": {typ: '+', string: "value"}} }, }, }) @@ -304,7 +304,7 @@ func TestMuxDelegation(t *testing.T) { t.Run("wire do", func(t *testing.T) { m, checkClean := setupMux([]*mockWire{ { - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return newErrResult(context.DeadlineExceeded) }, ErrorFn: func() error { @@ -312,11 +312,11 @@ func TestMuxDelegation(t *testing.T) { }, }, { - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if cmd.Commands()[0] != "READONLY_COMMAND" { t.Fatalf("command should be READONLY_COMMAND") } - return newResult(RedisMessage{typ: '+', string: "READONLY_COMMAND_RESPONSE"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "READONLY_COMMAND_RESPONSE"}, nil) }, }, }) @@ -335,8 +335,8 @@ func TestMuxDelegation(t *testing.T) { t.Run("wire do stream", func(t *testing.T) { m, checkClean := setupMux([]*mockWire{ { - DoStreamFn: func(pool *pool, cmd Completed) RedisResultStream { - return RedisResultStream{e: errors.New(cmd.Commands()[0])} + DoStreamFn: func(pool *pool, cmd Completed) ValkeyResultStream { + return ValkeyResultStream{e: errors.New(cmd.Commands()[0])} }, }, }) @@ -350,16 +350,16 @@ func TestMuxDelegation(t *testing.T) { t.Run("wire do multi", func(t *testing.T) { m, checkClean := setupMux([]*mockWire{ { - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newErrResult(context.DeadlineExceeded)}} + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(context.DeadlineExceeded)}} }, ErrorFn: func() error { return context.DeadlineExceeded }, }, { - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "MULTI_COMMANDS_RESPONSE"}, nil)}} + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "MULTI_COMMANDS_RESPONSE"}, nil)}} }, }, }) @@ -378,8 +378,8 @@ func TestMuxDelegation(t *testing.T) { t.Run("wire do multi stream", func(t *testing.T) { m, checkClean := setupMux([]*mockWire{ { - DoMultiStreamFn: func(pool *pool, cmd ...Completed) MultiRedisResultStream { - return MultiRedisResultStream{e: errors.New(cmd[0].Commands()[0])} + DoMultiStreamFn: func(pool *pool, cmd ...Completed) MultiValkeyResultStream { + return MultiValkeyResultStream{e: errors.New(cmd[0].Commands()[0])} }, }, }) @@ -393,7 +393,7 @@ func TestMuxDelegation(t *testing.T) { t.Run("wire do cache", func(t *testing.T) { m, checkClean := setupMux([]*mockWire{ { - DoCacheFn: func(cmd Cacheable, ttl time.Duration) RedisResult { + DoCacheFn: func(cmd Cacheable, ttl time.Duration) ValkeyResult { return newErrResult(context.DeadlineExceeded) }, ErrorFn: func() error { @@ -401,8 +401,8 @@ func TestMuxDelegation(t *testing.T) { }, }, { - DoCacheFn: func(cmd Cacheable, ttl time.Duration) RedisResult { - return newResult(RedisMessage{typ: '+', string: "READONLY_COMMAND_RESPONSE"}, nil) + DoCacheFn: func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "READONLY_COMMAND_RESPONSE"}, nil) }, }, }) @@ -421,16 +421,16 @@ func TestMuxDelegation(t *testing.T) { t.Run("wire do multi cache", func(t *testing.T) { m, checkClean := setupMux([]*mockWire{ { - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - return &redisresults{s: []RedisResult{newErrResult(context.DeadlineExceeded)}} + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(context.DeadlineExceeded)}} }, ErrorFn: func() error { return context.DeadlineExceeded }, }, { - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "MULTI_COMMANDS_RESPONSE"}, nil)}} + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "MULTI_COMMANDS_RESPONSE"}, nil)}} }, }, }) @@ -452,16 +452,16 @@ func TestMuxDelegation(t *testing.T) { for i := range wires { idx := uint16(i) wires[i] = &mockWire{ - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { - result := make([]RedisResult, len(multi)) + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { + result := make([]ValkeyResult, len(multi)) for j, cmd := range multi { if s := cmd.Cmd.Slot() & uint16(len(wires)-1); s != idx { result[j] = newErrResult(errors.New(fmt.Sprintf("wrong slot %v %v", s, idx))) } else { - result[j] = newResult(RedisMessage{typ: '+', string: cmd.Cmd.Commands()[1]}, nil) + result[j] = newResult(ValkeyMessage{typ: '+', string: cmd.Cmd.Commands()[1]}, nil) } } - return &redisresults{s: result} + return &valkeyresults{s: result} }, } } @@ -494,13 +494,13 @@ func TestMuxDelegation(t *testing.T) { for i := range wires { idx := uint16(i) wires[i] = &mockWire{ - DoMultiCacheFn: func(multi ...CacheableTTL) *redisresults { + DoMultiCacheFn: func(multi ...CacheableTTL) *valkeyresults { for _, cmd := range multi { if s := cmd.Cmd.Slot() & uint16(len(wires)-1); s != idx { - return &redisresults{s: []RedisResult{newErrResult(errors.New(fmt.Sprintf("wrong slot %v %v", s, idx)))}} + return &valkeyresults{s: []ValkeyResult{newErrResult(errors.New(fmt.Sprintf("wrong slot %v %v", s, idx)))}} } } - return &redisresults{s: []RedisResult{newErrResult(context.DeadlineExceeded)}} + return &valkeyresults{s: []ValkeyResult{newErrResult(context.DeadlineExceeded)}} }, ErrorFn: func() error { return context.DeadlineExceeded @@ -556,20 +556,20 @@ func TestMuxDelegation(t *testing.T) { t.Run("single blocking", func(t *testing.T) { blocked := make(chan struct{}) - responses := make(chan RedisResult) + responses := make(chan ValkeyResult) m, checkClean := setupMux([]*mockWire{ { // leave first wire for pipeline calls }, { - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { blocked <- struct{}{} return <-responses }, }, { - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { blocked <- struct{}{} return <-responses }, @@ -598,7 +598,7 @@ func TestMuxDelegation(t *testing.T) { <-blocked } for i := 0; i < 2; i++ { - responses <- newResult(RedisMessage{typ: '+', string: "BLOCK_COMMANDS_RESPONSE"}, nil) + responses <- newResult(ValkeyMessage{typ: '+', string: "BLOCK_COMMANDS_RESPONSE"}, nil) } wg.Wait() }) @@ -610,7 +610,7 @@ func TestMuxDelegation(t *testing.T) { // leave first wire for pipeline calls }, { - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { return newErrResult(context.DeadlineExceeded) }, ErrorFn: func() error { @@ -621,8 +621,8 @@ func TestMuxDelegation(t *testing.T) { }, }, { - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "OK"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) }, }, }) @@ -644,22 +644,22 @@ func TestMuxDelegation(t *testing.T) { t.Run("multiple blocking", func(t *testing.T) { blocked := make(chan struct{}) - responses := make(chan RedisResult) + responses := make(chan ValkeyResult) m, checkClean := setupMux([]*mockWire{ { // leave first wire for pipeline calls }, { - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { blocked <- struct{}{} - return &redisresults{s: []RedisResult{<-responses}} + return &valkeyresults{s: []ValkeyResult{<-responses}} }, }, { - DoMultiFn: func(cmd ...Completed) *redisresults { + DoMultiFn: func(cmd ...Completed) *valkeyresults { blocked <- struct{}{} - return &redisresults{s: []RedisResult{<-responses}} + return &valkeyresults{s: []ValkeyResult{<-responses}} }, }, }) @@ -690,7 +690,7 @@ func TestMuxDelegation(t *testing.T) { <-blocked } for i := 0; i < 2; i++ { - responses <- newResult(RedisMessage{typ: '+', string: "BLOCK_COMMANDS_RESPONSE"}, nil) + responses <- newResult(ValkeyMessage{typ: '+', string: "BLOCK_COMMANDS_RESPONSE"}, nil) } wg.Wait() }) @@ -702,8 +702,8 @@ func TestMuxDelegation(t *testing.T) { // leave first wire for pipeline calls }, { - DoMultiFn: func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newErrResult(context.DeadlineExceeded)}} + DoMultiFn: func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(context.DeadlineExceeded)}} }, ErrorFn: func() error { return context.DeadlineExceeded @@ -713,8 +713,8 @@ func TestMuxDelegation(t *testing.T) { }, }, { - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "OK"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "OK"}, nil) }, }, }) @@ -746,16 +746,16 @@ func TestMuxRegisterCloseHook(t *testing.T) { var hook atomic.Value m, checkClean := setupMux([]*mockWire{ { - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "PONG1"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "PONG1"}, nil) }, SetOnCloseHookFn: func(fn func(error)) { hook.Store(fn) }, }, { - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "PONG2"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "PONG2"}, nil) }, }, }) @@ -773,8 +773,8 @@ func TestMuxRegisterCloseHook(t *testing.T) { var hook atomic.Value m, checkClean := setupMux([]*mockWire{ { - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "PONG1"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "PONG1"}, nil) }, SetOnCloseHookFn: func(fn func(error)) { hook.Store(fn) @@ -826,14 +826,14 @@ func BenchmarkClientSideCaching(b *testing.B) { } type mockWire struct { - DoFn func(cmd Completed) RedisResult - DoCacheFn func(cmd Cacheable, ttl time.Duration) RedisResult - DoMultiFn func(multi ...Completed) *redisresults - DoMultiCacheFn func(multi ...CacheableTTL) *redisresults + DoFn func(cmd Completed) ValkeyResult + DoCacheFn func(cmd Cacheable, ttl time.Duration) ValkeyResult + DoMultiFn func(multi ...Completed) *valkeyresults + DoMultiCacheFn func(multi ...CacheableTTL) *valkeyresults ReceiveFn func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error - DoStreamFn func(pool *pool, cmd Completed) RedisResultStream - DoMultiStreamFn func(pool *pool, cmd ...Completed) MultiRedisResultStream - InfoFn func() map[string]RedisMessage + DoStreamFn func(pool *pool, cmd Completed) ValkeyResultStream + DoMultiStreamFn func(pool *pool, cmd ...Completed) MultiValkeyResultStream + InfoFn func() map[string]ValkeyMessage VersionFn func() int ErrorFn func() error CloseFn func() @@ -843,28 +843,28 @@ type mockWire struct { SetOnCloseHookFn func(fn func(error)) } -func (m *mockWire) Do(ctx context.Context, cmd Completed) RedisResult { +func (m *mockWire) Do(ctx context.Context, cmd Completed) ValkeyResult { if m.DoFn != nil { return m.DoFn(cmd) } - return RedisResult{} + return ValkeyResult{} } -func (m *mockWire) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) RedisResult { +func (m *mockWire) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) ValkeyResult { if m.DoCacheFn != nil { return m.DoCacheFn(cmd, ttl) } - return RedisResult{} + return ValkeyResult{} } -func (m *mockWire) DoMultiCache(ctx context.Context, multi ...CacheableTTL) *redisresults { +func (m *mockWire) DoMultiCache(ctx context.Context, multi ...CacheableTTL) *valkeyresults { if m.DoMultiCacheFn != nil { return m.DoMultiCacheFn(multi...) } return nil } -func (m *mockWire) DoMulti(ctx context.Context, multi ...Completed) *redisresults { +func (m *mockWire) DoMulti(ctx context.Context, multi ...Completed) *valkeyresults { if m.DoMultiFn != nil { return m.DoMultiFn(multi...) } @@ -878,18 +878,18 @@ func (m *mockWire) Receive(ctx context.Context, subscribe Completed, fn func(mes return nil } -func (m *mockWire) DoStream(ctx context.Context, pool *pool, cmd Completed) RedisResultStream { +func (m *mockWire) DoStream(ctx context.Context, pool *pool, cmd Completed) ValkeyResultStream { if m.DoStreamFn != nil { return m.DoStreamFn(pool, cmd) } - return RedisResultStream{} + return ValkeyResultStream{} } -func (m *mockWire) DoMultiStream(ctx context.Context, pool *pool, cmd ...Completed) MultiRedisResultStream { +func (m *mockWire) DoMultiStream(ctx context.Context, pool *pool, cmd ...Completed) MultiValkeyResultStream { if m.DoMultiStreamFn != nil { return m.DoMultiStreamFn(pool, cmd...) } - return MultiRedisResultStream{} + return MultiValkeyResultStream{} } func (m *mockWire) CleanSubscriptions() { @@ -913,7 +913,7 @@ func (m *mockWire) SetOnCloseHook(fn func(error)) { return } -func (m *mockWire) Info() map[string]RedisMessage { +func (m *mockWire) Info() map[string]ValkeyMessage { if m.InfoFn != nil { return m.InfoFn() } diff --git a/om/README.md b/om/README.md index d396322..90d990a 100644 --- a/om/README.md +++ b/om/README.md @@ -1,6 +1,6 @@ # Generic Object Mapping -The `om.NewHashRepository` and `om.NewJSONRepository` creates an OM repository backed by redis hash or RedisJSON. +The `om.NewHashRepository` and `om.NewJSONRepository` creates an OM repository backed by valkey hash or RedisJSON. ```golang package main @@ -10,20 +10,20 @@ import ( "fmt" "time" - "github.com/redis/rueidis" - "github.com/redis/rueidis/om" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/om" ) type Example struct { - Key string `json:"key" redis:",key"` // the redis:",key" is required to indicate which field is the ULID key - Ver int64 `json:"ver" redis:",ver"` // the redis:",ver" is required to do optimistic locking to prevent lost update - ExAt time.Time `json:"exat" redis:",exat"` // the redis:",exat" is optional for setting record expiry with unix timestamp + Key string `json:"key" valkey:",key"` // the valkey:",key" is required to indicate which field is the ULID key + Ver int64 `json:"ver" valkey:",ver"` // the valkey:",ver" is required to do optimistic locking to prevent lost update + ExAt time.Time `json:"exat" valkey:",exat"` // the valkey:",exat" is optional for setting record expiry with unix timestamp Str string `json:"str"` // both NewHashRepository and NewJSONRepository use json tag as field name } func main() { ctx := context.Background() - c, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) + c, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } @@ -52,13 +52,13 @@ If you have RediSearch, you can create and search the repository against the ind ```golang if _, ok := repo.(*om.HashRepository[Example]); ok { - repo.CreateIndex(ctx, func(schema om.FtCreateSchema) rueidis.Completed { - return schema.FieldName("str").Tag().Build() // Note that the Example.Str field is mapped to str on redis by its json tag + repo.CreateIndex(ctx, func(schema om.FtCreateSchema) valkey.Completed { + return schema.FieldName("str").Tag().Build() // Note that the Example.Str field is mapped to str on valkey by its json tag }) } if _, ok := repo.(*om.JSONRepository[Example]); ok { - repo.CreateIndex(ctx, func(schema om.FtCreateSchema) rueidis.Completed { + repo.CreateIndex(ctx, func(schema om.FtCreateSchema) valkey.Completed { return schema.FieldName("$.str").As("str").Tag().Build() // the FieldName of a json index should be a json path syntax }) } @@ -67,12 +67,12 @@ exp := repo.NewEntity() exp.Str = "special_chars:[$.-]" repo.Save(ctx, exp) -n, records, _ := repo.Search(ctx, func(search om.FtSearchIndex) rueidis.Completed { +n, records, _ := repo.Search(ctx, func(search om.FtSearchIndex) valkey.Completed { // Note that by using the named parameters with DIALECT >= 2, you won't have to escape chars for building queries. return search.Query("@str:{$v}").Params().Nargs(2).NameValue().NameValue("v", exp.Str).Dialect(2).Build() }) -fmt.Println("total", n) // n is total number of results matched in redis, which is >= len(records) +fmt.Println("total", n) // n is total number of results matched in valkey, which is >= len(records) for _, v := range records { fmt.Println(v.Str) // print "special_chars:[$.-]" @@ -92,7 +92,7 @@ repo2 := om.NewHashRepository("my_prefix", Example{}, c, om.WithIndexName("my_in ### Object Expiry Timestamp -Setting a `redis:",exat"` tag on a `time.Time` field will set `PEXPIREAT` on the record accordingly when calling `.Save()`. +Setting a `valkey:",exat"` tag on a `time.Time` field will set `PEXPIREAT` on the record accordingly when calling `.Save()`. If the `time.Time` is zero, then the expiry will be untouched when calling `.Save()`. diff --git a/om/conv.go b/om/conv.go index e80da1a..976ae5b 100644 --- a/om/conv.go +++ b/om/conv.go @@ -7,7 +7,7 @@ import ( "strconv" "unsafe" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) func newHashConvFactory(t reflect.Type, schema schema) *hashConvFactory { @@ -53,7 +53,7 @@ func (r hashConv) ToHash() (fields map[string]string) { ref := r.entity.Field(f.idx) if f.conv.ValueToString == nil { if bs, err := json.Marshal(ref.Interface()); err == nil { - fields[k] = rueidis.BinaryString(bs) + fields[k] = valkey.BinaryString(bs) } } else if v, ok := f.conv.ValueToString(ref); ok { fields[k] = v @@ -181,7 +181,7 @@ var converters = struct { slice: map[reflect.Kind]converter{ reflect.Uint8: { ValueToString: func(value reflect.Value) (string, bool) { - return rueidis.BinaryString(value.Bytes()), true + return valkey.BinaryString(value.Bytes()), true }, StringToValue: func(value string) (reflect.Value, error) { buf := unsafe.Slice(unsafe.StringData(value), len(value)) @@ -191,19 +191,19 @@ var converters = struct { reflect.Float32: { ValueToString: func(value reflect.Value) (string, bool) { vs, ok := value.Interface().([]float32) - return rueidis.VectorString32(vs), ok + return valkey.VectorString32(vs), ok }, StringToValue: func(value string) (reflect.Value, error) { - return reflect.ValueOf(rueidis.ToVector32(value)), nil + return reflect.ValueOf(valkey.ToVector32(value)), nil }, }, reflect.Float64: { ValueToString: func(value reflect.Value) (string, bool) { vs, ok := value.Interface().([]float64) - return rueidis.VectorString64(vs), ok + return valkey.VectorString64(vs), ok }, StringToValue: func(value string) (reflect.Value, error) { - return reflect.ValueOf(rueidis.ToVector64(value)), nil + return reflect.ValueOf(valkey.ToVector64(value)), nil }, }, reflect.Struct: { diff --git a/om/cursor.go b/om/cursor.go index def5fcc..6dd75ab 100644 --- a/om/cursor.go +++ b/om/cursor.go @@ -4,18 +4,18 @@ import ( "context" "errors" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) var EndOfCursor = errors.New("end of cursor") -func newAggregateCursor(idx string, client rueidis.Client, first []map[string]string, cursor, total int64) *AggregateCursor { +func newAggregateCursor(idx string, client valkey.Client, first []map[string]string, cursor, total int64) *AggregateCursor { return &AggregateCursor{client: client, idx: idx, first: first, id: cursor, n: total} } // AggregateCursor unifies the response of FT.AGGREGATE with or without WITHCURSOR type AggregateCursor struct { - client rueidis.Client + client valkey.Client idx string first []map[string]string id int64 diff --git a/om/cursor_test.go b/om/cursor_test.go index 1979412..528611a 100644 --- a/om/cursor_test.go +++ b/om/cursor_test.go @@ -5,15 +5,15 @@ import ( "strconv" "testing" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) type Book struct { - Key string `json:"key" redis:",key"` - Loc string `json:"loc" redis:",loc"` - Ver int64 `json:"ver" redis:",ver"` - ID int64 `json:"id" redis:",id"` - Count int64 `json:"count" redis:",count"` + Key string `json:"key" valkey:",key"` + Loc string `json:"loc" valkey:",loc"` + Ver int64 `json:"ver" valkey:",ver"` + ID int64 `json:"id" valkey:",id"` + Count int64 `json:"count" valkey:",count"` } func TestAggregateCursor(t *testing.T) { @@ -26,7 +26,7 @@ func TestAggregateCursor(t *testing.T) { jsonRepo := NewJSONRepository("book", Book{}, client) hashRepo := NewHashRepository("book", Book{}, client) - if err := jsonRepo.CreateIndex(ctx, func(schema FtCreateSchema) rueidis.Completed { + if err := jsonRepo.CreateIndex(ctx, func(schema FtCreateSchema) valkey.Completed { return schema. FieldName("$.id").As("id").Numeric(). FieldName("$.loc").As("loc").Tag(). @@ -35,7 +35,7 @@ func TestAggregateCursor(t *testing.T) { t.Fatal(err) } - if err := hashRepo.CreateIndex(ctx, func(schema FtCreateSchema) rueidis.Completed { + if err := hashRepo.CreateIndex(ctx, func(schema FtCreateSchema) valkey.Completed { return schema. FieldName("id").As("id").Numeric(). FieldName("loc").As("loc").Tag(). @@ -67,7 +67,7 @@ func testRepo(t *testing.T, repo Repository[Book]) { t.Run("Deadline exceed", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - _, err := repo.Aggregate(ctx, func(search FtAggregateIndex) rueidis.Completed { + _, err := repo.Aggregate(ctx, func(search FtAggregateIndex) valkey.Completed { return search.Query("any").Build() }) if err != context.Canceled { @@ -76,7 +76,7 @@ func testRepo(t *testing.T, repo Repository[Book]) { }) t.Run("Without cursor", func(t *testing.T) { - cursor, err := repo.Aggregate(context.Background(), func(search FtAggregateIndex) rueidis.Completed { + cursor, err := repo.Aggregate(context.Background(), func(search FtAggregateIndex) valkey.Completed { return search.Query("@loc:{1}"). Groupby(1).Property("@id").Reduce("MIN").Nargs(1).Arg("@count").As("minCount"). Sortby(2).Property("@minCount").Asc().Build() @@ -108,7 +108,7 @@ func testRepo(t *testing.T, repo Repository[Book]) { }) t.Run("With cursor", func(t *testing.T) { - cursor, err := repo.Aggregate(context.Background(), func(search FtAggregateIndex) rueidis.Completed { + cursor, err := repo.Aggregate(context.Background(), func(search FtAggregateIndex) valkey.Completed { return search.Query("@loc:{1}"). Groupby(1).Property("@id").Reduce("MIN").Nargs(1).Arg("@count").As("minCount"). Sortby(2).Property("@minCount").Asc().Withcursor().Count(2).Build() @@ -147,7 +147,7 @@ func testRepo(t *testing.T, repo Repository[Book]) { }) t.Run("Read deadline", func(t *testing.T) { - cursor, err := repo.Aggregate(context.Background(), func(search FtAggregateIndex) rueidis.Completed { + cursor, err := repo.Aggregate(context.Background(), func(search FtAggregateIndex) valkey.Completed { return search.Query("@loc:{1}"). Groupby(1).Property("@id").Reduce("MIN").Nargs(1).Arg("@count").As("minCount"). Sortby(2).Property("@minCount").Asc().Withcursor().Count(2).Build() @@ -166,7 +166,7 @@ func testRepo(t *testing.T, repo Repository[Book]) { }) t.Run("Del cursor", func(t *testing.T) { - cursor, err := repo.Aggregate(context.Background(), func(search FtAggregateIndex) rueidis.Completed { + cursor, err := repo.Aggregate(context.Background(), func(search FtAggregateIndex) valkey.Completed { return search.Query("@loc:{1}"). Groupby(1).Property("@id").Reduce("MIN").Nargs(1).Arg("@count").As("minCount"). Sortby(2).Property("@minCount").Asc().Withcursor().Count(2).Build() diff --git a/om/go.mod b/om/go.mod index df0f020..cadbcad 100644 --- a/om/go.mod +++ b/om/go.mod @@ -1,12 +1,12 @@ -module github.com/redis/rueidis/om +module github.com/rueian/valkey-go/om go 1.20 -replace github.com/redis/rueidis => ../ +replace github.com/rueian/valkey-go => ../ require ( github.com/oklog/ulid/v2 v2.1.0 - github.com/redis/rueidis v1.0.34 + github.com/rueian/valkey-go v1.0.34 ) require golang.org/x/sys v0.17.0 // indirect diff --git a/om/hash.go b/om/hash.go index b87020b..44ec7e1 100644 --- a/om/hash.go +++ b/om/hash.go @@ -6,13 +6,13 @@ import ( "strconv" "time" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) // NewHashRepository creates an HashRepository. -// The prefix parameter is used as redis key prefix. The entity stored by the repository will be named in the form of `{prefix}:{id}` -// The schema parameter should be a struct with fields tagged with `redis:",key"` and `redis:",ver"` -func NewHashRepository[T any](prefix string, schema T, client rueidis.Client, opts ...RepositoryOption) Repository[T] { +// The prefix parameter is used as valkey key prefix. The entity stored by the repository will be named in the form of `{prefix}:{id}` +// The schema parameter should be a struct with fields tagged with `valkey:",key"` and `valkey:",ver"` +func NewHashRepository[T any](prefix string, schema T, client valkey.Client, opts ...RepositoryOption) Repository[T] { repo := &HashRepository[T]{ prefix: prefix, idx: "hashidx:" + prefix, @@ -29,17 +29,17 @@ func NewHashRepository[T any](prefix string, schema T, client rueidis.Client, op var _ Repository[any] = (*HashRepository[any])(nil) -// HashRepository is an OM repository backed by redis hash. +// HashRepository is an OM repository backed by valkey hash. type HashRepository[T any] struct { schema schema typ reflect.Type - client rueidis.Client + client valkey.Client factory *hashConvFactory prefix string idx string } -// NewEntity returns an empty entity and will have the `redis:",key"` field be set with ULID automatically. +// NewEntity returns an empty entity and will have the `valkey:",key"` field be set with ULID automatically. func (r *HashRepository[T]) NewEntity() (entity *T) { var v T reflect.ValueOf(&v).Elem().Field(r.schema.key.idx).Set(reflect.ValueOf(id())) @@ -64,7 +64,7 @@ func (r *HashRepository[T]) FetchCache(ctx context.Context, id string, ttl time. return v, err } -func (r *HashRepository[T]) toExec(entity *T) (val reflect.Value, exec rueidis.LuaExec) { +func (r *HashRepository[T]) toExec(entity *T) (val reflect.Value, exec valkey.LuaExec) { val = reflect.ValueOf(entity).Elem() fields := r.factory.NewConverter(val).ToHash() keyVal := fields[r.schema.key.name] @@ -92,12 +92,12 @@ func (r *HashRepository[T]) toExec(entity *T) (val reflect.Value, exec rueidis.L return } -// Save the entity under the redis key of `{prefix}:{id}`. -// It also uses the `redis:",ver"` field and lua script to perform optimistic locking and prevent lost update. +// Save the entity under the valkey key of `{prefix}:{id}`. +// It also uses the `valkey:",ver"` field and lua script to perform optimistic locking and prevent lost update. func (r *HashRepository[T]) Save(ctx context.Context, entity *T) (err error) { val, exec := r.toExec(entity) str, err := hashSaveScript.Exec(ctx, r.client, exec.Keys, exec.Args).ToString() - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { return ErrVersionMismatch } if err == nil { @@ -111,13 +111,13 @@ func (r *HashRepository[T]) Save(ctx context.Context, entity *T) (err error) { func (r *HashRepository[T]) SaveMulti(ctx context.Context, entities ...*T) []error { errs := make([]error, len(entities)) vals := make([]reflect.Value, len(entities)) - exec := make([]rueidis.LuaExec, len(entities)) + exec := make([]valkey.LuaExec, len(entities)) for i, entity := range entities { vals[i], exec[i] = r.toExec(entity) } for i, resp := range hashSaveScript.ExecMulti(ctx, r.client, exec...) { if str, err := resp.ToString(); err != nil { - if errs[i] = err; rueidis.IsRedisNil(err) { + if errs[i] = err; valkey.IsValkeyNil(err) { errs[i] = ErrVersionMismatch } } else { @@ -128,14 +128,14 @@ func (r *HashRepository[T]) SaveMulti(ctx context.Context, entities ...*T) []err return errs } -// Remove the entity under the redis key of `{prefix}:{id}`. +// Remove the entity under the valkey key of `{prefix}:{id}`. func (r *HashRepository[T]) Remove(ctx context.Context, id string) error { return r.client.Do(ctx, r.client.B().Del().Key(key(r.prefix, id)).Build()).Error() } // CreateIndex uses FT.CREATE from the RediSearch module to create inverted index under the name `hashidx:{prefix}` // You can use the cmdFn parameter to mutate the index construction command. -func (r *HashRepository[T]) CreateIndex(ctx context.Context, cmdFn func(schema FtCreateSchema) rueidis.Completed) error { +func (r *HashRepository[T]) CreateIndex(ctx context.Context, cmdFn func(schema FtCreateSchema) valkey.Completed) error { return r.client.Do(ctx, cmdFn(r.client.B().FtCreate().Index(r.idx).OnHash().Prefix(1).Prefix(r.prefix+":").Schema())).Error() } @@ -146,11 +146,11 @@ func (r *HashRepository[T]) DropIndex(ctx context.Context) error { // Search uses FT.SEARCH from the RediSearch module to search the index whose name is `hashidx:{prefix}` // It returns three values: -// 1. total count of match results inside the redis, and note that it might be larger than returned search result. +// 1. total count of match results inside the valkey, and note that it might be larger than returned search result. // 2. search result, and note that its length might smaller than the first return value. // 3. error if any // You can use the cmdFn parameter to mutate the search command. -func (r *HashRepository[T]) Search(ctx context.Context, cmdFn func(search FtSearchIndex) rueidis.Completed) (n int64, s []*T, err error) { +func (r *HashRepository[T]) Search(ctx context.Context, cmdFn func(search FtSearchIndex) valkey.Completed) (n int64, s []*T, err error) { n, resp, err := r.client.Do(ctx, cmdFn(r.client.B().FtSearch().Index(r.idx))).AsFtSearch() if err == nil { s = make([]*T, len(resp)) @@ -164,7 +164,7 @@ func (r *HashRepository[T]) Search(ctx context.Context, cmdFn func(search FtSear } // Aggregate performs the FT.AGGREGATE and returns a *AggregateCursor for accessing the results -func (r *HashRepository[T]) Aggregate(ctx context.Context, cmdFn func(agg FtAggregateIndex) rueidis.Completed) (cursor *AggregateCursor, err error) { +func (r *HashRepository[T]) Aggregate(ctx context.Context, cmdFn func(agg FtAggregateIndex) valkey.Completed) (cursor *AggregateCursor, err error) { cid, total, resp, err := r.client.Do(ctx, cmdFn(r.client.B().FtAggregate().Index(r.idx))).AsFtAggregateCursor() if err != nil { return nil, err @@ -192,7 +192,7 @@ func (r *HashRepository[T]) fromFields(fields map[string]string) (*T, error) { return &v, nil } -var hashSaveScript = rueidis.NewLuaScript(` +var hashSaveScript = valkey.NewLuaScript(` local v = redis.call('HGET',KEYS[1],ARGV[1]) if (not v or v == ARGV[2]) then diff --git a/om/hash_test.go b/om/hash_test.go index 1e026c1..b93a501 100644 --- a/om/hash_test.go +++ b/om/hash_test.go @@ -10,11 +10,11 @@ import ( "time" "github.com/oklog/ulid/v2" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) type HashTestStruct struct { - Key string `redis:",key"` + Key string `valkey:",key"` F2 *bool F2N *bool F3 *string @@ -22,7 +22,7 @@ type HashTestStruct struct { F4 *int64 F4N *int64 Val []byte - Ver int64 `redis:",ver"` + Ver int64 `valkey:",ver"` F1 bool F5 *bool Vec32 []float32 @@ -31,14 +31,14 @@ type HashTestStruct struct { } type Unsupported struct { - Key string `redis:",key"` - Ver int64 `redis:",ver"` + Key string `valkey:",key"` + Ver int64 `valkey:",ver"` F1 int32 } type Mismatch struct { - Key string `redis:",key"` - Ver int64 `redis:",ver"` + Key string `valkey:",key"` + Ver int64 `valkey:",ver"` F1 int64 F2 *int64 } @@ -59,7 +59,7 @@ func TestNewHashRepositoryMismatch(t *testing.T) { defer client.Close() repo := NewHashRepository("hashmismatch", Mismatch{}, client) - if err := repo.CreateIndex(ctx, func(schema FtCreateSchema) rueidis.Completed { + if err := repo.CreateIndex(ctx, func(schema FtCreateSchema) valkey.Completed { return schema.FieldName("F1").Tag().Build() }); err != nil { t.Fatal(err) @@ -76,7 +76,7 @@ func TestNewHashRepositoryMismatch(t *testing.T) { if _, err := repo.Fetch(ctx, e.Key); err == nil { t.Fatal("Fetch not failed as expected") } - if _, _, err := repo.Search(ctx, func(search FtSearchIndex) rueidis.Completed { + if _, _, err := repo.Search(ctx, func(search FtSearchIndex) valkey.Completed { return search.Query("*").Build() }); err == nil { t.Fatal("Search not failed as expected") @@ -94,7 +94,7 @@ func TestNewHashRepositoryMismatch(t *testing.T) { if _, err := repo.Fetch(ctx, e.Key); err == nil { t.Fatal("Fetch not failed as expected") } - if _, _, err := repo.Search(ctx, func(search FtSearchIndex) rueidis.Completed { + if _, _, err := repo.Search(ctx, func(search FtSearchIndex) valkey.Completed { return search.Query("*").Build() }); err == nil { t.Fatal("Search not failed as expected") @@ -172,14 +172,14 @@ func TestNewHashRepository(t *testing.T) { }) t.Run("Search", func(t *testing.T) { - err := repo.CreateIndex(ctx, func(schema FtCreateSchema) rueidis.Completed { + err := repo.CreateIndex(ctx, func(schema FtCreateSchema) valkey.Completed { return schema.FieldName("Val").Text().Build() }) time.Sleep(time.Second) if err != nil { t.Fatal(err) } - n, records, err := repo.Search(ctx, func(search FtSearchIndex) rueidis.Completed { + n, records, err := repo.Search(ctx, func(search FtSearchIndex) valkey.Completed { return search.Query("*").Build() }) if err != nil { @@ -200,14 +200,14 @@ func TestNewHashRepository(t *testing.T) { }) t.Run("Search Sort", func(t *testing.T) { - err := repo.CreateIndex(ctx, func(schema FtCreateSchema) rueidis.Completed { + err := repo.CreateIndex(ctx, func(schema FtCreateSchema) valkey.Completed { return schema.FieldName("Val").Text().Sortable().Build() }) time.Sleep(time.Second) if err != nil { t.Fatal(err) } - n, records, err := repo.Search(ctx, func(search FtSearchIndex) rueidis.Completed { + n, records, err := repo.Search(ctx, func(search FtSearchIndex) valkey.Completed { return search.Query("*").Sortby("Val").Build() }) if err != nil { @@ -282,9 +282,9 @@ func TestNewHashRepository(t *testing.T) { } type HashTestTTLStruct struct { - Key string `redis:",key"` - Ver int64 `redis:",ver"` - Exat time.Time `redis:",exat"` + Key string `valkey:",key"` + Ver int64 `valkey:",ver"` + Exat time.Time `valkey:",exat"` } //gocyclo:ignore diff --git a/om/json.go b/om/json.go index 3317499..94b9746 100644 --- a/om/json.go +++ b/om/json.go @@ -8,13 +8,13 @@ import ( "strings" "time" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) // NewJSONRepository creates an JSONRepository. -// The prefix parameter is used as redis key prefix. The entity stored by the repository will be named in the form of `{prefix}:{id}` -// The schema parameter should be a struct with fields tagged with `redis:",key"` and `redis:",ver"` -func NewJSONRepository[T any](prefix string, schema T, client rueidis.Client, opts ...RepositoryOption) Repository[T] { +// The prefix parameter is used as valkey key prefix. The entity stored by the repository will be named in the form of `{prefix}:{id}` +// The schema parameter should be a struct with fields tagged with `valkey:",key"` and `valkey:",ver"` +func NewJSONRepository[T any](prefix string, schema T, client valkey.Client, opts ...RepositoryOption) Repository[T] { repo := &JSONRepository[T]{ prefix: prefix, idx: "jsonidx:" + prefix, @@ -34,12 +34,12 @@ var _ Repository[any] = (*JSONRepository[any])(nil) type JSONRepository[T any] struct { schema schema typ reflect.Type - client rueidis.Client + client valkey.Client prefix string idx string } -// NewEntity returns an empty entity and will have the `redis:",key"` field be set with ULID automatically. +// NewEntity returns an empty entity and will have the `valkey:",key"` field be set with ULID automatically. func (r *JSONRepository[T]) NewEntity() *T { var v T reflect.ValueOf(&v).Elem().Field(r.schema.key.idx).Set(reflect.ValueOf(id())) @@ -72,7 +72,7 @@ func (r *JSONRepository[T]) decode(record string) (*T, error) { return &v, nil } -func (r *JSONRepository[T]) toExec(entity *T) (verf reflect.Value, exec rueidis.LuaExec) { +func (r *JSONRepository[T]) toExec(entity *T) (verf reflect.Value, exec valkey.LuaExec) { val := reflect.ValueOf(entity).Elem() verf = val.Field(r.schema.ver.idx) extVal := int64(0) @@ -83,19 +83,19 @@ func (r *JSONRepository[T]) toExec(entity *T) (verf reflect.Value, exec rueidis. } exec.Keys = []string{key(r.prefix, val.Field(r.schema.key.idx).String())} if extVal != 0 { - exec.Args = []string{r.schema.ver.name, strconv.FormatInt(verf.Int(), 10), rueidis.JSON(entity), strconv.FormatInt(extVal, 10)} + exec.Args = []string{r.schema.ver.name, strconv.FormatInt(verf.Int(), 10), valkey.JSON(entity), strconv.FormatInt(extVal, 10)} } else { - exec.Args = []string{r.schema.ver.name, strconv.FormatInt(verf.Int(), 10), rueidis.JSON(entity)} + exec.Args = []string{r.schema.ver.name, strconv.FormatInt(verf.Int(), 10), valkey.JSON(entity)} } return } -// Save the entity under the redis key of `{prefix}:{id}`. -// It also uses the `redis:",ver"` field and lua script to perform optimistic locking and prevent lost update. +// Save the entity under the valkey key of `{prefix}:{id}`. +// It also uses the `valkey:",ver"` field and lua script to perform optimistic locking and prevent lost update. func (r *JSONRepository[T]) Save(ctx context.Context, entity *T) (err error) { valf, exec := r.toExec(entity) str, err := jsonSaveScript.Exec(ctx, r.client, exec.Keys, exec.Args).ToString() - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { return ErrVersionMismatch } if err == nil { @@ -109,13 +109,13 @@ func (r *JSONRepository[T]) Save(ctx context.Context, entity *T) (err error) { func (r *JSONRepository[T]) SaveMulti(ctx context.Context, entities ...*T) []error { errs := make([]error, len(entities)) valf := make([]reflect.Value, len(entities)) - exec := make([]rueidis.LuaExec, len(entities)) + exec := make([]valkey.LuaExec, len(entities)) for i, entity := range entities { valf[i], exec[i] = r.toExec(entity) } for i, resp := range jsonSaveScript.ExecMulti(ctx, r.client, exec...) { if str, err := resp.ToString(); err != nil { - if errs[i] = err; rueidis.IsRedisNil(err) { + if errs[i] = err; valkey.IsValkeyNil(err) { errs[i] = ErrVersionMismatch } } else { @@ -126,7 +126,7 @@ func (r *JSONRepository[T]) SaveMulti(ctx context.Context, entities ...*T) []err return errs } -// Remove the entity under the redis key of `{prefix}:{id}`. +// Remove the entity under the valkey key of `{prefix}:{id}`. func (r *JSONRepository[T]) Remove(ctx context.Context, id string) error { return r.client.Do(ctx, r.client.B().Del().Key(key(r.prefix, id)).Build()).Error() } @@ -134,7 +134,7 @@ func (r *JSONRepository[T]) Remove(ctx context.Context, id string) error { // CreateIndex uses FT.CREATE from the RediSearch module to create inverted index under the name `jsonidx:{prefix}` // You can use the cmdFn parameter to mutate the index construction command, // and note that the field name should be specified with JSON path syntax, otherwise the index may not work as expected. -func (r *JSONRepository[T]) CreateIndex(ctx context.Context, cmdFn func(schema FtCreateSchema) rueidis.Completed) error { +func (r *JSONRepository[T]) CreateIndex(ctx context.Context, cmdFn func(schema FtCreateSchema) valkey.Completed) error { return r.client.Do(ctx, cmdFn(r.client.B().FtCreate().Index(r.idx).OnJson().Prefix(1).Prefix(r.prefix+":").Schema())).Error() } @@ -145,11 +145,11 @@ func (r *JSONRepository[T]) DropIndex(ctx context.Context) error { // Search uses FT.SEARCH from the RediSearch module to search the index whose name is `jsonidx:{prefix}` // It returns three values: -// 1. total count of match results inside the redis, and note that it might be larger than returned search result. +// 1. total count of match results inside the valkey, and note that it might be larger than returned search result. // 2. search result, and note that its length might smaller than the first return value. // 3. error if any // You can use the cmdFn parameter to mutate the search command. -func (r *JSONRepository[T]) Search(ctx context.Context, cmdFn func(search FtSearchIndex) rueidis.Completed) (n int64, s []*T, err error) { +func (r *JSONRepository[T]) Search(ctx context.Context, cmdFn func(search FtSearchIndex) valkey.Completed) (n int64, s []*T, err error) { n, resp, err := r.client.Do(ctx, cmdFn(r.client.B().FtSearch().Index(r.idx))).AsFtSearch() if err == nil { s = make([]*T, len(resp)) @@ -166,7 +166,7 @@ func (r *JSONRepository[T]) Search(ctx context.Context, cmdFn func(search FtSear } // Aggregate performs the FT.AGGREGATE and returns a *AggregateCursor for accessing the results -func (r *JSONRepository[T]) Aggregate(ctx context.Context, cmdFn func(agg FtAggregateIndex) rueidis.Completed) (cursor *AggregateCursor, err error) { +func (r *JSONRepository[T]) Aggregate(ctx context.Context, cmdFn func(agg FtAggregateIndex) valkey.Completed) (cursor *AggregateCursor, err error) { cid, total, resp, err := r.client.Do(ctx, cmdFn(r.client.B().FtAggregate().Index(r.idx))).AsFtAggregateCursor() if err != nil { return nil, err @@ -179,7 +179,7 @@ func (r *JSONRepository[T]) IndexName() string { return r.idx } -var jsonSaveScript = rueidis.NewLuaScript(` +var jsonSaveScript = valkey.NewLuaScript(` local v = redis.call('JSON.GET',KEYS[1],ARGV[1]) if (not v or v == ARGV[2]) then diff --git a/om/json_test.go b/om/json_test.go index 09777c2..c206440 100644 --- a/om/json_test.go +++ b/om/json_test.go @@ -7,14 +7,14 @@ import ( "time" "github.com/oklog/ulid/v2" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) type JSONTestStruct struct { - Key string `redis:",key"` + Key string `valkey:",key"` Nested struct{ F1 string } Val []byte - Ver int64 `redis:",ver"` + Ver int64 `valkey:",ver"` } func TestNewJsonRepositoryMismatch(t *testing.T) { @@ -25,7 +25,7 @@ func TestNewJsonRepositoryMismatch(t *testing.T) { defer client.Close() repo := NewJSONRepository("jsonmismatch", Mismatch{}, client) - if err := repo.CreateIndex(ctx, func(schema FtCreateSchema) rueidis.Completed { + if err := repo.CreateIndex(ctx, func(schema FtCreateSchema) valkey.Completed { return schema.FieldName("$.F1").Tag().Build() }); err != nil { t.Fatal(err) @@ -39,13 +39,13 @@ func TestNewJsonRepositoryMismatch(t *testing.T) { if err := client.Do(ctx, client.B().Del().Key("jsonmismatch:"+e.Key).Build()).Error(); err != nil { t.Fatal(err) } - if err := client.Do(ctx, client.B().JsonSet().Key("jsonmismatch:"+e.Key).Path("$").Value(rueidis.JSON("1")).Build()).Error(); err != nil { + if err := client.Do(ctx, client.B().JsonSet().Key("jsonmismatch:"+e.Key).Path("$").Value(valkey.JSON("1")).Build()).Error(); err != nil { t.Fatal(err) } if _, err := repo.Fetch(ctx, e.Key); err == nil { t.Fatal("Fetch not failed as expected") } - if _, _, err := repo.Search(ctx, func(search FtSearchIndex) rueidis.Completed { + if _, _, err := repo.Search(ctx, func(search FtSearchIndex) valkey.Completed { return search.Query("*").Build() }); err == nil { t.Fatal("Search not failed as expected") @@ -121,14 +121,14 @@ func TestNewJSONRepository(t *testing.T) { }) t.Run("Search", func(t *testing.T) { - err := repo.CreateIndex(ctx, func(schema FtCreateSchema) rueidis.Completed { + err := repo.CreateIndex(ctx, func(schema FtCreateSchema) valkey.Completed { return schema.FieldName("$.Val").Text().Build() }) if err != nil { t.Fatal(err) } time.Sleep(time.Second) - n, records, err := repo.Search(ctx, func(search FtSearchIndex) rueidis.Completed { + n, records, err := repo.Search(ctx, func(search FtSearchIndex) valkey.Completed { return search.Query("*").Build() }) if err != nil { @@ -143,7 +143,7 @@ func TestNewJSONRepository(t *testing.T) { if !reflect.DeepEqual(e, records[0]) { t.Fatalf("items[0] should be the same as e") } - n, records, err = repo.Search(ctx, func(search FtSearchIndex) rueidis.Completed { + n, records, err = repo.Search(ctx, func(search FtSearchIndex) valkey.Completed { return search.Query("*").Dialect(3).Build() }) if err != nil { @@ -164,14 +164,14 @@ func TestNewJSONRepository(t *testing.T) { }) t.Run("Search Sort", func(t *testing.T) { - err := repo.CreateIndex(ctx, func(schema FtCreateSchema) rueidis.Completed { + err := repo.CreateIndex(ctx, func(schema FtCreateSchema) valkey.Completed { return schema.FieldName("$.Val").Text().Sortable().Build() }) if err != nil { t.Fatal(err) } time.Sleep(time.Second) - n, records, err := repo.Search(ctx, func(search FtSearchIndex) rueidis.Completed { + n, records, err := repo.Search(ctx, func(search FtSearchIndex) valkey.Completed { return search.Query("*").Sortby("$.Val").Build() }) if err != nil { @@ -246,9 +246,9 @@ func TestNewJSONRepository(t *testing.T) { } type JSONTestTTLStruct struct { - Key string `redis:",key"` - Ver int64 `redis:",ver"` - Exat time.Time `redis:",exat"` + Key string `valkey:",key"` + Ver int64 `valkey:",ver"` + Exat time.Time `valkey:",exat"` } //gocyclo:ignore diff --git a/om/repo.go b/om/repo.go index 99ef816..da0548f 100644 --- a/om/repo.go +++ b/om/repo.go @@ -5,8 +5,8 @@ import ( "errors" "time" - "github.com/redis/rueidis" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/internal/cmds" ) type ( @@ -29,7 +29,7 @@ var ( // IsRecordNotFound checks if the error is indicating the requested entity is not found. func IsRecordNotFound(err error) bool { - return rueidis.IsRedisNil(err) || err == ErrEmptyHashRecord + return valkey.IsValkeyNil(err) || err == ErrEmptyHashRecord } // Repository is backed by HashRepository or JSONRepository @@ -37,12 +37,12 @@ type Repository[T any] interface { NewEntity() (entity *T) Fetch(ctx context.Context, id string) (*T, error) FetchCache(ctx context.Context, id string, ttl time.Duration) (v *T, err error) - Search(ctx context.Context, cmdFn func(search FtSearchIndex) rueidis.Completed) (int64, []*T, error) - Aggregate(ctx context.Context, cmdFn func(agg FtAggregateIndex) rueidis.Completed) (*AggregateCursor, error) + Search(ctx context.Context, cmdFn func(search FtSearchIndex) valkey.Completed) (int64, []*T, error) + Aggregate(ctx context.Context, cmdFn func(agg FtAggregateIndex) valkey.Completed) (*AggregateCursor, error) Save(ctx context.Context, entity *T) (err error) SaveMulti(ctx context.Context, entity ...*T) (errs []error) Remove(ctx context.Context, id string) error - CreateIndex(ctx context.Context, cmdFn func(schema FtCreateSchema) rueidis.Completed) error + CreateIndex(ctx context.Context, cmdFn func(schema FtCreateSchema) valkey.Completed) error DropIndex(ctx context.Context) error IndexName() string } diff --git a/om/repo_test.go b/om/repo_test.go index 4eee4c5..f232908 100644 --- a/om/repo_test.go +++ b/om/repo_test.go @@ -3,11 +3,11 @@ package om import ( "testing" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) -func setup(t *testing.T) rueidis.Client { - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6377"}}) +func setup(t *testing.T) valkey.Client { + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6377"}}) if err != nil { t.Fatal(err) } @@ -15,8 +15,8 @@ func setup(t *testing.T) rueidis.Client { } type TestStruct struct { - Key string `redis:",key"` - Ver int64 `redis:",ver"` + Key string `valkey:",key"` + Ver int64 `valkey:",ver"` } func TestWithIndexName(t *testing.T) { diff --git a/om/schema.go b/om/schema.go index 0050782..8d52edb 100644 --- a/om/schema.go +++ b/om/schema.go @@ -46,29 +46,29 @@ func newSchema(t reflect.Type) schema { if f.isKey { if sf.Type.Kind() != reflect.String { - panic(fmt.Sprintf("field with tag `redis:\",key\"` in schema %q should be a string", t)) + panic(fmt.Sprintf("field with tag `valkey:\",key\"` in schema %q should be a string", t)) } s.key = &f } if f.isVer { if sf.Type.Kind() != reflect.Int64 { - panic(fmt.Sprintf("field with tag `redis:\",ver\"` in schema %q should be a int64", t)) + panic(fmt.Sprintf("field with tag `valkey:\",ver\"` in schema %q should be a int64", t)) } s.ver = &f } if f.isExt { if sf.Type != reflect.TypeOf(time.Time{}) { - panic(fmt.Sprintf("field with tag `redis:\",exat\"` in schema %q should be a time.Time", t)) + panic(fmt.Sprintf("field with tag `valkey:\",exat\"` in schema %q should be a time.Time", t)) } s.ext = &f } } if s.key == nil { - panic(fmt.Sprintf("schema %q should have one field with `redis:\",key\"` tag", t)) + panic(fmt.Sprintf("schema %q should have one field with `valkey:\",key\"` tag", t)) } if s.ver == nil { - panic(fmt.Sprintf("schema %q should have one field with `redis:\",ver\"` tag", t)) + panic(fmt.Sprintf("schema %q should have one field with `valkey:\",ver\"` tag", t)) } return s @@ -83,7 +83,7 @@ func parse(f reflect.StructField) (field field) { field.name = vs[0] } - v, _ = f.Tag.Lookup("redis") + v, _ = f.Tag.Lookup("valkey") field.isKey = strings.Contains(v, ",key") field.isVer = strings.Contains(v, ",ver") field.isExt = strings.Contains(v, ",exat") diff --git a/om/schema_test.go b/om/schema_test.go index d5ca419..8ef5016 100644 --- a/om/schema_test.go +++ b/om/schema_test.go @@ -7,29 +7,29 @@ import ( ) type s1 struct { - A int `redis:",key"` + A int `valkey:",key"` } type s2 struct { - A string `redis:",ver"` + A string `valkey:",ver"` } type s3 struct { - A string `json:"-" redis:",key"` - B int64 `redis:",ver"` + A string `json:"-" valkey:",key"` + B int64 `valkey:",ver"` private int64 } type s4 struct { - A string `redis:",key"` - B int64 `json:"-" redis:",ver"` + A string `valkey:",key"` + B int64 `json:"-" valkey:",ver"` private int64 } type s5 struct { - A string `redis:",key"` - B int64 `redis:",ver"` - C int64 `redis:",exat"` + A string `valkey:",key"` + B int64 `valkey:",ver"` + C int64 `valkey:",exat"` } func TestSchema(t *testing.T) { @@ -40,35 +40,35 @@ func TestSchema(t *testing.T) { t.Fatalf("unexpected msg %v", v) } }) - t.Run("non string `redis:\",key\"`", func(t *testing.T) { + t.Run("non string `valkey:\",key\"`", func(t *testing.T) { if v := recovered(func() { newSchema(reflect.TypeOf(s1{})) }); !strings.Contains(v, "should be a string") { t.Fatalf("unexpected msg %v", v) } }) - t.Run("non string `redis:\",ver\"`", func(t *testing.T) { + t.Run("non string `valkey:\",ver\"`", func(t *testing.T) { if v := recovered(func() { newSchema(reflect.TypeOf(s2{})) }); !strings.Contains(v, "should be a int64") { t.Fatalf("unexpected msg %v", v) } }) - t.Run("missing `redis:\",key\"`", func(t *testing.T) { + t.Run("missing `valkey:\",key\"`", func(t *testing.T) { if v := recovered(func() { newSchema(reflect.TypeOf(s3{})) - }); !strings.Contains(v, "should have one field with `redis:\",key\"` tag") { + }); !strings.Contains(v, "should have one field with `valkey:\",key\"` tag") { t.Fatalf("unexpected msg %v", v) } }) - t.Run("missing `redis:\",ver\"`", func(t *testing.T) { + t.Run("missing `valkey:\",ver\"`", func(t *testing.T) { if v := recovered(func() { newSchema(reflect.TypeOf(s4{})) - }); !strings.Contains(v, "should have one field with `redis:\",ver\"` tag") { + }); !strings.Contains(v, "should have one field with `valkey:\",ver\"` tag") { t.Fatalf("unexpected msg %v", v) } }) - t.Run("non time.Time `redis:\",exat\"`", func(t *testing.T) { + t.Run("non time.Time `valkey:\",exat\"`", func(t *testing.T) { if v := recovered(func() { newSchema(reflect.TypeOf(s5{})) }); !strings.Contains(v, "should be a time.Time") { diff --git a/pipe.go b/pipe.go index d3c1ec2..1a783a3 100644 --- a/pipe.go +++ b/pipe.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "bufio" @@ -16,24 +16,24 @@ import ( "sync/atomic" "time" - "github.com/redis/rueidis/internal/cmds" - "github.com/redis/rueidis/internal/util" + "github.com/rueian/valkey-go/internal/cmds" + "github.com/rueian/valkey-go/internal/util" ) -const LibName = "rueidis" +const LibName = "valkey" const LibVer = "1.0.34" var noHello = regexp.MustCompile("unknown command .?(HELLO|hello).?") type wire interface { - Do(ctx context.Context, cmd Completed) RedisResult - DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) RedisResult - DoMulti(ctx context.Context, multi ...Completed) *redisresults - DoMultiCache(ctx context.Context, multi ...CacheableTTL) *redisresults + Do(ctx context.Context, cmd Completed) ValkeyResult + DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) ValkeyResult + DoMulti(ctx context.Context, multi ...Completed) *valkeyresults + DoMultiCache(ctx context.Context, multi ...CacheableTTL) *valkeyresults Receive(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error - DoStream(ctx context.Context, pool *pool, cmd Completed) RedisResultStream - DoMultiStream(ctx context.Context, pool *pool, multi ...Completed) MultiRedisResultStream - Info() map[string]RedisMessage + DoStream(ctx context.Context, pool *pool, cmd Completed) ValkeyResultStream + DoMultiStream(ctx context.Context, pool *pool, multi ...Completed) MultiValkeyResultStream + Info() map[string]ValkeyMessage Version() int Error() error Close() @@ -43,23 +43,23 @@ type wire interface { SetOnCloseHook(fn func(error)) } -type redisresults struct { - s []RedisResult +type valkeyresults struct { + s []ValkeyResult } -func (r *redisresults) Capacity() int { +func (r *valkeyresults) Capacity() int { return cap(r.s) } -func (r *redisresults) ResetLen(n int) { +func (r *valkeyresults) ResetLen(n int) { r.s = r.s[:n] for i := 0; i < n; i++ { - r.s[i] = RedisResult{} + r.s[i] = ValkeyResult{} } } -var resultsp = util.NewPool(func(capacity int) *redisresults { - return &redisresults{s: make([]RedisResult, 0, capacity)} +var resultsp = util.NewPool(func(capacity int) *valkeyresults { + return &valkeyresults{s: make([]ValkeyResult, 0, capacity)} }) type cacheentries struct { @@ -93,13 +93,13 @@ type pipe struct { r *bufio.Reader w *bufio.Writer close chan struct{} - onInvalidations func([]RedisMessage) + onInvalidations func([]ValkeyMessage) r2psFn func() (p *pipe, err error) // func to build pipe for resp2 pubsub r2pipe *pipe // internal pipe for resp2 pubsub only ssubs *subs // pubsub smessage subscriptions nsubs *subs // pubsub message subscriptions psubs *subs // pubsub pmessage subscriptions - info map[string]RedisMessage + info map[string]ValkeyMessage timeout time.Duration pinggap time.Duration maxFlushDelay time.Duration @@ -236,7 +236,7 @@ func _newPipe(connFn func() (net.Conn, error), option *ClientOption, r2ps, nobg // ignore READONLY command error continue } - if re, ok := err.(*RedisError); ok { + if re, ok := err.(*ValkeyError); ok { if !r2 && noHello.MatchString(re.string) { r2 = true continue @@ -357,8 +357,8 @@ func (p *pipe) _background() { } var ( - resps []RedisResult - ch chan RedisResult + resps []ValkeyResult + ch chan ValkeyResult cond *sync.Cond ) @@ -398,7 +398,7 @@ func (p *pipe) _backgroundWrite() (err error) { var ( ones = make([]Completed, 1) multi []Completed - ch chan RedisResult + ch chan ValkeyResult flushDelay = p.maxFlushDelay flushStart = time.Time{} @@ -453,12 +453,12 @@ func (p *pipe) _backgroundWrite() (err error) { func (p *pipe) _backgroundRead() (err error) { var ( - msg RedisMessage + msg ValkeyMessage cond *sync.Cond ones = make([]Completed, 1) multi []Completed - resps []RedisResult - ch chan RedisResult + resps []ValkeyResult + ch chan ValkeyResult ff int // fulfilled count skip int // skip rest push messages ver = p.version @@ -494,8 +494,8 @@ func (p *pipe) _backgroundRead() (err error) { continue } } else if ver == 6 && len(msg.values) != 0 { - // This is a workaround for Redis 6's broken invalidation protocol: https://github.com/redis/redis/issues/8935 - // When Redis 6 handles MULTI, MGET, or other multi-keys command, + // This is a workaround for Valkey 6's broken invalidation protocol: https://github.com/redis/redis/issues/8935 + // When Valkey 6 handles MULTI, MGET, or other multi-keys command, // it will send invalidation message immediately if it finds the keys are expired, thus causing the multi-keys command response to be broken. // We fix this by fetching the next message and patch it back to the response. i := 0 @@ -520,7 +520,7 @@ func (p *pipe) _backgroundRead() (err error) { ones[0], multi, ch, resps, cond = p.queue.NextResultCh() // ch should not be nil, otherwise it must be a protocol bug if ch == nil { cond.L.Unlock() - // Redis will send sunsubscribe notification proactively in the event of slot migration. + // Valkey will send sunsubscribe notification proactively in the event of slot migration. // We should ignore them and go fetch next message. // We also treat all the other unsubscribe notifications just like sunsubscribe, // so that we don't need to track how many channels we have subscribed to deal with wildcard unsubscribe command @@ -559,7 +559,7 @@ func (p *pipe) _backgroundRead() (err error) { } } if prply { - // Redis will send sunsubscribe notification proactively in the event of slot migration. + // Valkey will send sunsubscribe notification proactively in the event of slot migration. // We should ignore them and go fetch next message. // We also treat all the other unsubscribe notifications just like sunsubscribe, // so that we don't need to track how many channels we have subscribed to deal with wildcard unsubscribe command @@ -574,7 +574,7 @@ func (p *pipe) _backgroundRead() (err error) { panic(protocolbug) } skip = len(multi[ff].Commands()) - 2 - msg = RedisMessage{} // override successful subscribe/unsubscribe response to empty + msg = ValkeyMessage{} // override successful subscribe/unsubscribe response to empty } else if multi[ff].NoReply() && msg.string == "QUEUED" { panic(multiexecsub) } @@ -605,7 +605,7 @@ func (p *pipe) backgroundPing() { } ch := make(chan error, 1) tm := time.NewTimer(p.timeout) - go func() { ch <- p.Do(context.Background(), cmds.PingCmd).NonRedisError() }() + go func() { ch <- p.Do(context.Background(), cmds.PingCmd).NonValkeyError() }() select { case <-tm.C: err = context.DeadlineExceeded @@ -624,7 +624,7 @@ func (p *pipe) backgroundPing() { } } -func (p *pipe) handlePush(values []RedisMessage) (reply bool, unsubscribe bool) { +func (p *pipe) handlePush(values []ValkeyMessage) (reply bool, unsubscribe bool) { if len(values) < 2 { return } @@ -805,7 +805,7 @@ func (p *pipe) SetOnCloseHook(fn func(error)) { p.clhks.Store(fn) } -func (p *pipe) Info() map[string]RedisMessage { +func (p *pipe) Info() map[string]ValkeyMessage { return p.info } @@ -813,7 +813,7 @@ func (p *pipe) Version() int { return int(p.version) } -func (p *pipe) Do(ctx context.Context, cmd Completed) (resp RedisResult) { +func (p *pipe) Do(ctx context.Context, cmd Completed) (resp ValkeyResult) { if err := ctx.Err(); err != nil { return newErrResult(err) } @@ -880,7 +880,7 @@ queue: atomic.AddInt32(&p.recvs, 1) return resp abort: - go func(ch chan RedisResult) { + go func(ch chan ValkeyResult) { <-ch atomic.AddInt32(&p.waits, -1) atomic.AddInt32(&p.recvs, 1) @@ -888,7 +888,7 @@ abort: return newErrResult(ctx.Err()) } -func (p *pipe) DoMulti(ctx context.Context, multi ...Completed) *redisresults { +func (p *pipe) DoMulti(ctx context.Context, multi ...Completed) *valkeyresults { resp := resultsp.Get(len(multi), len(multi)) if err := ctx.Err(); err != nil { for i := 0; i < len(resp.s); i++ { @@ -983,7 +983,7 @@ queue: atomic.AddInt32(&p.recvs, 1) return resp abort: - go func(resp *redisresults, ch chan RedisResult) { + go func(resp *valkeyresults, ch chan ValkeyResult) { <-ch resultsp.Put(resp) atomic.AddInt32(&p.waits, -1) @@ -997,9 +997,9 @@ abort: return resp } -type MultiRedisResultStream = RedisResultStream +type MultiValkeyResultStream = ValkeyResultStream -type RedisResultStream struct { +type ValkeyResultStream struct { p *pool w *pipe e error @@ -1007,20 +1007,20 @@ type RedisResultStream struct { } // HasNext can be used in a for loop condition to check if a further WriteTo call is needed. -func (s *RedisResultStream) HasNext() bool { +func (s *ValkeyResultStream) HasNext() bool { return s.n > 0 && s.e == nil } -// Error returns the error happened when sending commands to redis or reading response from redis. +// Error returns the error happened when sending commands to valkey or reading response from valkey. // Usually a user is not required to use this function because the error is also reported by the WriteTo. -func (s *RedisResultStream) Error() error { +func (s *ValkeyResultStream) Error() error { return s.e } -// WriteTo reads a redis response from redis and then write it to the given writer. +// WriteTo reads a valkey response from valkey and then write it to the given writer. // This function is not thread safe and should be called sequentially to read multiple responses. // An io.EOF error will be reported if all responses are read. -func (s *RedisResultStream) WriteTo(w io.Writer) (n int64, err error) { +func (s *ValkeyResultStream) WriteTo(w io.Writer) (n int64, err error) { if err = s.e; err == nil && s.n > 0 { var clean bool if n, err, clean = streamTo(s.w.r, w); !clean { @@ -1041,11 +1041,11 @@ func (s *RedisResultStream) WriteTo(w io.Writer) (n int64, err error) { return n, err } -func (p *pipe) DoStream(ctx context.Context, pool *pool, cmd Completed) RedisResultStream { +func (p *pipe) DoStream(ctx context.Context, pool *pool, cmd Completed) ValkeyResultStream { cmds.CompletedCS(cmd).Verify() if err := ctx.Err(); err != nil { - return RedisResultStream{e: err} + return ValkeyResultStream{e: err} } state := atomic.LoadInt32(&p.state) @@ -1080,22 +1080,22 @@ func (p *pipe) DoStream(ctx context.Context, pool *pool, cmd Completed) RedisRes p.conn.Close() p.background() // start the background worker to clean up goroutines } else { - return RedisResultStream{p: pool, w: p, n: 1} + return ValkeyResultStream{p: pool, w: p, n: 1} } } atomic.AddInt32(&p.blcksig, -1) atomic.AddInt32(&p.waits, -1) pool.Store(p) - return RedisResultStream{e: p.Error()} + return ValkeyResultStream{e: p.Error()} } -func (p *pipe) DoMultiStream(ctx context.Context, pool *pool, multi ...Completed) MultiRedisResultStream { +func (p *pipe) DoMultiStream(ctx context.Context, pool *pool, multi ...Completed) MultiValkeyResultStream { for _, cmd := range multi { cmds.CompletedCS(cmd).Verify() } if err := ctx.Err(); err != nil { - return RedisResultStream{e: err} + return ValkeyResultStream{e: err} } state := atomic.LoadInt32(&p.state) @@ -1139,16 +1139,16 @@ func (p *pipe) DoMultiStream(ctx context.Context, pool *pool, multi ...Completed p.conn.Close() p.background() // start the background worker to clean up goroutines } else { - return RedisResultStream{p: pool, w: p, n: len(multi)} + return ValkeyResultStream{p: pool, w: p, n: len(multi)} } } atomic.AddInt32(&p.blcksig, -1) atomic.AddInt32(&p.waits, -1) pool.Store(p) - return RedisResultStream{e: p.Error()} + return ValkeyResultStream{e: p.Error()} } -func (p *pipe) syncDo(dl time.Time, dlOk bool, cmd Completed) (resp RedisResult) { +func (p *pipe) syncDo(dl time.Time, dlOk bool, cmd Completed) (resp ValkeyResult) { if dlOk { if p.timeout > 0 { defaultDeadline := time.Now().Add(p.timeout) @@ -1163,7 +1163,7 @@ func (p *pipe) syncDo(dl time.Time, dlOk bool, cmd Completed) (resp RedisResult) p.conn.SetDeadline(time.Time{}) } - var msg RedisMessage + var msg ValkeyMessage err := writeCmd(p.w, cmd.Commands()) if err = p.w.Flush(); err == nil { msg, err = syncRead(p.r) @@ -1179,7 +1179,7 @@ func (p *pipe) syncDo(dl time.Time, dlOk bool, cmd Completed) (resp RedisResult) return newResult(msg, err) } -func (p *pipe) syncDoMulti(dl time.Time, dlOk bool, resp []RedisResult, multi []Completed) { +func (p *pipe) syncDoMulti(dl time.Time, dlOk bool, resp []ValkeyResult, multi []Completed) { if dlOk { if p.timeout > 0 { defaultDeadline := time.Now().Add(p.timeout) @@ -1201,7 +1201,7 @@ func (p *pipe) syncDoMulti(dl time.Time, dlOk bool, resp []RedisResult, multi [] } process: var err error - var msg RedisMessage + var msg ValkeyMessage for _, cmd := range multi { _ = writeCmd(p.w, cmd.Commands()) } @@ -1228,7 +1228,7 @@ abort: return } -func syncRead(r *bufio.Reader) (m RedisMessage, err error) { +func syncRead(r *bufio.Reader) (m ValkeyMessage, err error) { next: if m, err = readNextMessage(r); err != nil { return m, err @@ -1239,7 +1239,7 @@ next: return m, nil } -func (p *pipe) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) RedisResult { +func (p *pipe) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) ValkeyResult { if p.cache == nil { return p.Do(ctx, Completed(cmd)) } @@ -1267,7 +1267,7 @@ func (p *pipe) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) Re defer resultsp.Put(resp) exec, err := resp.s[4].ToArray() if err != nil { - if _, ok := err.(*RedisError); ok { + if _, ok := err.(*ValkeyError); ok { err = ErrDoCacheAborted } p.cache.Cancel(ck, cc, err) @@ -1276,11 +1276,11 @@ func (p *pipe) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) Re return newResult(exec[1], nil) } -func (p *pipe) doCacheMGet(ctx context.Context, cmd Cacheable, ttl time.Duration) RedisResult { +func (p *pipe) doCacheMGet(ctx context.Context, cmd Cacheable, ttl time.Duration) ValkeyResult { commands := cmd.Commands() keys := len(commands) - 1 builder := cmds.NewBuilder(cmds.InitSlot) - result := RedisResult{val: RedisMessage{typ: '*', values: nil}} + result := ValkeyResult{val: ValkeyMessage{typ: '*', values: nil}} mgetcc := cmds.MGetCacheCmd(cmd) if mgetcc[0] == 'J' { keys-- // the last one of JSON.MGET is a path, not a key @@ -1293,7 +1293,7 @@ func (p *pipe) doCacheMGet(ctx context.Context, cmd Cacheable, ttl time.Duration v, entry := p.cache.Flight(key, mgetcc, ttl, now) if v.typ != 0 { // cache hit for one key if len(result.val.values) == 0 { - result.val.values = make([]RedisMessage, keys) + result.val.values = make([]ValkeyMessage, keys) } result.val.values[i] = v continue @@ -1308,7 +1308,7 @@ func (p *pipe) doCacheMGet(ctx context.Context, cmd Cacheable, ttl time.Duration rewrite = rewrite.Args(key) } - var partial []RedisMessage + var partial []ValkeyMessage if !rewrite.IsZero() { var rewritten Completed var keys int @@ -1331,7 +1331,7 @@ func (p *pipe) doCacheMGet(ctx context.Context, cmd Cacheable, ttl time.Duration defer resultsp.Put(resp) exec, err := resp.s[len(multi)-1].ToArray() if err != nil { - if _, ok := err.(*RedisError); ok { + if _, ok := err.(*ValkeyError); ok { err = ErrDoCacheAborted } for _, key := range rewritten.Commands()[1 : keys+1] { @@ -1354,7 +1354,7 @@ func (p *pipe) doCacheMGet(ctx context.Context, cmd Cacheable, ttl time.Duration } if len(result.val.values) == 0 { - result.val.values = make([]RedisMessage, keys) + result.val.values = make([]ValkeyMessage, keys) } for i, entry := range entries.e { v, err := entry.Wait(ctx) @@ -1376,7 +1376,7 @@ func (p *pipe) doCacheMGet(ctx context.Context, cmd Cacheable, ttl time.Duration return result } -func (p *pipe) DoMultiCache(ctx context.Context, multi ...CacheableTTL) *redisresults { +func (p *pipe) DoMultiCache(ctx context.Context, multi ...CacheableTTL) *valkeyresults { if p.cache == nil { commands := make([]Completed, len(multi)) for i, ct := range multi { @@ -1420,13 +1420,13 @@ func (p *pipe) DoMultiCache(ctx context.Context, multi ...CacheableTTL) *redisre } } - var resp *redisresults + var resp *valkeyresults if len(missing) > 0 { resp = p.DoMulti(ctx, missing...) defer resultsp.Put(resp) for i := 4; i < len(resp.s); i += 5 { if err := resp.s[i].Error(); err != nil { - if _, ok := err.(*RedisError); ok { + if _, ok := err.(*ValkeyError); ok { err = ErrDoCacheAborted } ck, cc := cmds.CacheKey(Cacheable(missing[i-1])) @@ -1449,7 +1449,7 @@ func (p *pipe) DoMultiCache(ctx context.Context, multi ...CacheableTTL) *redisre if results.s[j].val.typ == 0 && results.s[j].err == nil { exec, err := resp.s[i].ToArray() if err != nil { - if _, ok := err.(*RedisError); ok { + if _, ok := err.(*ValkeyError); ok { err = ErrDoCacheAborted } results.s[j] = newErrResult(err) @@ -1534,7 +1534,7 @@ const ( panicmgetcsc = "MGET and JSON.MGET in DoMultiCache are not implemented, use DoCache instead" ) -var cacheMark = &(RedisMessage{}) +var cacheMark = &(ValkeyMessage{}) var errClosing = &errs{error: ErrClosing} type errs struct{ error } diff --git a/pipe_test.go b/pipe_test.go index 7008033..6189639 100644 --- a/pipe_test.go +++ b/pipe_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "bufio" @@ -16,84 +16,84 @@ import ( "testing" "time" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go/internal/cmds" ) -type redisExpect struct { - *redisMock +type valkeyExpect struct { + *valkeyMock err error } -type redisMock struct { +type valkeyMock struct { t *testing.T buf *bufio.Reader conn net.Conn } -func (r *redisMock) ReadMessage() (RedisMessage, error) { +func (r *valkeyMock) ReadMessage() (ValkeyMessage, error) { m, err := readNextMessage(r.buf) if err != nil { - return RedisMessage{}, err + return ValkeyMessage{}, err } return m, nil } -func (r *redisMock) Expect(expected ...string) *redisExpect { +func (r *valkeyMock) Expect(expected ...string) *valkeyExpect { if len(expected) == 0 { - return &redisExpect{redisMock: r} + return &valkeyExpect{valkeyMock: r} } m, err := r.ReadMessage() if err != nil { - return &redisExpect{redisMock: r, err: err} + return &valkeyExpect{valkeyMock: r, err: err} } if len(expected) != len(m.values) { - r.t.Fatalf("redismock receive unexpected command length: expected %v, got : %v", len(expected), m.values) + r.t.Fatalf("valkeymock receive unexpected command length: expected %v, got : %v", len(expected), m.values) } for i, expected := range expected { if m.values[i].string != expected { - r.t.Fatalf("redismock receive unexpected command: expected %v, got : %v", expected, m.values[i]) + r.t.Fatalf("valkeymock receive unexpected command: expected %v, got : %v", expected, m.values[i]) } } - return &redisExpect{redisMock: r} + return &valkeyExpect{valkeyMock: r} } -func (r *redisExpect) ReplyString(replies ...string) *redisExpect { +func (r *valkeyExpect) ReplyString(replies ...string) *valkeyExpect { for _, reply := range replies { if r.err == nil { - r.Reply(RedisMessage{typ: '+', string: reply}) + r.Reply(ValkeyMessage{typ: '+', string: reply}) } } return r } -func (r *redisExpect) ReplyBlobString(replies ...string) *redisExpect { +func (r *valkeyExpect) ReplyBlobString(replies ...string) *valkeyExpect { for _, reply := range replies { if r.err == nil { - r.Reply(RedisMessage{typ: '$', string: reply}) + r.Reply(ValkeyMessage{typ: '$', string: reply}) } } return r } -func (r *redisExpect) ReplyError(replies ...string) *redisExpect { +func (r *valkeyExpect) ReplyError(replies ...string) *valkeyExpect { for _, reply := range replies { if r.err == nil { - r.Reply(RedisMessage{typ: '-', string: reply}) + r.Reply(ValkeyMessage{typ: '-', string: reply}) } } return r } -func (r *redisExpect) ReplyInteger(replies ...int64) *redisExpect { +func (r *valkeyExpect) ReplyInteger(replies ...int64) *valkeyExpect { for _, reply := range replies { if r.err == nil { - r.Reply(RedisMessage{typ: ':', integer: reply}) + r.Reply(ValkeyMessage{typ: ':', integer: reply}) } } return r } -func (r *redisExpect) Reply(replies ...RedisMessage) *redisExpect { +func (r *valkeyExpect) Reply(replies ...ValkeyMessage) *valkeyExpect { for _, reply := range replies { if r.err == nil { r.err = write(r.conn, reply) @@ -102,11 +102,11 @@ func (r *redisExpect) Reply(replies ...RedisMessage) *redisExpect { return r } -func (r *redisMock) Close() { +func (r *valkeyMock) Close() { r.conn.Close() } -func write(o io.Writer, m RedisMessage) (err error) { +func write(o io.Writer, m ValkeyMessage) (err error) { _, err = o.Write([]byte{m.typ}) switch m.typ { case '$': @@ -134,21 +134,21 @@ func write(o io.Writer, m RedisMessage) (err error) { return err } -func setup(t *testing.T, option ClientOption) (*pipe, *redisMock, func(), func()) { +func setup(t *testing.T, option ClientOption) (*pipe, *valkeyMock, func(), func()) { if option.CacheSizeEachConn <= 0 { option.CacheSizeEachConn = DefaultCacheBytes } n1, n2 := net.Pipe() - mock := &redisMock{ + mock := &valkeyMock{ t: t, buf: bufio.NewReader(n2), conn: n2, } go func() { mock.Expect("HELLO", "3"). - Reply(RedisMessage{ + Reply(ValkeyMessage{ typ: '%', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "version"}, {typ: '+', string: "6.0.0"}, {typ: '+', string: "proto"}, @@ -188,7 +188,7 @@ func setup(t *testing.T, option ClientOption) (*pipe, *redisMock, func(), func() } } -func ExpectOK(t *testing.T, result RedisResult) { +func ExpectOK(t *testing.T, result ValkeyResult) { val, err := result.ToMessage() if err != nil { t.Errorf("unexpected error result: %v", err) @@ -202,12 +202,12 @@ func TestNewPipe(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) t.Run("Auth without Username", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "default", "pa", "SETNAME", "cn"). - Reply(RedisMessage{ + Reply(ValkeyMessage{ typ: '%', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "proto"}, {typ: ':', integer: 3}, }, @@ -244,7 +244,7 @@ func TestNewPipe(t *testing.T) { }) t.Run("AlwaysRESP2", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("AUTH", "pa"). ReplyString("OK") @@ -282,12 +282,12 @@ func TestNewPipe(t *testing.T) { }) t.Run("Auth with Username", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "ua", "pa", "SETNAME", "cn"). - Reply(RedisMessage{ + Reply(ValkeyMessage{ typ: '%', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "proto"}, {typ: ':', integer: 3}, }, @@ -318,12 +318,12 @@ func TestNewPipe(t *testing.T) { }) t.Run("Auth with Credentials Function", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "ua", "pa", "SETNAME", "cn"). - Reply(RedisMessage{ + Reply(ValkeyMessage{ typ: '%', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "proto"}, {typ: ':', integer: 3}, }, @@ -358,12 +358,12 @@ func TestNewPipe(t *testing.T) { }) t.Run("With ClientSideTrackingOptions", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3"). - Reply(RedisMessage{ + Reply(ValkeyMessage{ typ: '%', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "proto"}, {typ: ':', integer: 3}, }, @@ -389,12 +389,12 @@ func TestNewPipe(t *testing.T) { }) t.Run("Init with ReplicaOnly", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "ua", "pa", "SETNAME", "cn"). - Reply(RedisMessage{ + Reply(ValkeyMessage{ typ: '%', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "proto"}, {typ: ':', integer: 3}, }, @@ -428,12 +428,12 @@ func TestNewPipe(t *testing.T) { }) t.Run("Init with ReplicaOnly ignores READONLY Error", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "ua", "pa", "SETNAME", "cn"). - Reply(RedisMessage{ + Reply(ValkeyMessage{ typ: '%', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "proto"}, {typ: ':', integer: 3}, }, @@ -475,7 +475,7 @@ func TestNewPipe(t *testing.T) { }) t.Run("Auth Credentials Function Error", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("PING").ReplyString("OK") }() _, err := newPipe(func() (net.Conn, error) { return n1, nil }, &ClientOption{ SelectDB: 1, @@ -497,7 +497,7 @@ func TestNewRESP2Pipe(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) t.Run("Without DisableCache", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3"). ReplyError("ERR unknown command `HELLO`") @@ -518,7 +518,7 @@ func TestNewRESP2Pipe(t *testing.T) { }) t.Run("Without DisableCache 2", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3"). ReplyError("ERR unknown command `HELLO`") @@ -539,12 +539,12 @@ func TestNewRESP2Pipe(t *testing.T) { }) t.Run("With Hello Proto 2", func(t *testing.T) { // kvrocks version 2.2.0 n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: "server"}, - {typ: '+', string: "redis"}, + {typ: '+', string: "valkey"}, {typ: '+', string: "proto"}, {typ: ':', integer: 2}, }}) @@ -570,7 +570,7 @@ func TestNewRESP2Pipe(t *testing.T) { }) t.Run("Auth without Username", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "default", "pa", "SETNAME", "cn"). ReplyError("ERR unknown command `HELLO`") @@ -611,7 +611,7 @@ func TestNewRESP2Pipe(t *testing.T) { }) t.Run("Auth with Username", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "ua", "pa", "SETNAME", "cn"). ReplyError("ERR unknown command `HELLO`") @@ -653,7 +653,7 @@ func TestNewRESP2Pipe(t *testing.T) { }) t.Run("Init with ReplicaOnly", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "default", "pa", "SETNAME", "cn"). ReplyError("ERR unknown command `HELLO`") @@ -699,7 +699,7 @@ func TestNewRESP2Pipe(t *testing.T) { }) t.Run("Init with ReplicaOnly ignores READONLY error", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "default", "pa", "SETNAME", "cn"). ReplyError("ERR unknown command `HELLO`") @@ -745,7 +745,7 @@ func TestNewRESP2Pipe(t *testing.T) { }) t.Run("Network Error", func(t *testing.T) { n1, n2 := net.Pipe() - mock := &redisMock{buf: bufio.NewReader(n2), conn: n2, t: t} + mock := &valkeyMock{buf: bufio.NewReader(n2), conn: n2, t: t} go func() { mock.Expect("HELLO", "3", "AUTH", "ua", "pa", "SETNAME", "cn"). ReplyError("ERR unknown command `HELLO`") @@ -784,7 +784,7 @@ func TestIgnoreOutOfBandDataDuringSyncMode(t *testing.T) { p, mock, cancel, _ := setup(t, ClientOption{}) defer cancel() go func() { - mock.Expect("PING").Reply(RedisMessage{typ: '>', string: "This should be ignore"}).ReplyString("OK") + mock.Expect("PING").Reply(ValkeyMessage{typ: '>', string: "This should be ignore"}).ReplyString("OK") }() ExpectOK(t, p.Do(context.Background(), cmds.NewCompleted([]string{"PING"}))) } @@ -1113,7 +1113,7 @@ func TestNoReplyExceedRingSize(t *testing.T) { }() for i := 0; i < times; i++ { - mock.Expect("UNSUBSCRIBE").Reply(RedisMessage{typ: '>', values: []RedisMessage{ + mock.Expect("UNSUBSCRIBE").Reply(ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "unsubscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 0}, @@ -1159,7 +1159,7 @@ func TestResponseSequenceWithPushMessageInjected(t *testing.T) { for i := 0; i < times; i++ { m, _ := mock.ReadMessage() mock.Expect().ReplyString(m.values[1].string). - Reply(RedisMessage{typ: '>', values: []RedisMessage{{typ: '+', string: "should be ignore"}}}) + Reply(ValkeyMessage{typ: '>', values: []ValkeyMessage{{typ: '+', string: "should be ignore"}}}) } wg.Wait() } @@ -1179,15 +1179,15 @@ func TestClientSideCaching(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: ttl}, {typ: '+', string: resp}, }}) } - invalidateCSC := func(keys RedisMessage) { - mock.Expect().Reply(RedisMessage{ + invalidateCSC := func(keys ValkeyMessage) { + mock.Expect().Reply(ValkeyMessage{ typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, keys, }, @@ -1228,7 +1228,7 @@ func TestClientSideCaching(t *testing.T) { } // cache invalidation - invalidateCSC(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}) + invalidateCSC(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}) go func() { expectCSC(-1, "2") }() @@ -1241,7 +1241,7 @@ func TestClientSideCaching(t *testing.T) { } // cache flush invalidation - invalidateCSC(RedisMessage{typ: '_'}) + invalidateCSC(ValkeyMessage{typ: '_'}) go func() { expectCSC(-1, "3") }() @@ -1269,7 +1269,7 @@ func TestClientSideCachingExecAbort(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '_'}) + Reply(ValkeyMessage{typ: '_'}) }() v, err := p.DoCache(context.Background(), Cacheable(cmds.NewCompleted([]string{"GET", "a"})), 10*time.Second).ToMessage() @@ -1284,7 +1284,7 @@ func TestClientSideCachingExecAbort(t *testing.T) { } } -func TestClientSideCachingWithNonRedisError(t *testing.T) { +func TestClientSideCachingWithNonValkeyError(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) p, _, _, closeConn := setup(t, ClientOption{}) closeConn() @@ -1305,10 +1305,10 @@ func TestClientSideCachingMGet(t *testing.T) { p, mock, cancel, _ := setup(t, ClientOption{}) defer cancel() - invalidateCSC := func(keys RedisMessage) { - mock.Expect().Reply(RedisMessage{ + invalidateCSC := func(keys ValkeyMessage) { + mock.Expect().Reply(ValkeyMessage{ typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, keys, }, @@ -1329,11 +1329,11 @@ func TestClientSideCachingMGet(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 1000}, {typ: ':', integer: 2000}, {typ: ':', integer: 3000}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 1}, {typ: ':', integer: 2}, {typ: ':', integer: 3}, @@ -1379,7 +1379,7 @@ func TestClientSideCachingMGet(t *testing.T) { } // partial cache invalidation - invalidateCSC(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "a1"}, {typ: '+', string: "a3"}}}) + invalidateCSC(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "a1"}, {typ: '+', string: "a3"}}}) go func() { mock.Expect("CLIENT", "CACHING", "YES"). Expect("MULTI"). @@ -1392,10 +1392,10 @@ func TestClientSideCachingMGet(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 10000}, {typ: ':', integer: 30000}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 10}, {typ: ':', integer: 30}, }}, @@ -1438,10 +1438,10 @@ func TestClientSideCachingJSONMGet(t *testing.T) { p, mock, cancel, _ := setup(t, ClientOption{}) defer cancel() - invalidateCSC := func(keys RedisMessage) { - mock.Expect().Reply(RedisMessage{ + invalidateCSC := func(keys ValkeyMessage) { + mock.Expect().Reply(ValkeyMessage{ typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, keys, }, @@ -1462,11 +1462,11 @@ func TestClientSideCachingJSONMGet(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 1000}, {typ: ':', integer: 2000}, {typ: ':', integer: 3000}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 1}, {typ: ':', integer: 2}, {typ: ':', integer: 3}, @@ -1512,7 +1512,7 @@ func TestClientSideCachingJSONMGet(t *testing.T) { } // partial cache invalidation - invalidateCSC(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "a1"}, {typ: '+', string: "a3"}}}) + invalidateCSC(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "a1"}, {typ: '+', string: "a3"}}}) go func() { mock.Expect("CLIENT", "CACHING", "YES"). Expect("MULTI"). @@ -1525,10 +1525,10 @@ func TestClientSideCachingJSONMGet(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 10000}, {typ: ':', integer: 30000}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 10}, {typ: ':', integer: 30}, }}, @@ -1583,7 +1583,7 @@ func TestClientSideCachingExecAbortMGet(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '_'}) + Reply(ValkeyMessage{typ: '_'}) }() v, err := p.DoCache(context.Background(), Cacheable(cmds.NewMGetCompleted([]string{"MGET", "a1", "a2"})), 10*time.Second).ToMessage() @@ -1601,7 +1601,7 @@ func TestClientSideCachingExecAbortMGet(t *testing.T) { } } -func TestClientSideCachingWithNonRedisErrorMGet(t *testing.T) { +func TestClientSideCachingWithNonValkeyErrorMGet(t *testing.T) { p, _, _, closeConn := setup(t, ClientOption{}) closeConn() @@ -1627,7 +1627,7 @@ func TestClientSideCachingWithSideChannelMGet(t *testing.T) { p.cache.Flight("a1", "GET", 10*time.Second, time.Now()) go func() { time.Sleep(100 * time.Millisecond) - m := RedisMessage{typ: '+', string: "OK"} + m := ValkeyMessage{typ: '+', string: "OK"} m.setExpireAt(time.Now().Add(10 * time.Millisecond).UnixMilli()) p.cache.Update("a1", "GET", m) }() @@ -1673,10 +1673,10 @@ func TestClientSideCachingDoMultiCache(t *testing.T) { p, mock, cancel, _ := setup(t, option) defer cancel() - invalidateCSC := func(keys RedisMessage) { - mock.Expect().Reply(RedisMessage{ + invalidateCSC := func(keys ValkeyMessage) { + mock.Expect().Reply(ValkeyMessage{ typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, keys, }, @@ -1703,7 +1703,7 @@ func TestClientSideCachingDoMultiCache(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 1000}, {typ: ':', integer: 1}, }}). @@ -1711,7 +1711,7 @@ func TestClientSideCachingDoMultiCache(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 2000}, {typ: ':', integer: 2}, }}). @@ -1719,7 +1719,7 @@ func TestClientSideCachingDoMultiCache(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 3000}, {typ: ':', integer: 3}, }}) @@ -1766,7 +1766,7 @@ func TestClientSideCachingDoMultiCache(t *testing.T) { } // partial cache invalidation - invalidateCSC(RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "a1"}, {typ: '+', string: "a3"}}}) + invalidateCSC(ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "a1"}, {typ: '+', string: "a3"}}}) go func() { mock.Expect("CLIENT", "CACHING", "YES"). Expect("MULTI"). @@ -1782,7 +1782,7 @@ func TestClientSideCachingDoMultiCache(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 10000}, {typ: ':', integer: 10}, }}). @@ -1790,7 +1790,7 @@ func TestClientSideCachingDoMultiCache(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 30000}, {typ: ':', integer: 30}, }}) @@ -1840,7 +1840,7 @@ func TestClientSideCachingDoMultiCache(t *testing.T) { t.Run("Simple", func(t *testing.T) { testfn(t, ClientOption{ NewCacheStoreFn: func(option CacheStoreOption) CacheStore { - return NewSimpleCacheAdapter(&simple{store: map[string]RedisMessage{}}) + return NewSimpleCacheAdapter(&simple{store: map[string]ValkeyMessage{}}) }, }) }) @@ -1866,7 +1866,7 @@ func TestClientSideCachingExecAbortDoMultiCache(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 1000}, {typ: ':', integer: 1}, }}). @@ -1874,7 +1874,7 @@ func TestClientSideCachingExecAbortDoMultiCache(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '_'}) + Reply(ValkeyMessage{typ: '_'}) }() arr := p.DoMultiCache(context.Background(), []CacheableTTL{ @@ -1912,13 +1912,13 @@ func TestClientSideCachingExecAbortDoMultiCache(t *testing.T) { t.Run("Simple", func(t *testing.T) { testfn(t, ClientOption{ NewCacheStoreFn: func(option CacheStoreOption) CacheStore { - return NewSimpleCacheAdapter(&simple{store: map[string]RedisMessage{}}) + return NewSimpleCacheAdapter(&simple{store: map[string]ValkeyMessage{}}) }, }) }) } -func TestClientSideCachingWithNonRedisErrorDoMultiCache(t *testing.T) { +func TestClientSideCachingWithNonValkeyErrorDoMultiCache(t *testing.T) { testfn := func(t *testing.T, option ClientOption) { p, _, _, closeConn := setup(t, option) closeConn() @@ -1949,7 +1949,7 @@ func TestClientSideCachingWithNonRedisErrorDoMultiCache(t *testing.T) { t.Run("Simple", func(t *testing.T) { testfn(t, ClientOption{ NewCacheStoreFn: func(option CacheStoreOption) CacheStore { - return NewSimpleCacheAdapter(&simple{store: map[string]RedisMessage{}}) + return NewSimpleCacheAdapter(&simple{store: map[string]ValkeyMessage{}}) }, }) }) @@ -1963,7 +1963,7 @@ func TestClientSideCachingWithSideChannelDoMultiCache(t *testing.T) { p.cache.Flight("a1", "GET", 10*time.Second, time.Now()) go func() { time.Sleep(100 * time.Millisecond) - m := RedisMessage{typ: '+', string: "OK"} + m := ValkeyMessage{typ: '+', string: "OK"} m.setExpireAt(time.Now().Add(10 * time.Millisecond).UnixMilli()) p.cache.Update("a1", "GET", m) }() @@ -1981,7 +1981,7 @@ func TestClientSideCachingWithSideChannelDoMultiCache(t *testing.T) { t.Run("Simple", func(t *testing.T) { testfn(t, ClientOption{ NewCacheStoreFn: func(option CacheStoreOption) CacheStore { - return NewSimpleCacheAdapter(&simple{store: map[string]RedisMessage{}}) + return NewSimpleCacheAdapter(&simple{store: map[string]ValkeyMessage{}}) }, }) }) @@ -2010,7 +2010,7 @@ func TestClientSideCachingWithSideChannelErrorDoMultiCache(t *testing.T) { t.Run("Simple", func(t *testing.T) { testfn(t, ClientOption{ NewCacheStoreFn: func(option CacheStoreOption) CacheStore { - return NewSimpleCacheAdapter(&simple{store: map[string]RedisMessage{}}) + return NewSimpleCacheAdapter(&simple{store: map[string]ValkeyMessage{}}) }, }) }) @@ -2031,7 +2031,7 @@ func TestClientSideCachingMissCacheTTL(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: pttl}, {typ: '+', string: key}, }}) @@ -2071,11 +2071,11 @@ func TestClientSideCachingMissCacheTTL(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: -1}, {typ: ':', integer: 1000}, {typ: ':', integer: 20000}, - {typ: '*', values: []RedisMessage{ + {typ: '*', values: []ValkeyMessage{ {typ: '+', string: "a"}, {typ: '+', string: "b"}, {typ: '+', string: "c"}, @@ -2116,7 +2116,7 @@ func TestClientSideCachingMissCacheTTL(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: -1}, {typ: ':', integer: 1}, }}). @@ -2124,7 +2124,7 @@ func TestClientSideCachingMissCacheTTL(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 1000}, {typ: ':', integer: 2}, }}). @@ -2132,7 +2132,7 @@ func TestClientSideCachingMissCacheTTL(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: 20000}, {typ: ':', integer: 3}, }}) @@ -2159,14 +2159,14 @@ func TestClientSideCachingMissCacheTTL(t *testing.T) { t.Run("Simple", func(t *testing.T) { testfn(t, ClientOption{ NewCacheStoreFn: func(option CacheStoreOption) CacheStore { - return NewSimpleCacheAdapter(&simple{store: map[string]RedisMessage{}}) + return NewSimpleCacheAdapter(&simple{store: map[string]ValkeyMessage{}}) }, }) }) } // https://github.com/redis/redis/issues/8935 -func TestClientSideCachingRedis6InvalidationBug1(t *testing.T) { +func TestClientSideCachingValkey6InvalidationBug1(t *testing.T) { p, mock, cancel, _ := setup(t, ClientOption{}) defer cancel() @@ -2180,16 +2180,16 @@ func TestClientSideCachingRedis6InvalidationBug1(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ { typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, - {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}, + {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}, }, }, {typ: ':', integer: -2}, - }}).Reply(RedisMessage{typ: '_'}) + }}).Reply(ValkeyMessage{typ: '_'}) } go func() { @@ -2227,7 +2227,7 @@ func TestClientSideCachingRedis6InvalidationBug1(t *testing.T) { } // https://github.com/redis/redis/issues/8935 -func TestClientSideCachingRedis6InvalidationBug2(t *testing.T) { +func TestClientSideCachingValkey6InvalidationBug2(t *testing.T) { p, mock, cancel, _ := setup(t, ClientOption{}) defer cancel() @@ -2241,16 +2241,16 @@ func TestClientSideCachingRedis6InvalidationBug2(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: -2}, { typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, - {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}, + {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}, }, }, - }}).Reply(RedisMessage{typ: '_'}) + }}).Reply(ValkeyMessage{typ: '_'}) } go func() { @@ -2288,7 +2288,7 @@ func TestClientSideCachingRedis6InvalidationBug2(t *testing.T) { } // https://github.com/redis/redis/issues/8935 -func TestClientSideCachingRedis6InvalidationBugErr(t *testing.T) { +func TestClientSideCachingValkey6InvalidationBugErr(t *testing.T) { p, mock, _, closeConn := setup(t, ClientOption{}) expectCSC := func() { @@ -2301,13 +2301,13 @@ func TestClientSideCachingRedis6InvalidationBugErr(t *testing.T) { ReplyString("OK"). ReplyString("OK"). ReplyString("OK"). - Reply(RedisMessage{typ: '*', values: []RedisMessage{ + Reply(ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: ':', integer: -2}, { typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, - {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}, + {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}, }, }, }}) @@ -2330,11 +2330,11 @@ func TestDisableClientSideCaching(t *testing.T) { p.background() go func() { - mock.Expect().Reply(RedisMessage{ + mock.Expect().Reply(ValkeyMessage{ typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, - {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}, + {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}, }, }) mock.Expect("GET", "a").ReplyString("1"). @@ -2361,19 +2361,19 @@ func TestDisableClientSideCaching(t *testing.T) { } func TestOnInvalidations(t *testing.T) { - ch := make(chan []RedisMessage) + ch := make(chan []ValkeyMessage) _, mock, cancel, _ := setup(t, ClientOption{ - OnInvalidations: func(messages []RedisMessage) { + OnInvalidations: func(messages []ValkeyMessage) { ch <- messages }, }) go func() { - mock.Expect().Reply(RedisMessage{ + mock.Expect().Reply(ValkeyMessage{ typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, - {typ: '*', values: []RedisMessage{{typ: '+', string: "a"}}}, + {typ: '*', values: []ValkeyMessage{{typ: '+', string: "a"}}}, }, }) }() @@ -2383,9 +2383,9 @@ func TestOnInvalidations(t *testing.T) { } go func() { - mock.Expect().Reply(RedisMessage{ + mock.Expect().Reply(ValkeyMessage{ typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "invalidate"}, {typ: '_'}, }, @@ -2445,7 +2445,7 @@ func TestPubSub(t *testing.T) { go func() { for _, c := range commands { - mock.Expect(c.Commands()...).Reply(RedisMessage{typ: '>', values: []RedisMessage{ + mock.Expect(c.Commands()...).Reply(ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: strings.ToLower(c.Commands()[0])}, {typ: '+', string: strings.ToLower(c.Commands()[1])}, }}) @@ -2474,7 +2474,7 @@ func TestPubSub(t *testing.T) { go func() { for _, c := range commands { - mock.Expect(c.Commands()...).Reply(RedisMessage{typ: '>', values: []RedisMessage{ + mock.Expect(c.Commands()...).Reply(ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: strings.ToLower(c.Commands()[0])}, {typ: '+', string: strings.ToLower(c.Commands()[1])}, }}) @@ -2488,7 +2488,7 @@ func TestPubSub(t *testing.T) { } }) - t.Run("PubSub Subscribe RedisMessage", func(t *testing.T) { + t.Run("PubSub Subscribe ValkeyMessage", func(t *testing.T) { ctx := context.Background() p, mock, cancel, _ := setup(t, ClientOption{}) @@ -2496,19 +2496,19 @@ func TestPubSub(t *testing.T) { deactivate := builder.Unsubscribe().Channel("1").Build() go func() { mock.Expect(activate.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "subscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "message"}, {typ: '+', string: "1"}, {typ: '+', string: "2"}, }}, ) mock.Expect(deactivate.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "unsubscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 0}, @@ -2529,7 +2529,7 @@ func TestPubSub(t *testing.T) { cancel() }) - t.Run("PubSub SSubscribe RedisMessage", func(t *testing.T) { + t.Run("PubSub SSubscribe ValkeyMessage", func(t *testing.T) { ctx := context.Background() p, mock, cancel, _ := setup(t, ClientOption{}) @@ -2537,19 +2537,19 @@ func TestPubSub(t *testing.T) { deactivate := builder.Sunsubscribe().Channel("1").Build() go func() { mock.Expect(activate.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "ssubscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "smessage"}, {typ: '+', string: "1"}, {typ: '+', string: "2"}, }}, ) mock.Expect(deactivate.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "sunsubscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 0}, @@ -2570,7 +2570,7 @@ func TestPubSub(t *testing.T) { cancel() }) - t.Run("PubSub PSubscribe RedisMessage", func(t *testing.T) { + t.Run("PubSub PSubscribe ValkeyMessage", func(t *testing.T) { ctx := context.Background() p, mock, cancel, _ := setup(t, ClientOption{}) @@ -2578,12 +2578,12 @@ func TestPubSub(t *testing.T) { deactivate := builder.Punsubscribe().Pattern("1").Build() go func() { mock.Expect(activate.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "psubscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "pmessage"}, {typ: '+', string: "1"}, {typ: '+', string: "2"}, @@ -2591,7 +2591,7 @@ func TestPubSub(t *testing.T) { }}, ) mock.Expect(deactivate.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "punsubscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 0}, @@ -2612,7 +2612,7 @@ func TestPubSub(t *testing.T) { cancel() }) - t.Run("PubSub Wrong Command RedisMessage", func(t *testing.T) { + t.Run("PubSub Wrong Command ValkeyMessage", func(t *testing.T) { p, _, cancel, _ := setup(t, ClientOption{}) defer cancel() @@ -2642,12 +2642,12 @@ func TestPubSub(t *testing.T) { activate := builder.Subscribe().Channel("1").Build() go func() { mock.Expect(activate.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "subscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "message"}, {typ: '+', string: "1"}, {typ: '+', string: "2"}, @@ -2666,7 +2666,7 @@ func TestPubSub(t *testing.T) { cancel() }) - t.Run("PubSub Subscribe Redis Error", func(t *testing.T) { + t.Run("PubSub Subscribe Valkey Error", func(t *testing.T) { ctx := context.Background() p, mock, cancel, _ := setup(t, ClientOption{}) @@ -2680,7 +2680,7 @@ func TestPubSub(t *testing.T) { } go func() { for _, cmd := range commands { - mock.Expect(cmd.Commands()...).Reply(RedisMessage{typ: '-', string: cmd.Commands()[0]}) + mock.Expect(cmd.Commands()...).Reply(ValkeyMessage{typ: '-', string: cmd.Commands()[0]}) } }() for _, cmd := range commands { @@ -2709,17 +2709,17 @@ func TestPubSub(t *testing.T) { cmd2 := builder.Get().Key(strconv.Itoa(i)).Build() go func() { mock.Expect(cmd1.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "subscribe"}, {typ: '+', string: "a"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ // skip + ValkeyMessage{typ: '>', values: []ValkeyMessage{ // skip {typ: '+', string: "subscribe"}, {typ: '+', string: "b"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ // skip + ValkeyMessage{typ: '>', values: []ValkeyMessage{ // skip {typ: '+', string: "subscribe"}, {typ: '+', string: "c"}, {typ: ':', integer: 1}, @@ -2747,10 +2747,10 @@ func TestPubSub(t *testing.T) { builder.Sunsubscribe().Build(), } - replies := [][]RedisMessage{{ + replies := [][]ValkeyMessage{{ { typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "unsubscribe"}, {typ: '_'}, {typ: ':', integer: 0}, @@ -2759,7 +2759,7 @@ func TestPubSub(t *testing.T) { }, { { typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "punsubscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 0}, @@ -2768,7 +2768,7 @@ func TestPubSub(t *testing.T) { }, { { typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "sunsubscribe"}, {typ: '+', string: "2"}, {typ: ':', integer: 0}, @@ -2776,7 +2776,7 @@ func TestPubSub(t *testing.T) { }, { typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "sunsubscribe"}, {typ: '+', string: "3"}, {typ: ':', integer: 0}, @@ -2816,11 +2816,11 @@ func TestPubSub(t *testing.T) { builder.Ssubscribe().Channel("3").Build(), } - replies := [][]RedisMessage{ + replies := [][]ValkeyMessage{ { { // proactive unsubscribe before user unsubscribe typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: command}, {typ: '+', string: "1"}, {typ: ':', integer: 0}, @@ -2828,7 +2828,7 @@ func TestPubSub(t *testing.T) { }, { // proactive unsubscribe before user unsubscribe typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: command}, {typ: '+', string: "2"}, {typ: ':', integer: 0}, @@ -2836,7 +2836,7 @@ func TestPubSub(t *testing.T) { }, { // user unsubscribe typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: command}, {typ: '_'}, {typ: ':', integer: 0}, @@ -2844,7 +2844,7 @@ func TestPubSub(t *testing.T) { }, { // proactive unsubscribe after user unsubscribe typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: command}, {typ: '_'}, {typ: ':', integer: 0}, @@ -2854,7 +2854,7 @@ func TestPubSub(t *testing.T) { { { // user ssubscribe typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "ssubscribe"}, {typ: '+', string: "3"}, {typ: ':', integer: 0}, @@ -2862,7 +2862,7 @@ func TestPubSub(t *testing.T) { }, { // proactive unsubscribe after user ssubscribe typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: command}, {typ: '+', string: "3"}, {typ: ':', integer: 0}, @@ -2874,9 +2874,9 @@ func TestPubSub(t *testing.T) { p.background() // proactive unsubscribe before other commands - mock.Expect().Reply(RedisMessage{ // proactive unsubscribe before user unsubscribe + mock.Expect().Reply(ValkeyMessage{ // proactive unsubscribe before user unsubscribe typ: '>', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: command}, {typ: '+', string: "0"}, {typ: ':', integer: 0}, @@ -2911,8 +2911,8 @@ func TestPubSub(t *testing.T) { p.queue.PutOne(builder.Get().Key("a").Build()) p.queue.NextWriteCmd() go func() { - mock.Expect().Reply(RedisMessage{ - typ: '>', values: []RedisMessage{ + mock.Expect().Reply(ValkeyMessage{ + typ: '>', values: []ValkeyMessage{ {typ: '+', string: push}, {typ: '+', string: ""}, }, @@ -2941,7 +2941,7 @@ func TestPubSub(t *testing.T) { p.queue.PutOne(cmd) p.queue.NextWriteCmd() go func() { - mock.Expect().Reply(RedisMessage{typ: '+', string: "QUEUED"}) + mock.Expect().Reply(ValkeyMessage{typ: '+', string: "QUEUED"}) }() p._backgroundRead() return @@ -3074,22 +3074,22 @@ func TestPubSubHooks(t *testing.T) { deactivate2 := builder.Punsubscribe().Pattern("2").Build() go func() { mock.Expect(activate1.Commands()...).Expect(activate2.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "subscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "psubscribe"}, {typ: '+', string: "2"}, {typ: ':', integer: 2}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "message"}, {typ: '+', string: "1"}, {typ: '+', string: "11"}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "pmessage"}, {typ: '+', string: "2"}, {typ: '+', string: "22"}, @@ -3097,12 +3097,12 @@ func TestPubSubHooks(t *testing.T) { }}, ) mock.Expect(deactivate1.Commands()...).Expect(deactivate2.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "unsubscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "punsubscribe"}, {typ: '+', string: "2"}, {typ: ':', integer: 2}, @@ -3161,22 +3161,22 @@ func TestPubSubHooks(t *testing.T) { deactivate2 := builder.Punsubscribe().Pattern("2").Build() go func() { mock.Expect(activate1.Commands()...).Expect(activate2.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "subscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "psubscribe"}, {typ: '+', string: "2"}, {typ: ':', integer: 2}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "message"}, {typ: '+', string: "1"}, {typ: '+', string: "11"}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "pmessage"}, {typ: '+', string: "2"}, {typ: '+', string: "22"}, @@ -3184,12 +3184,12 @@ func TestPubSubHooks(t *testing.T) { }}, ) mock.Expect(deactivate1.Commands()...).Expect(deactivate2.Commands()...).Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "unsubscribe"}, {typ: '+', string: "1"}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "punsubscribe"}, {typ: '+', string: "2"}, {typ: ':', integer: 2}, @@ -3226,7 +3226,7 @@ func TestExitOnWriteError(t *testing.T) { closeConn() for i := 0; i < 2; i++ { - if err := p.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := p.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Errorf("unexpected cached result, expected io err, got %v", err) } } @@ -3245,7 +3245,7 @@ func TestExitOnPubSubSubscribeWriteError(t *testing.T) { go func() { defer wg.Done() atomic.AddInt64(&count, 1) - if err := p.Do(context.Background(), activate).NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := p.Do(context.Background(), activate).NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Errorf("unexpected result, expected io err, got %v", err) } }() @@ -3263,7 +3263,7 @@ func TestExitOnWriteMultiError(t *testing.T) { closeConn() for i := 0; i < 2; i++ { - if err := p.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := p.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Errorf("unexpected result, expected io err, got %v", err) } } @@ -3337,10 +3337,10 @@ func TestExitAllGoroutineOnWriteError(t *testing.T) { for i := 0; i < times; i++ { go func() { defer wg.Done() - if err := conn.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := conn.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Errorf("unexpected result, expected io err, got %v", err) } - if err := conn.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := conn.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Errorf("unexpected result, expected io err, got %v", err) } }() @@ -3357,7 +3357,7 @@ func TestExitOnReadError(t *testing.T) { }() for i := 0; i < 2; i++ { - if err := p.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := p.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Errorf("unexpected result, expected io err, got %v", err) } } @@ -3372,7 +3372,7 @@ func TestExitOnReadMultiError(t *testing.T) { }() for i := 0; i < 2; i++ { - if err := p.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := p.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Errorf("unexpected result, expected io err, got %v", err) } } @@ -3392,10 +3392,10 @@ func TestExitAllGoroutineOnReadError(t *testing.T) { for i := 0; i < times; i++ { go func() { defer wg.Done() - if err := p.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := p.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Errorf("unexpected result, expected io err, got %v", err) } - if err := p.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := p.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Errorf("unexpected result, expected io err, got %v", err) } }() @@ -3441,10 +3441,10 @@ func TestAlreadyCanceledContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); !errors.Is(err, context.Canceled) { + if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); !errors.Is(err, context.Canceled) { t.Fatalf("unexpected err %v", err) } - if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); !errors.Is(err, context.Canceled) { + if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); !errors.Is(err, context.Canceled) { t.Fatalf("unexpected err %v", err) } @@ -3459,10 +3459,10 @@ func TestAlreadyCanceledContext(t *testing.T) { ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-1*time.Second)) cancel() - if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("unexpected err %v", err) } - if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("unexpected err %v", err) } close() @@ -3479,7 +3479,7 @@ func TestCancelContext_Do(t *testing.T) { mock.Expect().ReplyString("OK") }() - if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); !errors.Is(err, context.Canceled) { + if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); !errors.Is(err, context.Canceled) { t.Fatalf("unexpected err %v", err) } shutdown() @@ -3534,7 +3534,7 @@ func TestCancelContext_Do_Block(t *testing.T) { mock.Expect().ReplyString("OK") }() - if err := p.Do(ctx, cmds.NewBlockingCompleted([]string{"GET", "a"})).NonRedisError(); !errors.Is(err, context.Canceled) { + if err := p.Do(ctx, cmds.NewBlockingCompleted([]string{"GET", "a"})).NonValkeyError(); !errors.Is(err, context.Canceled) { t.Fatalf("unexpected err %v", err) } shutdown() @@ -3551,7 +3551,7 @@ func TestCancelContext_DoMulti(t *testing.T) { mock.Expect().ReplyString("OK") }() - if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); !errors.Is(err, context.Canceled) { + if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); !errors.Is(err, context.Canceled) { t.Fatalf("unexpected err %v", err) } shutdown() @@ -3568,7 +3568,7 @@ func TestCancelContext_DoMulti_Block(t *testing.T) { mock.Expect().ReplyString("OK") }() - if err := p.DoMulti(ctx, cmds.NewBlockingCompleted([]string{"GET", "a"})).s[0].NonRedisError(); !errors.Is(err, context.Canceled) { + if err := p.DoMulti(ctx, cmds.NewBlockingCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); !errors.Is(err, context.Canceled) { t.Fatalf("unexpected err %v", err) } shutdown() @@ -3620,7 +3620,7 @@ func TestForceClose_Do_Block(t *testing.T) { p.Close() }() - if err := p.Do(context.Background(), cmds.NewBlockingCompleted([]string{"GET", "a"})).NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := p.Do(context.Background(), cmds.NewBlockingCompleted([]string{"GET", "a"})).NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Fatalf("unexpected err %v", err) } } @@ -3681,7 +3681,7 @@ func TestForceClose_Do_Canceled_Block(t *testing.T) { mock.Expect().ReplyString("OK") }() - if err := p.Do(ctx, cmds.NewBlockingCompleted([]string{"GET", "a"})).NonRedisError(); !errors.Is(err, context.Canceled) { + if err := p.Do(ctx, cmds.NewBlockingCompleted([]string{"GET", "a"})).NonValkeyError(); !errors.Is(err, context.Canceled) { t.Fatalf("unexpected err %v", err) } p.Close() @@ -3695,7 +3695,7 @@ func TestForceClose_DoMulti_Block(t *testing.T) { p.Close() }() - if err := p.DoMulti(context.Background(), cmds.NewBlockingCompleted([]string{"GET", "a"})).s[0].NonRedisError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { + if err := p.DoMulti(context.Background(), cmds.NewBlockingCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); err != io.EOF && !strings.HasPrefix(err.Error(), "io:") { t.Fatalf("unexpected err %v", err) } } @@ -3756,7 +3756,7 @@ func TestForceClose_DoMulti_Canceled_Block(t *testing.T) { mock.Expect().ReplyString("OK") }() - if err := p.DoMulti(ctx, cmds.NewBlockingCompleted([]string{"GET", "a"})).s[0].NonRedisError(); !errors.Is(err, context.Canceled) { + if err := p.DoMulti(ctx, cmds.NewBlockingCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); !errors.Is(err, context.Canceled) { t.Fatalf("unexpected err %v", err) } p.Close() @@ -3773,7 +3773,7 @@ func TestSyncModeSwitchingWithDeadlineExceed_Do(t *testing.T) { for i := 0; i < 10; i++ { wg.Add(1) go func() { - if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Errorf("unexpected err %v", err) } wg.Done() @@ -3798,7 +3798,7 @@ func TestSyncModeSwitchingWithDeadlineExceed_DoMulti(t *testing.T) { for i := 0; i < 10; i++ { wg.Add(1) go func() { - if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Errorf("unexpected err %v", err) } wg.Done() @@ -3819,7 +3819,7 @@ func TestOngoingDeadlineContextInSyncMode_Do(t *testing.T) { ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(1*time.Second/2)) defer cancel() - if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("unexpected err %v", err) } p.Close() @@ -3829,7 +3829,7 @@ func TestWriteDeadlineInSyncMode_Do(t *testing.T) { p, _, _, closeConn := setup(t, ClientOption{ConnWriteTimeout: 1 * time.Second / 2, Dialer: net.Dialer{KeepAlive: time.Second / 3}}) defer closeConn() - if err := p.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.Do(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("unexpected err %v", err) } p.Close() @@ -3843,7 +3843,7 @@ func TestWriteDeadlineIsShorterThanContextDeadlineInSyncMode_Do(t *testing.T) { defer cancel() startTime := time.Now() - if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.Do(ctx, cmds.NewCompleted([]string{"GET", "a"})).NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("unexpected err %v", err) } @@ -3861,7 +3861,7 @@ func TestOngoingDeadlineContextInSyncMode_DoMulti(t *testing.T) { ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(1*time.Second/2)) defer cancel() - if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("unexpected err %v", err) } p.Close() @@ -3871,7 +3871,7 @@ func TestWriteDeadlineInSyncMode_DoMulti(t *testing.T) { p, _, _, closeConn := setup(t, ClientOption{ConnWriteTimeout: time.Second / 2, Dialer: net.Dialer{KeepAlive: time.Second / 3}}) defer closeConn() - if err := p.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.DoMulti(context.Background(), cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("unexpected err %v", err) } p.Close() @@ -3885,7 +3885,7 @@ func TestWriteDeadlineIsShorterThanContextDeadlineInSyncMode_DoMulti(t *testing. defer cancel() startTime := time.Now() - if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonRedisError(); !errors.Is(err, context.DeadlineExceeded) { + if err := p.DoMulti(ctx, cmds.NewCompleted([]string{"GET", "a"})).s[0].NonValkeyError(); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("unexpected err %v", err) } @@ -4048,12 +4048,12 @@ func TestPipe_CleanSubscriptions_6(t *testing.T) { p.CleanSubscriptions() }() mock.Expect("UNSUBSCRIBE").Expect("PUNSUBSCRIBE").Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "unsubscribe"}, {typ: '_'}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "punsubscribe"}, {typ: '_'}, {typ: ':', integer: 2}, @@ -4069,17 +4069,17 @@ func TestPipe_CleanSubscriptions_7(t *testing.T) { p.CleanSubscriptions() }() mock.Expect("UNSUBSCRIBE").Expect("PUNSUBSCRIBE").Expect("SUNSUBSCRIBE").Reply( - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "unsubscribe"}, {typ: '_'}, {typ: ':', integer: 1}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "punsubscribe"}, {typ: '_'}, {typ: ':', integer: 2}, }}, - RedisMessage{typ: '>', values: []RedisMessage{ + ValkeyMessage{typ: '>', values: []ValkeyMessage{ {typ: '+', string: "sunsubscribe"}, {typ: '_'}, {typ: ':', integer: 2}, diff --git a/pool.go b/pool.go index d45ede8..efb681b 100644 --- a/pool.go +++ b/pool.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import "sync" diff --git a/pool_test.go b/pool_test.go index 14a2b03..778939c 100644 --- a/pool_test.go +++ b/pool_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "errors" diff --git a/pubsub.go b/pubsub.go index 72eb3c3..451c51c 100644 --- a/pubsub.go +++ b/pubsub.go @@ -1,11 +1,11 @@ -package rueidis +package valkey import ( "sync" "sync/atomic" ) -// PubSubMessage represent a pubsub message from redis +// PubSubMessage represent a pubsub message from valkey type PubSubMessage struct { // Pattern is only available with pmessage. Pattern string diff --git a/pubsub_test.go b/pubsub_test.go index ac6d2c4..0f836ea 100644 --- a/pubsub_test.go +++ b/pubsub_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "testing" diff --git a/resp.go b/resp.go index c2f3ef0..fbe1fe8 100644 --- a/resp.go +++ b/resp.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "bufio" @@ -11,7 +11,7 @@ import ( "sync" ) -var errChunked = errors.New("unbounded redis message") +var errChunked = errors.New("unbounded valkey message") var errOldNull = errors.New("RESP2 null") const ( @@ -36,7 +36,7 @@ const ( var typeNames = make(map[byte]string, 16) -type reader func(i *bufio.Reader) (RedisMessage, error) +type reader func(i *bufio.Reader) (ValkeyMessage, error) var readers = [256]reader{} @@ -76,47 +76,47 @@ func init() { typeNames[typeEnd] = "null" } -func readSimpleString(i *bufio.Reader) (m RedisMessage, err error) { +func readSimpleString(i *bufio.Reader) (m ValkeyMessage, err error) { m.string, err = readS(i) return } -func readBlobString(i *bufio.Reader) (m RedisMessage, err error) { +func readBlobString(i *bufio.Reader) (m ValkeyMessage, err error) { m.string, err = readB(i) if err == errChunked { sb := strings.Builder{} for { if _, err = i.Discard(1); err != nil { // discard the ';' - return RedisMessage{}, err + return ValkeyMessage{}, err } length, err := readI(i) if err != nil { - return RedisMessage{}, err + return ValkeyMessage{}, err } if length == 0 { - return RedisMessage{string: sb.String()}, nil + return ValkeyMessage{string: sb.String()}, nil } sb.Grow(int(length)) if _, err = io.CopyN(&sb, i, length); err != nil { - return RedisMessage{}, err + return ValkeyMessage{}, err } if _, err = i.Discard(2); err != nil { - return RedisMessage{}, err + return ValkeyMessage{}, err } } } return } -func readInteger(i *bufio.Reader) (m RedisMessage, err error) { +func readInteger(i *bufio.Reader) (m ValkeyMessage, err error) { m.integer, err = readI(i) return } -func readBoolean(i *bufio.Reader) (m RedisMessage, err error) { +func readBoolean(i *bufio.Reader) (m ValkeyMessage, err error) { b, err := i.ReadByte() if err != nil { - return RedisMessage{}, err + return ValkeyMessage{}, err } if b == 't' { m.integer = 1 @@ -125,12 +125,12 @@ func readBoolean(i *bufio.Reader) (m RedisMessage, err error) { return } -func readNull(i *bufio.Reader) (m RedisMessage, err error) { +func readNull(i *bufio.Reader) (m ValkeyMessage, err error) { _, err = i.Discard(2) return } -func readArray(i *bufio.Reader) (m RedisMessage, err error) { +func readArray(i *bufio.Reader) (m ValkeyMessage, err error) { length, err := readI(i) if err == nil { if length == -1 { @@ -143,7 +143,7 @@ func readArray(i *bufio.Reader) (m RedisMessage, err error) { return m, err } -func readMap(i *bufio.Reader) (m RedisMessage, err error) { +func readMap(i *bufio.Reader) (m ValkeyMessage, err error) { length, err := readI(i) if err == nil { m.values, err = readA(i, length*2) @@ -219,8 +219,8 @@ func readB(i *bufio.Reader) (string, error) { return BinaryString(bs), nil } -func readE(i *bufio.Reader) ([]RedisMessage, error) { - v := make([]RedisMessage, 0) +func readE(i *bufio.Reader) ([]ValkeyMessage, error) { + v := make([]ValkeyMessage, 0) for { n, err := readNextMessage(i) if err != nil { @@ -233,8 +233,8 @@ func readE(i *bufio.Reader) ([]RedisMessage, error) { } } -func readA(i *bufio.Reader, length int64) (v []RedisMessage, err error) { - v = make([]RedisMessage, length) +func readA(i *bufio.Reader, length int64) (v []ValkeyMessage, err error) { + v = make([]ValkeyMessage, length) for n := int64(0); n < length; n++ { if v[n], err = readNextMessage(i); err != nil { return nil, err @@ -271,28 +271,28 @@ func writeN(o *bufio.Writer, id byte, n int) (err error) { return err } -func readNextMessage(i *bufio.Reader) (m RedisMessage, err error) { - var attrs *RedisMessage +func readNextMessage(i *bufio.Reader) (m ValkeyMessage, err error) { + var attrs *ValkeyMessage var typ byte for { if typ, err = i.ReadByte(); err != nil { - return RedisMessage{}, err + return ValkeyMessage{}, err } fn := readers[typ] if fn == nil { - return RedisMessage{}, errors.New(unknownMessageType + strconv.Itoa(int(typ))) + return ValkeyMessage{}, errors.New(unknownMessageType + strconv.Itoa(int(typ))) } if m, err = fn(i); err != nil { if err == errOldNull { - return RedisMessage{typ: typeNull}, nil + return ValkeyMessage{typ: typeNull}, nil } - return RedisMessage{}, err + return ValkeyMessage{}, err } m.typ = typ if m.typ == typeAttribute { // handle the attributes a := m // clone the original m first, and then take address of the clone attrs = &a // to avoid go compiler allocating the m on heap which causing worse performance. - m = RedisMessage{} + m = ValkeyMessage{} continue } m.attrs = attrs @@ -353,14 +353,14 @@ next: return 0, Nil, true case typeSimpleErr, typeBlobErr: mm := m - return 0, (*RedisError)(&mm), true + return 0, (*ValkeyError)(&mm), true case typeInteger, typeBool: n, err := w.Write([]byte(strconv.FormatInt(m.integer, 10))) return int64(n), err, true case typePush: goto next default: - return 0, fmt.Errorf("unsupported redis %q response for streaming read", typeNames[typ]), true + return 0, fmt.Errorf("unsupported valkey %q response for streaming read", typeNames[typ]), true } } } diff --git a/resp_test.go b/resp_test.go index d151b92..994555f 100644 --- a/resp_test.go +++ b/resp_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "bufio" @@ -477,9 +477,9 @@ func TestReadAttr(t *testing.T) { if m.values[1].integer != 9543892 { t.Fatalf("unexpected msg values[0] %v", m.values[1]) } - if !reflect.DeepEqual(*m.attrs, RedisMessage{typ: '|', values: []RedisMessage{ + if !reflect.DeepEqual(*m.attrs, ValkeyMessage{typ: '|', values: []ValkeyMessage{ {typ: '+', string: "key-popularity"}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '$', string: "a"}, {typ: ',', string: "0.1923"}, {typ: '$', string: "b"}, @@ -521,7 +521,7 @@ func TestReadRESP3NullStream(t *testing.T) { t.Fatalf("unexpected no error: %v", i) } } else { - if m, ok := err.(*RedisError); !ok { + if m, ok := err.(*ValkeyError); !ok { t.Fatal(err) } else if m.typ != '_' { t.Fatalf("unexpected msg type %v", m.typ) @@ -546,7 +546,7 @@ func TestReadRESP2NullStringStream(t *testing.T) { t.Fatalf("unexpected no error: %v", i) } } else { - if m, ok := err.(*RedisError); !ok { + if m, ok := err.(*ValkeyError); !ok { t.Fatal(err) } else if m.typ != '_' { t.Fatalf("unexpected msg type %v", m.typ) @@ -573,9 +573,9 @@ func TestReadRESP2NullStringInArray(t *testing.T) { if err != nil { t.Fatal(err) } - if !reflect.DeepEqual(m, RedisMessage{ + if !reflect.DeepEqual(m, ValkeyMessage{ typ: '*', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '$', string: "hello"}, {typ: '_'}, {typ: '$', string: "world"}, @@ -638,7 +638,7 @@ func TWriterAndReader(t *testing.T, writer func(*bufio.Writer, byte, string) err } func TestRand(t *testing.T) { - read := func(in *bufio.Reader) (m RedisMessage, err error) { + read := func(in *bufio.Reader) (m ValkeyMessage, err error) { m, err = readNextMessage(in) return } @@ -646,7 +646,7 @@ func TestRand(t *testing.T) { if _, err := read(bufio.NewReader(strings.NewReader(random(false)))); err != nil { if err != io.EOF && err.Error() != "panic as expected" && - err.Error() != "unbounded redis message" && + err.Error() != "unbounded valkey message" && !strings.HasPrefix(err.Error(), unexpectedNoCRLF) && !strings.HasPrefix(err.Error(), unexpectedNumByte) && !strings.HasPrefix(err.Error(), unknownMessageType) { @@ -659,7 +659,7 @@ func TestRand(t *testing.T) { func TestChunkedStringRand(t *testing.T) { chunkedPrefix := "$?\n;" - read := func(in *bufio.Reader) (m RedisMessage, err error) { + read := func(in *bufio.Reader) (m ValkeyMessage, err error) { m, err = readNextMessage(in) return } diff --git a/ring.go b/ring.go index 197d0a5..18c9037 100644 --- a/ring.go +++ b/ring.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "sync" @@ -8,11 +8,11 @@ import ( ) type queue interface { - PutOne(m Completed) chan RedisResult - PutMulti(m []Completed, resps []RedisResult) chan RedisResult - NextWriteCmd() (Completed, []Completed, chan RedisResult) - WaitForWrite() (Completed, []Completed, chan RedisResult) - NextResultCh() (Completed, []Completed, chan RedisResult, []RedisResult, *sync.Cond) + PutOne(m Completed) chan ValkeyResult + PutMulti(m []Completed, resps []ValkeyResult) chan ValkeyResult + NextWriteCmd() (Completed, []Completed, chan ValkeyResult) + WaitForWrite() (Completed, []Completed, chan ValkeyResult) + NextResultCh() (Completed, []Completed, chan ValkeyResult, []ValkeyResult, *sync.Cond) } var _ queue = (*ring)(nil) @@ -27,7 +27,7 @@ func newRing(factor int) *ring { m := &sync.Mutex{} r.store[i].c1 = sync.NewCond(m) r.store[i].c2 = sync.NewCond(m) - r.store[i].ch = make(chan RedisResult, 0) // this channel can't be buffered + r.store[i].ch = make(chan ValkeyResult, 0) // this channel can't be buffered } return r } @@ -45,15 +45,15 @@ type ring struct { type node struct { c1 *sync.Cond c2 *sync.Cond - ch chan RedisResult + ch chan ValkeyResult one Completed multi []Completed - resps []RedisResult + resps []ValkeyResult mark uint32 slept bool } -func (r *ring) PutOne(m Completed) chan RedisResult { +func (r *ring) PutOne(m Completed) chan ValkeyResult { n := &r.store[atomic.AddUint32(&r.write, 1)&r.mask] n.c1.L.Lock() for n.mark != 0 { @@ -69,7 +69,7 @@ func (r *ring) PutOne(m Completed) chan RedisResult { return n.ch } -func (r *ring) PutMulti(m []Completed, resps []RedisResult) chan RedisResult { +func (r *ring) PutMulti(m []Completed, resps []ValkeyResult) chan ValkeyResult { n := &r.store[atomic.AddUint32(&r.write, 1)&r.mask] n.c1.L.Lock() for n.mark != 0 { @@ -87,7 +87,7 @@ func (r *ring) PutMulti(m []Completed, resps []RedisResult) chan RedisResult { } // NextWriteCmd should be only called by one dedicated thread -func (r *ring) NextWriteCmd() (one Completed, multi []Completed, ch chan RedisResult) { +func (r *ring) NextWriteCmd() (one Completed, multi []Completed, ch chan ValkeyResult) { r.read1++ p := r.read1 & r.mask n := &r.store[p] @@ -103,7 +103,7 @@ func (r *ring) NextWriteCmd() (one Completed, multi []Completed, ch chan RedisRe } // WaitForWrite should be only called by one dedicated thread -func (r *ring) WaitForWrite() (one Completed, multi []Completed, ch chan RedisResult) { +func (r *ring) WaitForWrite() (one Completed, multi []Completed, ch chan ValkeyResult) { r.read1++ p := r.read1 & r.mask n := &r.store[p] @@ -120,7 +120,7 @@ func (r *ring) WaitForWrite() (one Completed, multi []Completed, ch chan RedisRe } // NextResultCh should be only called by one dedicated thread -func (r *ring) NextResultCh() (one Completed, multi []Completed, ch chan RedisResult, resps []RedisResult, cond *sync.Cond) { +func (r *ring) NextResultCh() (one Completed, multi []Completed, ch chan ValkeyResult, resps []ValkeyResult, cond *sync.Cond) { r.read2++ p := r.read2 & r.mask n := &r.store[p] diff --git a/ring_test.go b/ring_test.go index 0ae273a..13f33c7 100644 --- a/ring_test.go +++ b/ring_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "runtime" @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go/internal/cmds" ) //gocyclo:ignore diff --git a/rueidisaside/go.mod b/rueidisaside/go.mod deleted file mode 100644 index edf2b57..0000000 --- a/rueidisaside/go.mod +++ /dev/null @@ -1,12 +0,0 @@ -module github.com/redis/rueidis/rueidisaside - -go 1.20 - -replace github.com/redis/rueidis => ../ - -require ( - github.com/oklog/ulid/v2 v2.1.0 - github.com/redis/rueidis v1.0.34 -) - -require golang.org/x/sys v0.17.0 // indirect diff --git a/rueidiscompat/README.md b/rueidiscompat/README.md deleted file mode 100644 index f71ee3e..0000000 --- a/rueidiscompat/README.md +++ /dev/null @@ -1,41 +0,0 @@ -## Go-redis like API Adapter - -Though it is easier to know what command will be sent to redis at first glance if the command is constructed by the command builder, -users may sometimes feel it too verbose to write. - -For users who don't like the command builder, `rueidiscompat.Adapter`, contributed mainly by [@418Coffee](https://github.com/418Coffee), is an alternative. -It is a high level API which is close to go-redis's `Cmdable` interface. - -### Migrating from go-redis - -You can also try adapting `rueidis` with existing go-redis code by replacing go-redis's `UniversalClient` with `rueidiscompat.Adapter`. - -### Client side caching - -To use client side caching with `rueidiscompat.Adapter`, chain `Cache(ttl)` call in front of supported command. - -```golang -package main - -import ( - "context" - "time" - "github.com/redis/rueidis" - "github.com/redis/rueidis/rueidiscompat" -) - -func main() { - ctx := context.Background() - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) - if err != nil { - panic(err) - } - defer client.Close() - - compat := rueidiscompat.NewAdapter(client) - ok, _ := compat.SetNX(ctx, "key", "val", time.Second).Result() - - // with client side caching - res, _ := compat.Cache(time.Second).Get(ctx, "key").Result() -} -``` \ No newline at end of file diff --git a/rueidishook/README.md b/rueidishook/README.md deleted file mode 100644 index be002d3..0000000 --- a/rueidishook/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# rueidishook - -With `rueidishook.WithHook`, users can easily intercept `rueidis.Client` by implementing custom `rueidishook.Hook` handler. - -This can be useful to change the behavior of `rueidis.Client` or add other integrations such as observability, APM etc. - -## Example - -```go -package main - -import ( - "context" - "time" - - "github.com/redis/rueidis" - "github.com/redis/rueidis/rueidishook" -) - -type hook struct{} - -func (h *hook) Do(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) { - // do whatever you want before client.Do - resp = client.Do(ctx, cmd) - // do whatever you want after client.Do - return -} - -func (h *hook) DoMulti(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) (resps []rueidis.RedisResult) { - // do whatever you want before client.DoMulti - resps = client.DoMulti(ctx, multi...) - // do whatever you want after client.DoMulti - return -} - -func (h *hook) DoCache(client rueidis.Client, ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) (resp rueidis.RedisResult) { - // do whatever you want before client.DoCache - resp = client.DoCache(ctx, cmd, ttl) - // do whatever you want after client.DoCache - return -} - -func (h *hook) DoMultiCache(client rueidis.Client, ctx context.Context, multi ...rueidis.CacheableTTL) (resps []rueidis.RedisResult) { - // do whatever you want before client.DoMultiCache - resps = client.DoMultiCache(ctx, multi...) - // do whatever you want after client.DoMultiCache - return -} - -func (h *hook) Receive(client rueidis.Client, ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) { - // do whatever you want before client.Receive - err = client.Receive(ctx, subscribe, fn) - // do whatever you want after client.Receive - return -} - -func main() { - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) - if err != nil { - panic(err) - } - client = rueidishook.WithHook(client, &hook{}) - defer client.Close() -} -``` diff --git a/rueidishook/go.mod b/rueidishook/go.mod deleted file mode 100644 index 7aee55d..0000000 --- a/rueidishook/go.mod +++ /dev/null @@ -1,16 +0,0 @@ -module github.com/redis/rueidis/rueidishook - -go 1.20 - -replace ( - github.com/redis/rueidis => ../ - github.com/redis/rueidis/mock => ../mock -) - -require ( - github.com/redis/rueidis v1.0.34 - github.com/redis/rueidis/mock v1.0.34 - go.uber.org/mock v0.4.0 -) - -require golang.org/x/sys v0.17.0 // indirect diff --git a/rueidishook/hook.go b/rueidishook/hook.go deleted file mode 100644 index 6cc32ef..0000000 --- a/rueidishook/hook.go +++ /dev/null @@ -1,173 +0,0 @@ -package rueidishook - -import ( - "context" - "time" - "unsafe" - - "github.com/redis/rueidis" -) - -var _ rueidis.Client = (*hookclient)(nil) - -// Hook allows user to intercept rueidis.Client by using WithHook -type Hook interface { - Do(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) - DoMulti(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) (resps []rueidis.RedisResult) - DoCache(client rueidis.Client, ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) (resp rueidis.RedisResult) - DoMultiCache(client rueidis.Client, ctx context.Context, multi ...rueidis.CacheableTTL) (resps []rueidis.RedisResult) - Receive(client rueidis.Client, ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) - DoStream(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) rueidis.RedisResultStream - DoMultiStream(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) rueidis.MultiRedisResultStream -} - -// WithHook wraps rueidis.Client with Hook and allows user to intercept rueidis.Client -func WithHook(client rueidis.Client, hook Hook) rueidis.Client { - return &hookclient{client: client, hook: hook} -} - -type hookclient struct { - client rueidis.Client - hook Hook -} - -func (c *hookclient) B() rueidis.Builder { - return c.client.B() -} - -func (c *hookclient) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) { - return c.hook.Do(c.client, ctx, cmd) -} - -func (c *hookclient) DoMulti(ctx context.Context, multi ...rueidis.Completed) (resp []rueidis.RedisResult) { - return c.hook.DoMulti(c.client, ctx, multi...) -} - -func (c *hookclient) DoCache(ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) (resp rueidis.RedisResult) { - return c.hook.DoCache(c.client, ctx, cmd, ttl) -} - -func (c *hookclient) DoMultiCache(ctx context.Context, multi ...rueidis.CacheableTTL) (resps []rueidis.RedisResult) { - return c.hook.DoMultiCache(c.client, ctx, multi...) -} - -func (c *hookclient) DoStream(ctx context.Context, cmd rueidis.Completed) rueidis.RedisResultStream { - return c.hook.DoStream(c.client, ctx, cmd) -} - -func (c *hookclient) DoMultiStream(ctx context.Context, multi ...rueidis.Completed) rueidis.MultiRedisResultStream { - return c.hook.DoMultiStream(c.client, ctx, multi...) -} - -func (c *hookclient) Dedicated(fn func(rueidis.DedicatedClient) error) (err error) { - return c.client.Dedicated(func(client rueidis.DedicatedClient) error { - return fn(&dedicated{client: &extended{DedicatedClient: client}, hook: c.hook}) - }) -} - -func (c *hookclient) Dedicate() (rueidis.DedicatedClient, func()) { - client, cancel := c.client.Dedicate() - return &dedicated{client: &extended{DedicatedClient: client}, hook: c.hook}, cancel -} - -func (c *hookclient) Receive(ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) { - return c.hook.Receive(c.client, ctx, subscribe, fn) -} - -func (c *hookclient) Nodes() map[string]rueidis.Client { - nodes := c.client.Nodes() - for addr, client := range nodes { - nodes[addr] = &hookclient{client: client, hook: c.hook} - } - return nodes -} - -func (c *hookclient) Close() { - c.client.Close() -} - -var _ rueidis.DedicatedClient = (*dedicated)(nil) - -type dedicated struct { - client *extended - hook Hook -} - -func (d *dedicated) B() rueidis.Builder { - return d.client.B() -} - -func (d *dedicated) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) { - return d.hook.Do(d.client, ctx, cmd) -} - -func (d *dedicated) DoMulti(ctx context.Context, multi ...rueidis.Completed) (resp []rueidis.RedisResult) { - return d.hook.DoMulti(d.client, ctx, multi...) -} - -func (d *dedicated) Receive(ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) { - return d.hook.Receive(d.client, ctx, subscribe, fn) -} - -func (d *dedicated) SetPubSubHooks(hooks rueidis.PubSubHooks) <-chan error { - return d.client.SetPubSubHooks(hooks) -} - -func (d *dedicated) Close() { - d.client.Close() -} - -var _ rueidis.Client = (*extended)(nil) - -type extended struct { - rueidis.DedicatedClient -} - -func (e *extended) DoCache(ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) (resp rueidis.RedisResult) { - panic("DoCache() is not allowed with rueidis.DedicatedClient") -} - -func (e *extended) DoMultiCache(ctx context.Context, multi ...rueidis.CacheableTTL) (resp []rueidis.RedisResult) { - panic("DoMultiCache() is not allowed with rueidis.DedicatedClient") -} -func (c *extended) DoStream(ctx context.Context, cmd rueidis.Completed) rueidis.RedisResultStream { - panic("DoStream() is not allowed with rueidis.DedicatedClient") -} - -func (c *extended) DoMultiStream(ctx context.Context, multi ...rueidis.Completed) rueidis.MultiRedisResultStream { - panic("DoMultiStream() is not allowed with rueidis.DedicatedClient") -} - -func (e *extended) Dedicated(fn func(rueidis.DedicatedClient) error) (err error) { - panic("Dedicated() is not allowed with rueidis.DedicatedClient") -} - -func (e *extended) Dedicate() (client rueidis.DedicatedClient, cancel func()) { - panic("Dedicate() is not allowed with rueidis.DedicatedClient") -} - -func (e *extended) Nodes() map[string]rueidis.Client { - panic("Nodes() is not allowed with rueidis.DedicatedClient") -} - -type result struct { - err error - val rueidis.RedisMessage -} - -func NewErrorResult(err error) rueidis.RedisResult { - r := result{err: err} - return *(*rueidis.RedisResult)(unsafe.Pointer(&r)) -} - -type stream struct { - p *int - w *int - e error - n int -} - -func NewErrorResultStream(err error) rueidis.RedisResultStream { - r := stream{e: err} - return *(*rueidis.RedisResultStream)(unsafe.Pointer(&r)) -} diff --git a/rueidisotel/README.md b/rueidisotel/README.md deleted file mode 100644 index 3f5713f..0000000 --- a/rueidisotel/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# OpenTelemetry Tracing & Connection Metrics - -Use `rueidisotel.NewClient` to create a client with OpenTelemetry Tracing and Connection Metrics enabled. -Builtin connection metrics are: -- `rueidis_dial_attempt`: number of dial attempts -- `rueidis_dial_success`: number of successful dials -- `rueidis_dial_conns`: number of connections -- `rueidis_dial_latency`: dial latency in seconds - -Client side caching metrics: -- `rueidis_do_cache_miss`: number of cache miss on client side -- `rueidis_do_cache_hits`: number of cache hits on client side - -```golang -package main - -import ( - "github.com/redis/rueidis" - "github.com/redis/rueidis/rueidisotel" -) - -func main() { - client, err := rueidisotel.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) - if err != nil { - panic(err) - } - defer client.Close() -} -``` - -See [rueidishook](../rueidishook) if you want more customizations. - -Note: `rueidisotel.NewClient` is not supported on go1.18 and go1.19 builds. [Reference](https://github.com/redis/rueidis/issues/442#issuecomment-1886993707) \ No newline at end of file diff --git a/rueidisprob/go.mod b/rueidisprob/go.mod deleted file mode 100644 index d3b0297..0000000 --- a/rueidisprob/go.mod +++ /dev/null @@ -1,12 +0,0 @@ -module github.com/redis/rueidis/rueidisprob - -go 1.20.0 - -replace github.com/redis/rueidis => ../ - -require ( - github.com/redis/rueidis v1.0.34 - github.com/twmb/murmur3 v1.1.8 -) - -require golang.org/x/sys v0.17.0 // indirect diff --git a/sentinel.go b/sentinel.go index ba87e48..8a4dd90 100644 --- a/sentinel.go +++ b/sentinel.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "container/list" @@ -14,7 +14,7 @@ import ( "math/rand" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go/internal/cmds" ) func newSentinelClient(opt *ClientOption, connFn connFn) (client *sentinelClient, err error) { @@ -61,19 +61,19 @@ func (c *sentinelClient) B() Builder { return c.cmd } -func (c *sentinelClient) Do(ctx context.Context, cmd Completed) (resp RedisResult) { +func (c *sentinelClient) Do(ctx context.Context, cmd Completed) (resp ValkeyResult) { retry: resp = c.mConn.Load().(conn).Do(ctx, cmd) - if c.retry && cmd.IsReadOnly() && c.isRetryable(resp.NonRedisError(), ctx) { + if c.retry && cmd.IsReadOnly() && c.isRetryable(resp.NonValkeyError(), ctx) { goto retry } - if resp.NonRedisError() == nil { // not recycle cmds if error, since cmds may be used later in pipe. consider recycle them by pipe + if resp.NonValkeyError() == nil { // not recycle cmds if error, since cmds may be used later in pipe. consider recycle them by pipe cmds.PutCompleted(cmd) } return resp } -func (c *sentinelClient) DoMulti(ctx context.Context, multi ...Completed) []RedisResult { +func (c *sentinelClient) DoMulti(ctx context.Context, multi ...Completed) []ValkeyResult { if len(multi) == 0 { return nil } @@ -81,33 +81,33 @@ retry: resps := c.mConn.Load().(conn).DoMulti(ctx, multi...) if c.retry && allReadOnly(multi) { for _, resp := range resps.s { - if c.isRetryable(resp.NonRedisError(), ctx) { + if c.isRetryable(resp.NonValkeyError(), ctx) { resultsp.Put(resps) goto retry } } } for i, cmd := range multi { - if resps.s[i].NonRedisError() == nil { + if resps.s[i].NonValkeyError() == nil { cmds.PutCompleted(cmd) } } return resps.s } -func (c *sentinelClient) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp RedisResult) { +func (c *sentinelClient) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp ValkeyResult) { retry: resp = c.mConn.Load().(conn).DoCache(ctx, cmd, ttl) - if c.retry && c.isRetryable(resp.NonRedisError(), ctx) { + if c.retry && c.isRetryable(resp.NonValkeyError(), ctx) { goto retry } - if err := resp.NonRedisError(); err == nil || err == ErrDoCacheAborted { + if err := resp.NonValkeyError(); err == nil || err == ErrDoCacheAborted { cmds.PutCacheable(cmd) } return resp } -func (c *sentinelClient) DoMultiCache(ctx context.Context, multi ...CacheableTTL) []RedisResult { +func (c *sentinelClient) DoMultiCache(ctx context.Context, multi ...CacheableTTL) []ValkeyResult { if len(multi) == 0 { return nil } @@ -115,14 +115,14 @@ retry: resps := c.mConn.Load().(conn).DoMultiCache(ctx, multi...) if c.retry { for _, resp := range resps.s { - if c.isRetryable(resp.NonRedisError(), ctx) { + if c.isRetryable(resp.NonValkeyError(), ctx) { resultsp.Put(resps) goto retry } } } for i, cmd := range multi { - if err := resps.s[i].NonRedisError(); err == nil || err == ErrDoCacheAborted { + if err := resps.s[i].NonValkeyError(); err == nil || err == ErrDoCacheAborted { cmds.PutCacheable(cmd.Cmd) } } @@ -133,7 +133,7 @@ func (c *sentinelClient) Receive(ctx context.Context, subscribe Completed, fn fu retry: err = c.mConn.Load().(conn).Receive(ctx, subscribe, fn) if c.retry { - if _, ok := err.(*RedisError); !ok && c.isRetryable(err, ctx) { + if _, ok := err.(*ValkeyError); !ok && c.isRetryable(err, ctx) { goto retry } } @@ -143,15 +143,15 @@ retry: return err } -func (c *sentinelClient) DoStream(ctx context.Context, cmd Completed) RedisResultStream { +func (c *sentinelClient) DoStream(ctx context.Context, cmd Completed) ValkeyResultStream { resp := c.mConn.Load().(conn).DoStream(ctx, cmd) cmds.PutCompleted(cmd) return resp } -func (c *sentinelClient) DoMultiStream(ctx context.Context, multi ...Completed) MultiRedisResultStream { +func (c *sentinelClient) DoMultiStream(ctx context.Context, multi ...Completed) MultiValkeyResultStream { if len(multi) == 0 { - return RedisResultStream{e: io.EOF} + return ValkeyResultStream{e: io.EOF} } s := c.mConn.Load().(conn).DoMultiStream(ctx, multi...) for _, cmd := range multi { @@ -413,7 +413,7 @@ func (c *sentinelClient) listWatch(cc conn) (target string, sentinels []string, return net.JoinHostPort(m[0], m[1]), sentinels, nil } -func pickReplica(resp []RedisResult) (string, error) { +func pickReplica(resp []ValkeyResult) (string, error) { replicas, err := resp[1].ToArray() if err != nil { return "", err @@ -452,6 +452,6 @@ func newSentinelOpt(opt *ClientOption) *ClientOption { } var ( - errNotMaster = errors.New("the redis role is not master") - errNotSlave = errors.New("the redis role is not slave") + errNotMaster = errors.New("the valkey role is not master") + errNotSlave = errors.New("the valkey role is not slave") ) diff --git a/sentinel_test.go b/sentinel_test.go index 01fb9e7..0d5a7a7 100644 --- a/sentinel_test.go +++ b/sentinel_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" @@ -9,7 +9,7 @@ import ( "testing" "time" - "github.com/redis/rueidis/internal/cmds" + "github.com/rueian/valkey-go/internal/cmds" ) //gocyclo:ignore @@ -34,7 +34,7 @@ func TestSentinelClientInit(t *testing.T) { v := errors.New("refresh err") if _, err := newSentinelClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { return &mockConn{ - DoMultiFn: func(cmd ...Completed) *redisresults { return &redisresults{s: []RedisResult{newErrResult(v)}} }, + DoMultiFn: func(cmd ...Completed) *valkeyresults { return &valkeyresults{s: []ValkeyResult{newErrResult(v)}} }, } }); err != v { t.Fatalf("unexpected err %v", err) @@ -44,20 +44,20 @@ func TestSentinelClientInit(t *testing.T) { t.Run("Refresh retry", func(t *testing.T) { v := errors.New("refresh err") s0 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ newErrResult(v), newErrResult(v), }} }, } s1 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "0"}, }}, @@ -67,48 +67,48 @@ func TestSentinelClientInit(t *testing.T) { }, } s2 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "3"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "5"}, }}}, }} }, } s3 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "4"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "6"}, }}}, }} }, } s4 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "2"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "7"}, }}}, }} @@ -137,15 +137,15 @@ func TestSentinelClientInit(t *testing.T) { } if dst == ":6" { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "slave"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "slave"}}}} }, } } if dst == ":7" { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} }, } } @@ -166,20 +166,20 @@ func TestSentinelClientInit(t *testing.T) { t.Run("Refresh retry replica-only client", func(t *testing.T) { v := errors.New("refresh err") slaveWithMultiError := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ newErrResult(v), newErrResult(v), }} }, } slaveWithReplicaResponseErr := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "0"}, }}, @@ -189,17 +189,17 @@ func TestSentinelClientInit(t *testing.T) { }, } sentinelWithFaultiSlave := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "3"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "6"}, }}, @@ -211,29 +211,29 @@ func TestSentinelClientInit(t *testing.T) { // since the next 2 connections won't update sentinel list, // we update the list here. sentinelWithHealthySlaveInSDown := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "4"}, }}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "32"}, }}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "31"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "6"}, }}, - {typ: '%', values: []RedisMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "8"}, {typ: '+', string: "s-down-time"}, {typ: '+', string: "1"}, @@ -243,17 +243,17 @@ func TestSentinelClientInit(t *testing.T) { }, } sentinelWithoutEligibleSlave := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "32"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "8"}, {typ: '+', string: "s-down-time"}, {typ: '+', string: "1"}, @@ -264,33 +264,33 @@ func TestSentinelClientInit(t *testing.T) { } sentinelWithInvalidMapResponse := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "4"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ - RedisMessage(*Nil), + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + ValkeyMessage(*Nil), }}}, }} }, } sentinelWithMasterRoleAsSlave := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "5"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "7"}, }}, @@ -299,17 +299,17 @@ func TestSentinelClientInit(t *testing.T) { }, } sentinelWithOKResponse := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "2"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "8"}, }}, @@ -352,15 +352,15 @@ func TestSentinelClientInit(t *testing.T) { } if dst == ":7" { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} }, } } if dst == ":8" { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "slave"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "slave"}}}} }, } } @@ -385,32 +385,32 @@ func TestSentinelClientInit(t *testing.T) { t.Run("Refresh retry 2", func(t *testing.T) { v := errors.New("refresh err") s0 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "1"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "2"}, }}}, }} }, } s1 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "0"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "3"}, }}}, }} @@ -425,13 +425,13 @@ func TestSentinelClientInit(t *testing.T) { } if dst == ":2" { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { return newErrResult(v) }, + DoFn: func(cmd Completed) ValkeyResult { return newErrResult(v) }, } } if dst == ":3" { return &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} }, } } @@ -455,21 +455,21 @@ func TestSentinelClientInit(t *testing.T) { s0closed := int32(0) r3closed := int32(0) s0 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if atomic.LoadInt32(&disconnect) == 1 { return newErrResult(errors.New("die")) } - return RedisResult{} + return ValkeyResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "1"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "3"}, }}}, }} @@ -485,43 +485,43 @@ func TestSentinelClientInit(t *testing.T) { }, } s1 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "2"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "3"}, }}}, }} }, } s2 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "0"}, }}, }}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "4"}, }}}, }} }, } r3 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if atomic.LoadInt32(&disconnect) == 1 { return newErrResult(errors.New("die")) } - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} }, CloseFn: func() { atomic.StoreInt32(&r3closed, 1) @@ -534,8 +534,8 @@ func TestSentinelClientInit(t *testing.T) { }, } r4 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} }, } client, err := newSentinelClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { @@ -582,23 +582,23 @@ func TestSentinelRefreshAfterClose(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) first := true s0 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { if first { first = true - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "1"}, }}}, }} } - return &redisresults{s: []RedisResult{newErrResult(ErrClosing), newErrResult(ErrClosing)}} + return &valkeyresults{s: []ValkeyResult{newErrResult(ErrClosing), newErrResult(ErrClosing)}} }, } m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} }, } client, err := newSentinelClient(&ClientOption{InitAddress: []string{":0"}}, func(dst string, opt *ClientOption) conn { @@ -623,21 +623,21 @@ func TestSentinelSwitchAfterClose(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) first := true s0 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "1"}, }}}, }} }, } m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if first { first = false - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} } return newErrResult(ErrClosing) }, @@ -664,19 +664,19 @@ func TestSentinelSwitchAfterClose(t *testing.T) { func TestSentinelClientDelegate(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) s0 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "1"}, }}}, }} }, } m := &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} }, AddrFn: func() string { return ":1" }, } @@ -702,11 +702,11 @@ func TestSentinelClientDelegate(t *testing.T) { t.Run("Delegate Do", func(t *testing.T) { c := client.B().Get().Key("Do").Build() - m.DoFn = func(cmd Completed) RedisResult { + m.DoFn = func(cmd Completed) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), c.Commands()) { t.Fatalf("unexpected command %v", cmd) } - return newResult(RedisMessage{typ: '+', string: "Do"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "Do"}, nil) } if v, err := client.Do(context.Background(), c).ToString(); err != nil || v != "Do" { t.Fatalf("unexpected response %v %v", v, err) @@ -715,8 +715,8 @@ func TestSentinelClientDelegate(t *testing.T) { t.Run("Delegate DoStream", func(t *testing.T) { c := client.B().Get().Key("Do").Build() - m.DoStreamFn = func(cmd Completed) RedisResultStream { - return RedisResultStream{e: errors.New(cmd.Commands()[1])} + m.DoStreamFn = func(cmd Completed) ValkeyResultStream { + return ValkeyResultStream{e: errors.New(cmd.Commands()[1])} } if s := client.DoStream(context.Background(), c); s.Error().Error() != "Do" { t.Fatalf("unexpected response %v", s.Error()) @@ -725,11 +725,11 @@ func TestSentinelClientDelegate(t *testing.T) { t.Run("Delegate DoMulti", func(t *testing.T) { c := client.B().Get().Key("Do").Build() - m.DoMultiFn = func(cmd ...Completed) *redisresults { + m.DoMultiFn = func(cmd ...Completed) *valkeyresults { if !reflect.DeepEqual(cmd[0].Commands(), c.Commands()) { t.Fatalf("unexpected command %v", cmd) } - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "Do"}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "Do"}, nil)}} } if len(client.DoMulti(context.Background())) != 0 { t.Fatalf("unexpected response length") @@ -741,8 +741,8 @@ func TestSentinelClientDelegate(t *testing.T) { t.Run("Delegate DoMultiStream", func(t *testing.T) { c := client.B().Get().Key("Do").Build() - m.DoMultiStreamFn = func(cmd ...Completed) MultiRedisResultStream { - return MultiRedisResultStream{e: errors.New(cmd[0].Commands()[1])} + m.DoMultiStreamFn = func(cmd ...Completed) MultiValkeyResultStream { + return MultiValkeyResultStream{e: errors.New(cmd[0].Commands()[1])} } if s := client.DoMultiStream(context.Background()); s.Error() != io.EOF { t.Fatalf("unexpected response %v", err) @@ -754,11 +754,11 @@ func TestSentinelClientDelegate(t *testing.T) { t.Run("Delegate DoCache", func(t *testing.T) { c := client.B().Get().Key("DoCache").Cache() - m.DoCacheFn = func(cmd Cacheable, ttl time.Duration) RedisResult { + m.DoCacheFn = func(cmd Cacheable, ttl time.Duration) ValkeyResult { if !reflect.DeepEqual(cmd.Commands(), c.Commands()) || ttl != 100 { t.Fatalf("unexpected command %v, %v", cmd, ttl) } - return newResult(RedisMessage{typ: '+', string: "DoCache"}, nil) + return newResult(ValkeyMessage{typ: '+', string: "DoCache"}, nil) } if v, err := client.DoCache(context.Background(), c, 100).ToString(); err != nil || v != "DoCache" { t.Fatalf("unexpected response %v %v", v, err) @@ -767,11 +767,11 @@ func TestSentinelClientDelegate(t *testing.T) { t.Run("Delegate DoMultiCache", func(t *testing.T) { c := client.B().Get().Key("DoCache").Cache() - m.DoMultiCacheFn = func(multi ...CacheableTTL) *redisresults { + m.DoMultiCacheFn = func(multi ...CacheableTTL) *valkeyresults { if !reflect.DeepEqual(multi[0].Cmd.Commands(), c.Commands()) || multi[0].TTL != 100 { t.Fatalf("unexpected command %v, %v", multi[0].Cmd, multi[0].TTL) } - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "DoCache"}, nil)}} + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "DoCache"}, nil)}} } if len(client.DoMultiCache(context.Background())) != 0 { t.Fatalf("unexpected response length") @@ -795,9 +795,9 @@ func TestSentinelClientDelegate(t *testing.T) { } }) - t.Run("Delegate Receive Redis Err", func(t *testing.T) { + t.Run("Delegate Receive Valkey Err", func(t *testing.T) { c := client.B().Subscribe().Channel("ch").Build() - e := &RedisError{} + e := &ValkeyError{} m.ReceiveFn = func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return e } @@ -826,11 +826,11 @@ func TestSentinelClientDelegate(t *testing.T) { t.Run("Dedicated Delegate", func(t *testing.T) { w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "Delegate"}, nil)}} + DoMultiFn: func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil)}} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return ErrClosing @@ -875,11 +875,11 @@ func TestSentinelClientDelegate(t *testing.T) { t.Run("Dedicate Delegate", func(t *testing.T) { w := &mockWire{ - DoFn: func(cmd Completed) RedisResult { - return newResult(RedisMessage{typ: '+', string: "Delegate"}, nil) + DoFn: func(cmd Completed) ValkeyResult { + return newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil) }, - DoMultiFn: func(cmd ...Completed) *redisresults { - return &redisresults{s: []RedisResult{newResult(RedisMessage{typ: '+', string: "Delegate"}, nil)}} + DoMultiFn: func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newResult(ValkeyMessage{typ: '+', string: "Delegate"}, nil)}} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return ErrClosing @@ -927,19 +927,19 @@ func TestSentinelClientDelegateRetry(t *testing.T) { retry := uint32(0) trigger := make(chan error) s0 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { if atomic.LoadUint32(&retry) == 0 { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "1"}, }}}, }} } - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "2"}, }}}, }} @@ -955,18 +955,18 @@ func TestSentinelClientDelegateRetry(t *testing.T) { }, } m1 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if cmd == cmds.RoleCmd { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} } atomic.AddUint32(&retry, 1) return newErrResult(ErrClosing) }, - DoMultiFn: func(multi ...Completed) *redisresults { + DoMultiFn: func(multi ...Completed) *valkeyresults { atomic.AddUint32(&retry, 1) - return &redisresults{s: []RedisResult{newErrResult(ErrClosing)}} + return &valkeyresults{s: []ValkeyResult{newErrResult(ErrClosing)}} }, - DoCacheFn: func(cmd Cacheable, ttl time.Duration) RedisResult { + DoCacheFn: func(cmd Cacheable, ttl time.Duration) ValkeyResult { atomic.AddUint32(&retry, 1) return newErrResult(ErrClosing) }, @@ -976,17 +976,17 @@ func TestSentinelClientDelegateRetry(t *testing.T) { }, } m2 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if cmd == cmds.RoleCmd { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} } - return RedisResult{val: RedisMessage{typ: '+', string: "OK"}} + return ValkeyResult{val: ValkeyMessage{typ: '+', string: "OK"}} }, - DoMultiFn: func(multi ...Completed) *redisresults { - return &redisresults{s: []RedisResult{{val: RedisMessage{typ: '+', string: "OK"}}}} + DoMultiFn: func(multi ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{{val: ValkeyMessage{typ: '+', string: "OK"}}}} }, - DoCacheFn: func(cmd Cacheable, ttl time.Duration) RedisResult { - return RedisResult{val: RedisMessage{typ: '+', string: "OK"}} + DoCacheFn: func(cmd Cacheable, ttl time.Duration) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '+', string: "OK"}} }, ReceiveFn: func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error { return nil @@ -1087,20 +1087,20 @@ func TestSentinelClientPubSub(t *testing.T) { messages := make(chan PubSubMessage) s0 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { count := atomic.AddInt32(&s0count, 1) if (count-1)%2 == 0 { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "1"}, }}}, }} } - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "2"}, }}}, }} @@ -1114,31 +1114,33 @@ func TestSentinelClientPubSub(t *testing.T) { CloseFn: func() { atomic.AddInt32(&s0close, 1) }, } m1 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if cmd == cmds.RoleCmd { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} } - return RedisResult{val: RedisMessage{typ: '+', string: "OK"}} + return ValkeyResult{val: ValkeyMessage{typ: '+', string: "OK"}} }, CloseFn: func() { atomic.AddInt32(&m1close, 1) }, } m2 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "slave"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "slave"}}}} }, CloseFn: func() { atomic.AddInt32(&m2close, 1) }, } s3 := &mockConn{ - DoMultiFn: func(cmd ...Completed) *redisresults { return &redisresults{s: []RedisResult{newErrResult(errClosing)}} }, + DoMultiFn: func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(errClosing)}} + }, } m4 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if cmd == cmds.RoleCmd { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} } - return RedisResult{val: RedisMessage{typ: '+', string: "OK4"}} + return ValkeyResult{val: ValkeyMessage{typ: '+', string: "OK4"}} }, CloseFn: func() { atomic.AddInt32(&m4close, 1) }, } @@ -1233,35 +1235,35 @@ func TestSentinelReplicaOnlyClientPubSub(t *testing.T) { messages := make(chan PubSubMessage) s0 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { return RedisResult{} }, - DoMultiFn: func(multi ...Completed) *redisresults { + DoFn: func(cmd Completed) ValkeyResult { return ValkeyResult{} }, + DoMultiFn: func(multi ...Completed) *valkeyresults { count := atomic.AddInt32(&s0count, 1) remainder := (count - 1) % 3 if remainder == 0 { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "1"}, }}, }}}, }} } else if remainder == 1 { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "2"}, }}, }}}, }} } else { - return &redisresults{s: []RedisResult{ - {val: RedisMessage{typ: '*', values: []RedisMessage{}}}, - {val: RedisMessage{typ: '*', values: []RedisMessage{ - {typ: '%', values: []RedisMessage{ + return &valkeyresults{s: []ValkeyResult{ + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}}, + {val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ + {typ: '%', values: []ValkeyMessage{ {typ: '+', string: "ip"}, {typ: '+', string: ""}, {typ: '+', string: "port"}, {typ: '+', string: "4"}, }}, @@ -1278,31 +1280,33 @@ func TestSentinelReplicaOnlyClientPubSub(t *testing.T) { CloseFn: func() { atomic.AddInt32(&s0close, 1) }, } slave1 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if cmd == cmds.RoleCmd { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "slave"}}}} + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "slave"}}}} } - return RedisResult{val: RedisMessage{typ: '+', string: "OK"}} + return ValkeyResult{val: ValkeyMessage{typ: '+', string: "OK"}} }, CloseFn: func() { atomic.AddInt32(&slave1close, 1) }, } slave2 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + DoFn: func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} }, CloseFn: func() { atomic.AddInt32(&slave2close, 1) }, } s3 := &mockConn{ - DoMultiFn: func(cmd ...Completed) *redisresults { return &redisresults{s: []RedisResult{newErrResult(errClosing)}} }, + DoMultiFn: func(cmd ...Completed) *valkeyresults { + return &valkeyresults{s: []ValkeyResult{newErrResult(errClosing)}} + }, } slave4 := &mockConn{ - DoFn: func(cmd Completed) RedisResult { + DoFn: func(cmd Completed) ValkeyResult { if cmd == cmds.RoleCmd { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "slave"}}}} + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "slave"}}}} } - return RedisResult{val: RedisMessage{typ: '+', string: "OK4"}} + return ValkeyResult{val: ValkeyMessage{typ: '+', string: "OK4"}} }, CloseFn: func() { atomic.AddInt32(&slave4close, 1) }, } @@ -1416,17 +1420,17 @@ func TestSentinelReplicaOnlyClientPubSub(t *testing.T) { func TestSentinelClientRetry(t *testing.T) { defer ShouldNotLeaked(SetupLeakDetection()) SetupClientRetry(t, func(m *mockConn) Client { - m.DoOverride = map[string]func(cmd Completed) RedisResult{ - "SENTINEL SENTINELS masters": func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{}}} + m.DoOverride = map[string]func(cmd Completed) ValkeyResult{ + "SENTINEL SENTINELS masters": func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{}}} }, - "SENTINEL GET-MASTER-ADDR-BY-NAME masters": func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{ + "SENTINEL GET-MASTER-ADDR-BY-NAME masters": func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{ {typ: '+', string: ""}, {typ: '+', string: "5"}, }}} }, - "ROLE": func(cmd Completed) RedisResult { - return RedisResult{val: RedisMessage{typ: '*', values: []RedisMessage{{typ: '+', string: "master"}}}} + "ROLE": func(cmd Completed) ValkeyResult { + return ValkeyResult{val: ValkeyMessage{typ: '*', values: []ValkeyMessage{{typ: '+', string: "master"}}}} }, } m.ReceiveOverride = map[string]func(ctx context.Context, subscribe Completed, fn func(message PubSubMessage)) error{ diff --git a/singleflight.go b/singleflight.go index 49840cd..f473872 100644 --- a/singleflight.go +++ b/singleflight.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" diff --git a/singleflight_test.go b/singleflight_test.go index 736b40d..1a735e9 100644 --- a/singleflight_test.go +++ b/singleflight_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "context" diff --git a/url.go b/url.go index a4382aa..0116172 100644 --- a/url.go +++ b/url.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "crypto/tls" @@ -10,7 +10,7 @@ import ( "time" ) -// ParseURL parses a redis URL into ClientOption. +// ParseURL parses a valkey URL into ClientOption. // https://github.com/redis/redis-specifications/blob/master/uri/redis.txt // Example: // @@ -47,7 +47,7 @@ func ParseURL(str string) (opt ClientOption, err error) { } case "redis": default: - return opt, fmt.Errorf("redis: invalid URL scheme: %s", u.Scheme) + return opt, fmt.Errorf("valkey: invalid URL scheme: %s", u.Scheme) } if opt.InitAddress == nil { host, addr := parseAddr(u.Host) @@ -63,26 +63,26 @@ func ParseURL(str string) (opt ClientOption, err error) { if u.Scheme != "unix" { if ps := strings.Split(u.Path, "/"); len(ps) == 2 { if opt.SelectDB, err = strconv.Atoi(ps[1]); err != nil { - return opt, fmt.Errorf("redis: invalid database number: %q", ps[1]) + return opt, fmt.Errorf("valkey: invalid database number: %q", ps[1]) } } else if len(ps) > 2 { - return opt, fmt.Errorf("redis: invalid URL path: %s", u.Path) + return opt, fmt.Errorf("valkey: invalid URL path: %s", u.Path) } } q := u.Query() if q.Has("db") { if opt.SelectDB, err = strconv.Atoi(q.Get("db")); err != nil { - return opt, fmt.Errorf("redis: invalid database number: %q", q.Get("db")) + return opt, fmt.Errorf("valkey: invalid database number: %q", q.Get("db")) } } if q.Has("dial_timeout") { if opt.Dialer.Timeout, err = time.ParseDuration(q.Get("dial_timeout")); err != nil { - return opt, fmt.Errorf("redis: invalid dial timeout: %q", q.Get("dial_timeout")) + return opt, fmt.Errorf("valkey: invalid dial timeout: %q", q.Get("dial_timeout")) } } if q.Has("write_timeout") { if opt.Dialer.Timeout, err = time.ParseDuration(q.Get("write_timeout")); err != nil { - return opt, fmt.Errorf("redis: invalid write timeout: %q", q.Get("write_timeout")) + return opt, fmt.Errorf("valkey: invalid write timeout: %q", q.Get("write_timeout")) } } for _, addr := range q["addr"] { diff --git a/url_test.go b/url_test.go index aea7758..db08074 100644 --- a/url_test.go +++ b/url_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "strings" @@ -9,7 +9,7 @@ func TestParseURL(t *testing.T) { if opt, err := ParseURL("re dis://"); err == nil { t.Fatalf("unexpected %v %v", opt, err) } - if opt, err := ParseURL(""); !strings.HasPrefix(err.Error(), "redis: invalid URL scheme") { + if opt, err := ParseURL(""); !strings.HasPrefix(err.Error(), "valkey: invalid URL scheme") { t.Fatalf("unexpected %v %v", opt, err) } if opt, err := ParseURL("rediss://"); err != nil || opt.TLSConfig == nil { @@ -36,19 +36,19 @@ func TestParseURL(t *testing.T) { if opt, err := ParseURL("redis:///1"); err != nil || opt.SelectDB != 1 { t.Fatalf("unexpected %v %v", opt, err) } - if opt, err := ParseURL("redis:///a"); !strings.HasPrefix(err.Error(), "redis: invalid database number") { + if opt, err := ParseURL("redis:///a"); !strings.HasPrefix(err.Error(), "valkey: invalid database number") { t.Fatalf("unexpected %v %v", opt, err) } - if opt, err := ParseURL("redis:///1?db=a"); !strings.HasPrefix(err.Error(), "redis: invalid database number") { + if opt, err := ParseURL("redis:///1?db=a"); !strings.HasPrefix(err.Error(), "valkey: invalid database number") { t.Fatalf("unexpected %v %v", opt, err) } - if opt, err := ParseURL("redis:////1"); !strings.HasPrefix(err.Error(), "redis: invalid URL path") { + if opt, err := ParseURL("redis:////1"); !strings.HasPrefix(err.Error(), "valkey: invalid URL path") { t.Fatalf("unexpected %v %v", opt, err) } - if opt, err := ParseURL("redis://?dial_timeout=a"); !strings.HasPrefix(err.Error(), "redis: invalid dial timeout") { + if opt, err := ParseURL("redis://?dial_timeout=a"); !strings.HasPrefix(err.Error(), "valkey: invalid dial timeout") { t.Fatalf("unexpected %v %v", opt, err) } - if opt, err := ParseURL("redis://?write_timeout=a"); !strings.HasPrefix(err.Error(), "redis: invalid write timeout") { + if opt, err := ParseURL("redis://?write_timeout=a"); !strings.HasPrefix(err.Error(), "valkey: invalid write timeout") { t.Fatalf("unexpected %v %v", opt, err) } if opt, err := ParseURL("redis://?protocol=2"); !opt.AlwaysRESP2 { @@ -76,7 +76,7 @@ func TestParseURL(t *testing.T) { func TestMustParseURL(t *testing.T) { defer func() { - if err := recover(); !strings.HasPrefix(err.(error).Error(), "redis: invalid URL path") { + if err := recover(); !strings.HasPrefix(err.(error).Error(), "valkey: invalid URL path") { t.Failed() } }() diff --git a/rueidis.go b/valkey.go similarity index 78% rename from rueidis.go rename to valkey.go index 06287a4..06eed48 100644 --- a/rueidis.go +++ b/valkey.go @@ -1,5 +1,5 @@ -// Package rueidis is a fast Golang Redis RESP3 client that does auto pipelining and supports client side caching. -package rueidis +// Package valkey is a fast Golang Valkey RESP3 client that does auto pipelining and supports client side caching. +package valkey //go:generate go run hack/cmds/gen.go internal/cmds hack/cmds/*.json @@ -36,15 +36,15 @@ const ( var ( // ErrClosing means the Client.Close had been called - ErrClosing = errors.New("rueidis client is closing or unable to connect redis") + ErrClosing = errors.New("valkey client is closing or unable to connect valkey") // ErrNoAddr means the ClientOption.InitAddress is empty ErrNoAddr = errors.New("no alive address in InitAddress") - // ErrNoCache means your redis does not support client-side caching and must set ClientOption.DisableCache to true - ErrNoCache = errors.New("ClientOption.DisableCache must be true for redis not supporting client-side caching or not supporting RESP3") - // ErrRESP2PubSubMixed means your redis does not support RESP3 and rueidis can't handle SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE in mixed case - ErrRESP2PubSubMixed = errors.New("rueidis does not support SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE mixed with other commands in RESP2") - // ErrDoCacheAborted means redis abort EXEC request or connection closed - ErrDoCacheAborted = errors.New("failed to fetch the cache because EXEC was aborted by redis or connection closed") + // ErrNoCache means your valkey does not support client-side caching and must set ClientOption.DisableCache to true + ErrNoCache = errors.New("ClientOption.DisableCache must be true for valkey not supporting client-side caching or not supporting RESP3") + // ErrRESP2PubSubMixed means your valkey does not support RESP3 and valkey can't handle SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE in mixed case + ErrRESP2PubSubMixed = errors.New("valkey does not support SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE mixed with other commands in RESP2") + // ErrDoCacheAborted means valkey abort EXEC request or connection closed + ErrDoCacheAborted = errors.New("failed to fetch the cache because EXEC was aborted by valkey or connection closed") // ErrReplicaOnlyNotSupported means ReplicaOnly flag is not supported by // current client ErrReplicaOnlyNotSupported = errors.New("ReplicaOnly is not supported for single client") @@ -55,7 +55,7 @@ var ( // ClientOption should be passed to NewClient to construct a Client type ClientOption struct { // TCP & TLS - // Dialer can be used to customized how rueidis connect to a redis instance via TCP, including: + // Dialer can be used to customized how valkey connect to a valkey instance via TCP, including: // - Timeout, the default is DefaultDialTimeout // - KeepAlive, the default is DefaultTCPKeepAlive // The Dialer.KeepAlive interval is used to detect an unresponsive idle tcp connection. @@ -72,8 +72,8 @@ type ClientOption struct { NewCacheStoreFn NewCacheStoreFn // OnInvalidations is a callback function in case of client-side caching invalidation received. - // Note that this function must be fast, otherwise other redis messages will be blocked. - OnInvalidations func([]RedisMessage) + // Note that this function must be fast, otherwise other valkey messages will be blocked. + OnInvalidations func([]ValkeyMessage) // SendToReplicas is a function that returns true if the command should be sent to replicas. // currently only used for cluster client. @@ -83,7 +83,7 @@ type ClientOption struct { // Sentinel options, including MasterSet and Auth options Sentinel SentinelOption - // Redis AUTH parameters + // Valkey AUTH parameters Username string Password string ClientName string @@ -96,9 +96,9 @@ type ClientOption struct { // Note that ClientSetInfo should have exactly 2 values, the lib name and the lib version respectively. ClientSetInfo []string - // InitAddress point to redis nodes. - // Rueidis will connect to them one by one and issue CLUSTER SLOT command to initialize the cluster client until success. - // If len(InitAddress) == 1 and the address is not running in cluster mode, rueidis will fall back to the single client mode. + // InitAddress point to valkey nodes. + // Valkey will connect to them one by one and issue CLUSTER SLOT command to initialize the cluster client until success. + // If len(InitAddress) == 1 and the address is not running in cluster mode, valkey will fall back to the single client mode. // If ClientOption.Sentinel.MasterSet is set, then InitAddress will be used to connect sentinels // You can bypass this behaviour by using ClientOption.ForceSingleClient. InitAddress []string @@ -109,7 +109,7 @@ type ClientOption struct { SelectDB int - // CacheSizeEachConn is redis client side cache size that bind to each TCP connection to a single redis instance. + // CacheSizeEachConn is valkey client side cache size that bind to each TCP connection to a single valkey instance. // The default is DefaultCacheBytes. CacheSizeEachConn int @@ -128,23 +128,23 @@ type ClientOption struct { // The default is DefaultPoolSize. BlockingPoolSize int - // PipelineMultiplex determines how many tcp connections used to pipeline commands to one redis instance. + // PipelineMultiplex determines how many tcp connections used to pipeline commands to one valkey instance. // The default for single and sentinel clients is 2, which means 4 connections (2^2). // The default for cluster clients is 0, which means 1 connection (2^0). PipelineMultiplex int // ConnWriteTimeout is read/write timeout for each connection. If specified, // it is used to control the maximum duration waits for responses to pipeline commands. - // Also, ConnWriteTimeout is applied net.Conn.SetDeadline and periodic PING to redis + // Also, ConnWriteTimeout is applied net.Conn.SetDeadline and periodic PING to valkey // Since the Dialer.KeepAlive will not be triggered if there is data in the outgoing buffer, - // ConnWriteTimeout should be set in order to detect local congestion or unresponsive redis server. + // ConnWriteTimeout should be set in order to detect local congestion or unresponsive valkey server. // This default is ClientOption.Dialer.KeepAlive * (9+1), where 9 is the default of tcp_keepalive_probes on Linux. ConnWriteTimeout time.Duration // MaxFlushDelay when greater than zero pauses pipeline write loop for some time (not larger than MaxFlushDelay) // after each flushing of data to the connection. This gives pipeline a chance to collect more commands to send - // to Redis. Adding this delay increases latency, reduces throughput – but in most cases may significantly reduce - // application and Redis CPU utilization due to less executed system calls. By default, Rueidis flushes data to the + // to Valkey. Adding this delay increases latency, reduces throughput – but in most cases may significantly reduce + // application and Valkey CPU utilization due to less executed system calls. By default, Valkey flushes data to the // connection without extra delays. Depending on network latency and application-specific conditions the value // of MaxFlushDelay may vary, sth like 20 microseconds should not affect latency/throughput a lot but still // produce notable CPU usage reduction under load. Ref: https://github.com/redis/rueidis/issues/156 @@ -158,15 +158,15 @@ type ClientOption struct { DisableRetry bool // DisableCache falls back Client.DoCache/Client.DoMultiCache to Client.Do/Client.DoMulti DisableCache bool - // AlwaysPipelining makes rueidis.Client always pipeline redis commands even if they are not issued concurrently. + // AlwaysPipelining makes valkey.Client always pipeline valkey commands even if they are not issued concurrently. AlwaysPipelining bool - // AlwaysRESP2 makes rueidis.Client always uses RESP2, otherwise it will try using RESP3 first. + // AlwaysRESP2 makes valkey.Client always uses RESP2, otherwise it will try using RESP3 first. AlwaysRESP2 bool // ForceSingleClient force the usage of a single client connection, without letting the lib guessing - // if redis instance is a cluster or a single redis instance. + // if valkey instance is a cluster or a single valkey instance. ForceSingleClient bool - // ReplicaOnly indicates that this client will only try to connect to readonly replicas of redis setup. + // ReplicaOnly indicates that this client will only try to connect to readonly replicas of valkey setup. ReplicaOnly bool // ClientNoEvict sets the client eviction mode for the current connection. @@ -182,17 +182,17 @@ type SentinelOption struct { Dialer net.Dialer TLSConfig *tls.Config - // MasterSet is the redis master set name monitored by sentinel cluster. + // MasterSet is the valkey master set name monitored by sentinel cluster. // If this field is set, then ClientOption.InitAddress will be used to connect to sentinel cluster. MasterSet string - // Redis AUTH parameters for sentinel + // Valkey AUTH parameters for sentinel Username string Password string ClientName string } -// Client is the redis client interface for both single redis instance and redis cluster. It should be created from the NewClient() +// Client is the valkey client interface for both single valkey instance and valkey cluster. It should be created from the NewClient() type Client interface { CoreClient @@ -200,33 +200,33 @@ type Client interface { // The explicit client side TTL specifies the maximum TTL on the client side. // If the key's TTL on the server is smaller than the client side TTL, the client side TTL will be capped. // client.Do(ctx, client.B().Get().Key("k").Cache(), time.Minute).ToString() - // The above example will send the following command to redis if cache miss: + // The above example will send the following command to valkey if cache miss: // CLIENT CACHING YES // PTTL k // GET k // The in-memory cache size is configured by ClientOption.CacheSizeEachConn. // The cmd parameter is recycled after passing into DoCache() and should not be reused. - DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp RedisResult) + DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp ValkeyResult) // DoMultiCache is similar to DoCache, but works with multiple cacheable commands across different slots. - // It will first group commands by slots and will send only cache missed commands to redis. - DoMultiCache(ctx context.Context, multi ...CacheableTTL) (resp []RedisResult) + // It will first group commands by slots and will send only cache missed commands to valkey. + DoMultiCache(ctx context.Context, multi ...CacheableTTL) (resp []ValkeyResult) - // DoStream send a command to redis through a dedicated connection acquired from a connection pool. - // It returns a RedisResultStream, but it does not read the command response until the RedisResultStream.WriteTo is called. - // After the RedisResultStream.WriteTo is called, the underlying connection is then recycled. - // DoStream should only be used when you want to stream redis response directly to an io.Writer without additional allocation, + // DoStream send a command to valkey through a dedicated connection acquired from a connection pool. + // It returns a ValkeyResultStream, but it does not read the command response until the ValkeyResultStream.WriteTo is called. + // After the ValkeyResultStream.WriteTo is called, the underlying connection is then recycled. + // DoStream should only be used when you want to stream valkey response directly to an io.Writer without additional allocation, // otherwise, the normal Do() should be used instead. // Also note that DoStream can only work with commands returning string, integer, or float response. - DoStream(ctx context.Context, cmd Completed) RedisResultStream + DoStream(ctx context.Context, cmd Completed) ValkeyResultStream - // DoMultiStream is similar to DoStream, but pipelines multiple commands to redis. - // It returns a MultiRedisResultStream, and users should call MultiRedisResultStream.WriteTo as many times as the number of commands sequentially - // to read each command response from redis. After all responses are read, the underlying connection is then recycled. - // DoMultiStream should only be used when you want to stream redis responses directly to an io.Writer without additional allocation, + // DoMultiStream is similar to DoStream, but pipelines multiple commands to valkey. + // It returns a MultiValkeyResultStream, and users should call MultiValkeyResultStream.WriteTo as many times as the number of commands sequentially + // to read each command response from valkey. After all responses are read, the underlying connection is then recycled. + // DoMultiStream should only be used when you want to stream valkey responses directly to an io.Writer without additional allocation, // otherwise, the normal DoMulti() should be used instead. - // DoMultiStream does not support multiple key slots when connecting to a redis cluster. - DoMultiStream(ctx context.Context, multi ...Completed) MultiRedisResultStream + // DoMultiStream does not support multiple key slots when connecting to a valkey cluster. + DoMultiStream(ctx context.Context, multi ...Completed) MultiValkeyResultStream // Dedicated acquire a connection from the blocking connection pool, no one else can use the connection // during Dedicated. The main usage of Dedicated is CAS operation, which is WATCH + MULTI + EXEC. @@ -238,14 +238,14 @@ type Client interface { // and requires user to invoke cancel() manually to put connection back to the pool. Dedicate() (client DedicatedClient, cancel func()) - // Nodes returns each redis node this client known as rueidis.Client. This is useful if you want to - // send commands to some specific redis nodes in the cluster. + // Nodes returns each valkey node this client known as valkey.Client. This is useful if you want to + // send commands to some specific valkey nodes in the cluster. Nodes() map[string]Client } -// DedicatedClient is obtained from Client.Dedicated() and it will be bound to single redis connection and +// DedicatedClient is obtained from Client.Dedicated() and it will be bound to single valkey connection and // no other commands can be pipelined in to this connection during Client.Dedicated(). -// If the DedicatedClient is obtained from cluster client, the first command to it must have a Key() to identify the redis node. +// If the DedicatedClient is obtained from cluster client, the first command to it must have a Key() to identify the valkey node. type DedicatedClient interface { CoreClient @@ -266,15 +266,15 @@ type CoreClient interface { // B is the getter function to the command builder for the client // If the client is a cluster client, the command builder also prohibits cross key slots in one command. B() Builder - // Do is the method sending user's redis command building from the B() to a redis node. + // Do is the method sending user's valkey command building from the B() to a valkey node. // client.Do(ctx, client.B().Get().Key("k").Build()).ToString() // All concurrent non-blocking commands will be pipelined automatically and have better throughput. // Blocking commands will use another separated connection pool. // The cmd parameter is recycled after passing into Do() and should not be reused. - Do(ctx context.Context, cmd Completed) (resp RedisResult) - // DoMulti takes multiple redis commands and sends them together, reducing RTT from the user code. + Do(ctx context.Context, cmd Completed) (resp ValkeyResult) + // DoMulti takes multiple valkey commands and sends them together, reducing RTT from the user code. // The multi parameters are recycled after passing into DoMulti() and should not be reused. - DoMulti(ctx context.Context, multi ...Completed) (resp []RedisResult) + DoMulti(ctx context.Context, multi ...Completed) (resp []ValkeyResult) // Receive accepts SUBSCRIBE, SSUBSCRIBE, PSUBSCRIBE command and a message handler. // Receive will block and then return value only when the following cases: // 1. return nil when received any unsubscribe/punsubscribe message related to the provided `subscribe` command. @@ -351,7 +351,7 @@ func NewClient(option ClientOption) (client Client, err error) { if client == (*clusterClient)(nil) { return nil, err } - if len(option.InitAddress) == 1 && (err.Error() == redisErrMsgCommandNotAllow || strings.Contains(strings.ToUpper(err.Error()), "CLUSTER")) { + if len(option.InitAddress) == 1 && (err.Error() == valkeyErrMsgCommandNotAllow || strings.Contains(strings.ToUpper(err.Error()), "CLUSTER")) { option.PipelineMultiplex = singleClientMultiplex(option.PipelineMultiplex) client, err = newSingleClient(&option, client.(*clusterClient).single(), makeConn) } else { @@ -390,5 +390,5 @@ func dial(dst string, opt *ClientOption) (conn net.Conn, err error) { return conn, err } -const redisErrMsgCommandNotAllow = "command is not allowed" +const valkeyErrMsgCommandNotAllow = "command is not allowed" const dedicatedClientUsedAfterReleased = "DedicatedClient should not be used after recycled" diff --git a/redis_test.go b/valkey_e2e_test.go similarity index 98% rename from redis_test.go rename to valkey_e2e_test.go index 472dd54..e47b2c5 100644 --- a/redis_test.go +++ b/valkey_e2e_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "bytes" @@ -87,7 +87,7 @@ func testFlush(t *testing.T, client Client) { key := strconv.Itoa(i) jobs <- func() { resp := client.DoCache(ctx, client.B().Get().Key(key).Cache(), time.Minute) - if !IsRedisNil(resp.Error()) { + if !IsValkeyNil(resp.Error()) { t.Fatalf("unexpected csc get response after flush %v", resp) } if resp.IsCacheHit() { @@ -136,7 +136,7 @@ func testSETGET(t *testing.T, client Client, csc bool) { key := strconv.Itoa(rand.Intn(keys * 2)) jobs <- func() { val, err := client.Do(ctx, client.B().Get().Key(key).Build()).ToString() - if v, ok := kvs[key]; !((ok && val == v) || (!ok && IsRedisNil(err))) { + if v, ok := kvs[key]; !((ok && val == v) || (!ok && IsValkeyNil(err))) { t.Errorf("unexpected get response %v %v %v", val, err, ok) } } @@ -151,7 +151,7 @@ func testSETGET(t *testing.T, client Client, csc bool) { s := client.DoStream(ctx, client.B().Get().Key(key).Build()) buf := bytes.NewBuffer(nil) n, err := s.WriteTo(buf) - if v, ok := kvs[key]; !((ok && buf.String() == v && n == int64(buf.Len())) || (!ok && IsRedisNil(err))) { + if v, ok := kvs[key]; !((ok && buf.String() == v && n == int64(buf.Len())) || (!ok && IsValkeyNil(err))) { t.Errorf("unexpected get response %v %v %v", buf.String(), err, ok) } } @@ -167,7 +167,7 @@ func testSETGET(t *testing.T, client Client, csc bool) { defer cancel() val, err := client.Do(ctx, client.B().Get().Key(key).Build()).ToString() if err != context.DeadlineExceeded { - if v, ok := kvs[key]; !((ok && val == v) || (!ok && IsRedisNil(err))) { + if v, ok := kvs[key]; !((ok && val == v) || (!ok && IsValkeyNil(err))) { t.Errorf("unexpected get response %v %v %v", val, err, ok) } } @@ -183,7 +183,7 @@ func testSETGET(t *testing.T, client Client, csc bool) { jobs <- func() { resp := client.DoCache(ctx, client.B().Get().Key(key).Cache(), time.Minute) val, err := resp.ToString() - if v, ok := kvs[key]; !((ok && val == v) || (!ok && IsRedisNil(err))) { + if v, ok := kvs[key]; !((ok && val == v) || (!ok && IsValkeyNil(err))) { t.Errorf("unexpected csc get response %v %v %v", val, err, ok) } if resp.IsCacheHit() { @@ -225,7 +225,7 @@ func testSETGET(t *testing.T, client Client, csc bool) { key := strconv.Itoa(i) jobs <- func() { resp := client.DoCache(ctx, client.B().Get().Key(key).Cache(), time.Minute) - if !IsRedisNil(resp.Error()) { + if !IsValkeyNil(resp.Error()) { t.Errorf("unexpected csc get response after delete %v", resp) } if resp.IsCacheHit() { @@ -295,7 +295,7 @@ func testMultiSETGET(t *testing.T, client Client, csc bool) { jobs <- func() { for j, resp := range client.DoMulti(ctx, commands...) { val, err := resp.ToString() - if v, ok := kvs[cmdkeys[j]]; !((ok && val == v) || (!ok && IsRedisNil(err))) { + if v, ok := kvs[cmdkeys[j]]; !((ok && val == v) || (!ok && IsValkeyNil(err))) { t.Fatalf("unexpected get response %v %v %v", val, err, ok) } } @@ -318,7 +318,7 @@ func testMultiSETGET(t *testing.T, client Client, csc bool) { for j, resp := range client.DoMulti(ctx, commands...) { val, err := resp.ToString() if err != context.DeadlineExceeded { - if v, ok := kvs[cmdkeys[j]]; !((ok && val == v) || (!ok && IsRedisNil(err))) { + if v, ok := kvs[cmdkeys[j]]; !((ok && val == v) || (!ok && IsValkeyNil(err))) { t.Fatalf("unexpected get response %v %v %v", val, err, ok) } } @@ -340,7 +340,7 @@ func testMultiSETGET(t *testing.T, client Client, csc bool) { jobs <- func() { for j, resp := range client.DoMultiCache(ctx, commands...) { val, err := resp.ToString() - if v, ok := kvs[cmdkeys[j]]; !((ok && val == v) || (!ok && IsRedisNil(err))) { + if v, ok := kvs[cmdkeys[j]]; !((ok && val == v) || (!ok && IsValkeyNil(err))) { t.Fatalf("unexpected csc get response %v %v %v", val, err, ok) } if resp.IsCacheHit() { @@ -395,7 +395,7 @@ func testMultiSETGET(t *testing.T, client Client, csc bool) { } jobs <- func() { for _, resp := range client.DoMultiCache(ctx, commands...) { - if !IsRedisNil(resp.Error()) { + if !IsValkeyNil(resp.Error()) { t.Fatalf("unexpected csc get response after delete %v", resp) } if resp.IsCacheHit() { @@ -428,7 +428,7 @@ func testMultiSETGETHelpers(t *testing.T, client Client, csc bool) { for i := 0; i < len(cmdKeys); i++ { cmdKeys[i] = "z" + strconv.Itoa(i) } - validate := func(resp map[string]RedisMessage) { + validate := func(resp map[string]ValkeyMessage) { for _, key := range cmdKeys { ret, ok := resp[key] if !ok { diff --git a/rueidis_test.go b/valkey_test.go similarity index 95% rename from rueidis_test.go rename to valkey_test.go index 8a54734..95cca9e 100644 --- a/rueidis_test.go +++ b/valkey_test.go @@ -1,4 +1,4 @@ -package rueidis +package valkey import ( "bufio" @@ -39,21 +39,21 @@ func TestMain(m *testing.M) { os.Exit(code) } -func accept(t *testing.T, ln net.Listener) (*redisMock, error) { +func accept(t *testing.T, ln net.Listener) (*valkeyMock, error) { conn, err := ln.Accept() if err != nil { t.Error(err) return nil, err } - mock := &redisMock{ + mock := &valkeyMock{ t: t, buf: bufio.NewReader(conn), conn: conn, } mock.Expect("HELLO", "3"). - Reply(RedisMessage{ + Reply(ValkeyMessage{ typ: '%', - values: []RedisMessage{ + values: []ValkeyMessage{ {typ: '+', string: "proto"}, {typ: ':', integer: 3}, }, @@ -118,7 +118,7 @@ func TestNewClusterClientError(t *testing.T) { ReplyError("UNKNOWN COMMAND") mock.Expect("CLIENT", "SETINFO", "LIB-VER", LibVer). ReplyError("UNKNOWN COMMAND") - mock.Expect("CLUSTER", "SLOTS").Reply(RedisMessage{typ: '-', string: "other error"}) + mock.Expect("CLUSTER", "SLOTS").Reply(ValkeyMessage{typ: '-', string: "other error"}) mock.Expect("PING").ReplyString("OK") mock.Close() close(done) @@ -175,7 +175,7 @@ func TestFallBackSingleClient(t *testing.T) { ReplyError("UNKNOWN COMMAND") mock.Expect("CLIENT", "SETINFO", "LIB-VER", LibVer). ReplyError("UNKNOWN COMMAND") - mock.Expect("CLUSTER", "SLOTS").Reply(RedisMessage{typ: '-', string: "ERR This instance has cluster support disabled"}) + mock.Expect("CLUSTER", "SLOTS").Reply(ValkeyMessage{typ: '-', string: "ERR This instance has cluster support disabled"}) mock.Expect("PING").ReplyString("OK") mock.Close() close(done) @@ -294,7 +294,7 @@ func TestTLSClient(t *testing.T) { ReplyError("UNKNOWN COMMAND") mock.Expect("CLIENT", "SETINFO", "LIB-VER", LibVer). ReplyError("UNKNOWN COMMAND") - mock.Expect("CLUSTER", "SLOTS").Reply(RedisMessage{typ: '-', string: "ERR This instance has cluster support disabled"}) + mock.Expect("CLUSTER", "SLOTS").Reply(ValkeyMessage{typ: '-', string: "ERR This instance has cluster support disabled"}) mock.Expect("PING").ReplyString("OK") mock.Close() close(done) @@ -358,7 +358,7 @@ func TestCustomDialFnIsCalled(t *testing.T) { } } -func ExampleIsRedisNil() { +func ExampleIsValkeyNil() { client, err := NewClient(ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) @@ -366,7 +366,7 @@ func ExampleIsRedisNil() { defer client.Close() _, err = client.Do(context.Background(), client.B().Get().Key("not_exists").Build()).ToString() - if err != nil && IsRedisNil(err) { + if err != nil && IsValkeyNil(err) { fmt.Printf("it is a nil response") } } @@ -420,7 +420,7 @@ func ExampleClient_scan() { } defer client.Close() - for _, c := range client.Nodes() { // loop over all your redis nodes + for _, c := range client.Nodes() { // loop over all your valkey nodes var scan ScanEntry for more := true; more; more = scan.Cursor != 0 { if scan, err = c.Do(context.Background(), c.B().Scan().Cursor(scan.Cursor).Build()).AsScanEntry(); err != nil { diff --git a/rueidisaside/README.md b/valkeyaside/README.md similarity index 64% rename from rueidisaside/README.md rename to valkeyaside/README.md index 899c9c7..6573c03 100644 --- a/rueidisaside/README.md +++ b/valkeyaside/README.md @@ -1,18 +1,18 @@ -# rueidisaside +# valkeyaside A Cache-Aside pattern implementation enhanced by [Client Side Caching](https://redis.io/docs/manual/client-side-caching/). -## Features backed by the Redis Client Side Caching +## Features backed by the Valkey Client Side Caching -Cache-Aside is a widely used pattern to cache other data sources into Redis. However, there are many issues to be considered when implementing it. +Cache-Aside is a widely used pattern to cache other data sources into Valkey. However, there are many issues to be considered when implementing it. For example, an implementation without locking or versioning may cause a fresh cache be overridden by a stale one. And if using a locking mechanism, how to get notified when a lock is released? If using versioning mechanism, how to version an empty value? Thankfully, the above issues can be addressed better with the client-side caching along with the following additional benefits: -* Avoiding unnecessary network round trips. Redis will proactively invalidate the client-side cache. -* Avoiding Cache Stampede by locking keys with the client-side caching, the same technique used in [rueidislock](https://github.com/redis/rueidis/tree/main/rueidislock). Only the first cache missed call can update the cache and others will wait for notifications. +* Avoiding unnecessary network round trips. Valkey will proactively invalidate the client-side cache. +* Avoiding Cache Stampede by locking keys with the client-side caching, the same technique used in [valkeylock](https://github.com/rueian/valkey-go/tree/main/valkeylock). Only the first cache missed call can update the cache and others will wait for notifications. ## Example @@ -24,14 +24,14 @@ import ( "database/sql" "time" - "github.com/redis/rueidis" - "github.com/redis/rueidis/rueidisaside" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/valkeyaside" ) func main() { var db sql.DB - client, err := rueidisaside.NewClient(rueidisaside.ClientOption{ - ClientOption: rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}, + client, err := valkeyaside.NewClient(valkeyaside.ClientOption{ + ClientOption: valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}, }) if err != nil { panic(err) @@ -56,4 +56,4 @@ func main() { ## Limitation -Currently, requires Redis >= 7.0. \ No newline at end of file +Currently, requires Valkey >= 7.0. \ No newline at end of file diff --git a/rueidisaside/aside.go b/valkeyaside/aside.go similarity index 81% rename from rueidisaside/aside.go rename to valkeyaside/aside.go index 7d71aaf..85673b9 100644 --- a/rueidisaside/aside.go +++ b/valkeyaside/aside.go @@ -1,4 +1,4 @@ -package rueidisaside +package valkeyaside import ( "context" @@ -8,20 +8,20 @@ import ( "time" "github.com/oklog/ulid/v2" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) type ClientOption struct { - // ClientBuilder can be used to modify rueidis.Client used by Locker - ClientBuilder func(option rueidis.ClientOption) (rueidis.Client, error) - ClientOption rueidis.ClientOption + // ClientBuilder can be used to modify valkey.Client used by Locker + ClientBuilder func(option valkey.ClientOption) (valkey.Client, error) + ClientOption valkey.ClientOption ClientTTL time.Duration // TTL for the client marker, refreshed every 1/2 TTL. Defaults to 10s. The marker allows other client to know if this client is still alive. } type CacheAsideClient interface { Get(ctx context.Context, ttl time.Duration, key string, fn func(ctx context.Context, key string) (val string, err error)) (val string, err error) Del(ctx context.Context, key string) error - Client() rueidis.Client + Client() valkey.Client Close() } @@ -37,7 +37,7 @@ func NewClient(option ClientOption) (cc CacheAsideClient, err error) { if option.ClientBuilder != nil { ca.client, err = option.ClientBuilder(option.ClientOption) } else { - ca.client, err = rueidis.NewClient(option.ClientOption) + ca.client, err = valkey.NewClient(option.ClientOption) } if err != nil { return nil, err @@ -47,7 +47,7 @@ func NewClient(option ClientOption) (cc CacheAsideClient, err error) { } type Client struct { - client rueidis.Client + client valkey.Client ctx context.Context waits map[string]chan struct{} cancel context.CancelFunc @@ -56,7 +56,7 @@ type Client struct { mu sync.Mutex } -func (c *Client) onInvalidation(messages []rueidis.RedisMessage) { +func (c *Client) onInvalidation(messages []valkey.ValkeyMessage) { var id string c.mu.Lock() if messages == nil { @@ -135,11 +135,11 @@ retry: wait := c.register(key) resp := c.client.DoCache(ctx, c.client.B().Get().Key(key).Cache(), ttl) val, err := resp.ToString() - if rueidis.IsRedisNil(err) && fn != nil { // cache miss, prepare to populate the value by fn() + if valkey.IsValkeyNil(err) && fn != nil { // cache miss, prepare to populate the value by fn() var id string if id, err = c.keepalive(); err == nil { // acquire client id val, err = c.client.Do(ctx, c.client.B().Set().Key(key).Value(id).Nx().Get().Px(ttl).Build()).ToString() - if rueidis.IsRedisNil(err) { // successfully set client id on the key as a lock + if valkey.IsValkeyNil(err) { // successfully set client id on the key as a lock if val, err = fn(ctx, key); err == nil { err = setkey.Exec(ctx, c.client, []string{key}, []string{id, val, strconv.FormatInt(ttl.Milliseconds(), 10)}).Error() } @@ -155,7 +155,7 @@ retry: if strings.HasPrefix(val, PlaceholderPrefix) { ph := c.register(val) err = c.client.DoCache(ctx, c.client.B().Get().Key(val).Cache(), c.ttl).Error() - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { // the client who held the lock has gone, release the lock. delkey.Exec(context.Background(), c.client, []string{key}, []string{val}) goto retry @@ -178,8 +178,8 @@ func (c *Client) Del(ctx context.Context, key string) error { return c.client.Do(ctx, c.client.B().Del().Key(key).Build()).Error() } -// Client exports the underlying rueidis.Client -func (c *Client) Client() rueidis.Client { +// Client exports the underlying valkey.Client +func (c *Client) Client() valkey.Client { return c.client } @@ -194,9 +194,9 @@ func (c *Client) Close() { c.client.Close() } -const PlaceholderPrefix = "rueidisid:" +const PlaceholderPrefix = "valkeyid:" var ( - delkey = rueidis.NewLuaScript(`if redis.call("GET",KEYS[1]) == ARGV[1] then return redis.call("DEL",KEYS[1]) else return 0 end`) - setkey = rueidis.NewLuaScript(`if redis.call("GET",KEYS[1]) == ARGV[1] then return redis.call("SET",KEYS[1],ARGV[2],"PX",ARGV[3]) else return 0 end`) + delkey = valkey.NewLuaScript(`if redis.call("GET",KEYS[1]) == ARGV[1] then return redis.call("DEL",KEYS[1]) else return 0 end`) + setkey = valkey.NewLuaScript(`if redis.call("GET",KEYS[1]) == ARGV[1] then return redis.call("SET",KEYS[1],ARGV[2],"PX",ARGV[3]) else return 0 end`) ) diff --git a/rueidisaside/aside_test.go b/valkeyaside/aside_test.go similarity index 93% rename from rueidisaside/aside_test.go rename to valkeyaside/aside_test.go index 84c5e4d..d5a39f1 100644 --- a/rueidisaside/aside_test.go +++ b/valkeyaside/aside_test.go @@ -1,4 +1,4 @@ -package rueidisaside +package valkeyaside import ( "context" @@ -9,14 +9,14 @@ import ( "testing" "time" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) var addr = []string{"127.0.0.1:6379"} func makeClient(t *testing.T, addr []string) CacheAsideClient { client, err := NewClient(ClientOption{ - ClientOption: rueidis.ClientOption{InitAddress: addr}, + ClientOption: valkey.ClientOption{InitAddress: addr}, ClientTTL: time.Second, }) if err != nil { @@ -32,11 +32,11 @@ func TestClientErr(t *testing.T) { } func TestWithClientBuilder(t *testing.T) { - var client rueidis.Client + var client valkey.Client c, err := NewClient(ClientOption{ - ClientOption: rueidis.ClientOption{InitAddress: addr}, - ClientBuilder: func(option rueidis.ClientOption) (_ rueidis.Client, err error) { - client, err = rueidis.NewClient(option) + ClientOption: valkey.ClientOption{InitAddress: addr}, + ClientBuilder: func(option valkey.ClientOption) (_ valkey.Client, err error) { + client, err = valkey.NewClient(option) return client, err }, }) @@ -66,7 +66,7 @@ func TestCacheFilled(t *testing.T) { } time.Sleep(time.Millisecond * 600) val, err = client.Get(context.Background(), time.Millisecond*500, key, nil) // should miss - if !rueidis.IsRedisNil(err) { + if !valkey.IsValkeyNil(err) { t.Fatal(err) } } @@ -92,7 +92,7 @@ func TestCacheDel(t *testing.T) { } time.Sleep(time.Millisecond * 50) val, err = client.Get(context.Background(), time.Millisecond*500, key, nil) // should miss - if !rueidis.IsRedisNil(err) { + if !valkey.IsValkeyNil(err) { t.Fatal(err) } } @@ -138,7 +138,7 @@ func TestCloseCleanup(t *testing.T) { client = makeClient(t, addr).(*Client) defer client.Close() err := client.client.Do(context.Background(), client.client.B().Get().Key(<-ch).Build()).Error() - if !rueidis.IsRedisNil(err) { + if !valkey.IsValkeyNil(err) { t.Error(err) } } @@ -165,7 +165,7 @@ func TestWriteCancel(t *testing.T) { t.Fatal(err) } err = client.client.Do(context.Background(), client.client.B().Get().Key(key).Build()).Error() - if !rueidis.IsRedisNil(err) { + if !valkey.IsValkeyNil(err) { t.Error(err) } } @@ -228,7 +228,7 @@ func TestDisconnect(t *testing.T) { t.Error(err) } err = client.client.Do(context.Background(), client.client.B().Get().Key(<-ch).Build()).Error() // id1 - if !rueidis.IsRedisNil(err) { + if !valkey.IsValkeyNil(err) { t.Error(err) } err = client.client.Do(context.Background(), client.client.B().Get().Key(<-ch).Build()).Error() // id2 diff --git a/valkeyaside/go.mod b/valkeyaside/go.mod new file mode 100644 index 0000000..15bd0e8 --- /dev/null +++ b/valkeyaside/go.mod @@ -0,0 +1,12 @@ +module github.com/rueian/valkey-go/valkeyaside + +go 1.20 + +replace github.com/rueian/valkey-go => ../ + +require ( + github.com/oklog/ulid/v2 v2.1.0 + github.com/rueian/valkey-go v1.0.34 +) + +require golang.org/x/sys v0.17.0 // indirect diff --git a/rueidisaside/go.sum b/valkeyaside/go.sum similarity index 100% rename from rueidisaside/go.sum rename to valkeyaside/go.sum diff --git a/valkeycompat/README.md b/valkeycompat/README.md new file mode 100644 index 0000000..fc5057f --- /dev/null +++ b/valkeycompat/README.md @@ -0,0 +1,41 @@ +## Go-redis like API Adapter + +Though it is easier to know what command will be sent to valkey at first glance if the command is constructed by the command builder, +users may sometimes feel it too verbose to write. + +For users who don't like the command builder, `valkeycompat.Adapter`, contributed mainly by [@418Coffee](https://github.com/418Coffee), is an alternative. +It is a high level API which is close to go-redis's `Cmdable` interface. + +### Migrating from go-redis + +You can also try adapting `valkey` with existing go-redis code by replacing go-redis's `UniversalClient` with `valkeycompat.Adapter`. + +### Client side caching + +To use client side caching with `valkeycompat.Adapter`, chain `Cache(ttl)` call in front of supported command. + +```golang +package main + +import ( + "context" + "time" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/valkeycompat" +) + +func main() { + ctx := context.Background() + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) + if err != nil { + panic(err) + } + defer client.Close() + + compat := valkeycompat.NewAdapter(client) + ok, _ := compat.SetNX(ctx, "key", "val", time.Second).Result() + + // with client side caching + res, _ := compat.Cache(time.Second).Get(ctx, "key").Result() +} +``` \ No newline at end of file diff --git a/rueidiscompat/adapter.go b/valkeycompat/adapter.go similarity index 97% rename from rueidiscompat/adapter.go rename to valkeycompat/adapter.go index 4ac383e..19cb34b 100644 --- a/rueidiscompat/adapter.go +++ b/valkeycompat/adapter.go @@ -24,7 +24,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package rueidiscompat +package valkeycompat import ( "context" @@ -38,9 +38,9 @@ import ( "sync/atomic" "time" - "github.com/redis/rueidis" - "github.com/redis/rueidis/internal/cmds" - "github.com/redis/rueidis/internal/util" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/internal/cmds" + "github.com/rueian/valkey-go/internal/util" ) const KeepTTL = -1 @@ -546,17 +546,17 @@ type JSONCmdable interface { var _ Cmdable = (*Compat)(nil) type Compat struct { - client rueidis.Client + client valkey.Client maxp int } // CacheCompat implements commands that support client-side caching. type CacheCompat struct { - client rueidis.Client + client valkey.Client ttl time.Duration } -func NewAdapter(client rueidis.Client) Cmdable { +func NewAdapter(client valkey.Client) Cmdable { return &Compat{client: client, maxp: runtime.GOMAXPROCS(0)} } @@ -577,7 +577,7 @@ type FilterBy struct { } func (c *Compat) CommandList(ctx context.Context, filter FilterBy) *StringSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if filter.Module != "" { resp = c.client.Do(ctx, c.client.B().CommandList().FilterbyModuleName(filter.Module).Build()) } else if filter.Pattern != "" { @@ -694,7 +694,7 @@ func (c *Compat) ExpireLT(ctx context.Context, key string, seconds time.Duration func (c *Compat) Keys(ctx context.Context, pattern string) *StringSliceCmd { var mu sync.Mutex ret := &StringSliceCmd{} - ret.err = c.doPrimaries(ctx, func(c rueidis.Client) error { + ret.err = c.doPrimaries(ctx, func(c valkey.Client) error { res, err := c.Do(ctx, c.B().Keys().Pattern(pattern).Build()).AsStrSlice() if err == nil { mu.Lock() @@ -707,7 +707,7 @@ func (c *Compat) Keys(ctx context.Context, pattern string) *StringSliceCmd { } func (c *Compat) Migrate(ctx context.Context, host string, port int64, key string, db int64, timeout time.Duration) *StatusCmd { - var cmd rueidis.Completed + var cmd valkey.Completed cmd = c.client.B().Migrate().Host(host).Port(port).Key(key).DestinationDb(db).Timeout(formatSec(timeout)).Build() resp := c.client.Do(ctx, cmd) return newStatusCmd(resp) @@ -895,9 +895,9 @@ func (c *Compat) GetSet(ctx context.Context, key string, value any) *StringCmd { } // GetEx An expiration of zero removes the TTL associated with the key (i.e. GETEX key persist). -// Requires Redis >= 6.2.0. +// Requires Valkey >= 6.2.0. func (c *Compat) GetEx(ctx context.Context, key string, expiration time.Duration) *StringCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if expiration > 0 { if usePrecise(expiration) { resp = c.client.Do(ctx, c.client.B().Getex().Key(key).PxMilliseconds(formatMs(expiration)).Build()) @@ -974,7 +974,7 @@ func (c *Compat) MSetNX(ctx context.Context, values ...any) *BoolCmd { // // For more options, use SetArgs. func (c *Compat) Set(ctx context.Context, key string, value any, expiration time.Duration) *StatusCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if expiration > 0 { if usePrecise(expiration) { resp = c.client.Do(ctx, c.client.B().Set().Key(key).Value(str(value)).PxMilliseconds(formatMs(expiration)).Build()) @@ -1025,7 +1025,7 @@ func (c *Compat) SetEX(ctx context.Context, key string, value any, expiration ti } func (c *Compat) SetNX(ctx context.Context, key string, value any, expiration time.Duration) *BoolCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult switch expiration { case 0: @@ -1044,7 +1044,7 @@ func (c *Compat) SetNX(ctx context.Context, key string, value any, expiration ti } func (c *Compat) SetXX(ctx context.Context, key string, value any, expiration time.Duration) *BoolCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if expiration > 0 { if usePrecise(expiration) { resp = c.client.Do(ctx, c.client.B().Set().Key(key).Value(str(value)).Xx().PxMilliseconds(formatMs(expiration)).Build()) @@ -1072,7 +1072,7 @@ func (c *Compat) StrLen(ctx context.Context, key string) *IntCmd { } func (c *Compat) Copy(ctx context.Context, source string, destination string, db int64, replace bool) *IntCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if replace { resp = c.client.Do(ctx, c.client.B().Copy().Source(source).Destination(destination).Db(db).Replace().Build()) } else { @@ -1094,7 +1094,7 @@ func (c *Compat) SetBit(ctx context.Context, key string, offset int64, value int } func (c *Compat) BitCount(ctx context.Context, key string, bitCount *BitCount) *IntCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if bitCount == nil { resp = c.client.Do(ctx, c.client.B().Bitcount().Key(key).Build()) } else { @@ -1128,7 +1128,7 @@ func (c *Compat) BitOpNot(ctx context.Context, destKey string, key string) *IntC } func (c *Compat) BitPos(ctx context.Context, key string, bit int64, pos ...int64) *IntCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult switch len(pos) { case 0: resp = c.client.Do(ctx, c.client.B().Bitpos().Key(key).Bit(bit).Build()) @@ -1143,7 +1143,7 @@ func (c *Compat) BitPos(ctx context.Context, key string, bit int64, pos ...int64 } func (c *Compat) BitPosSpan(ctx context.Context, key string, bit, start, end int64, span string) *IntCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if strings.ToLower(span) == "bit" { resp = c.client.Do(ctx, c.client.B().Bitpos().Key(key).Bit(bit).Start(start).End(end).Bit().Build()) } else { @@ -1275,7 +1275,7 @@ func (c *Compat) HMGet(ctx context.Context, key string, fields ...string) *Slice return newSliceCmd(resp, false, fields...) } -// HSet requires Redis v4 for multiple field/value pairs support. +// HSet requires Valkey v4 for multiple field/value pairs support. func (c *Compat) HSet(ctx context.Context, key string, values ...any) *IntCmd { partial := c.client.B().Hset().Key(key).FieldValue() @@ -1289,7 +1289,7 @@ func (c *Compat) HSet(ctx context.Context, key string, values ...any) *IntCmd { return newIntCmd(resp) } -// HMSet is a deprecated version of HSet left for compatibility with Redis 3. +// HMSet is a deprecated version of HSet left for compatibility with Valkey 3. func (c *Compat) HMSet(ctx context.Context, key string, values ...any) *BoolCmd { partial := c.client.B().Hset().Key(key).FieldValue() @@ -1357,7 +1357,7 @@ func (c *Compat) LIndex(ctx context.Context, key string, index int64) *StringCmd } func (c *Compat) LInsert(ctx context.Context, key, op string, pivot, element any) *IntCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult switch strings.ToUpper(op) { case "BEFORE": resp = c.client.Do(ctx, c.client.B().Linsert().Key(key).Before().Pivot(str(pivot)).Element(str(element)).Build()) @@ -1701,7 +1701,7 @@ func (c *Compat) XRead(ctx context.Context, a XReadArgs) *XStreamSliceCmd { } cmd = cmd.Args("STREAMS") cmd = cmd.Keys(a.Streams[:len(a.Streams)/2]...).Args(a.Streams[len(a.Streams)/2:]...) - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if a.Block >= 0 { resp = c.client.Do(ctx, cmd.Blocking()) } else { @@ -1764,7 +1764,7 @@ func (c *Compat) XReadGroup(ctx context.Context, a XReadGroupArgs) *XStreamSlice } cmd = cmd.Args("STREAMS") cmd = cmd.Keys(a.Streams[:len(a.Streams)/2]...).Args(a.Streams[len(a.Streams)/2:]...) - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if a.Block >= 0 { resp = c.client.Do(ctx, cmd.Blocking()) } else { @@ -1811,7 +1811,7 @@ func (c *Compat) XClaimJustID(ctx context.Context, a XClaimArgs) *StringSliceCmd } func (c *Compat) XAutoClaim(ctx context.Context, a XAutoClaimArgs) *XAutoClaimCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if a.Count > 0 { resp = c.client.Do(ctx, c.client.B().Xautoclaim().Key(a.Stream).Group(a.Group).Consumer(a.Consumer).MinIdleTime(strconv.FormatInt(formatMs(a.MinIdle), 10)).Start(a.Start).Count(a.Count).Build()) } else { @@ -1821,7 +1821,7 @@ func (c *Compat) XAutoClaim(ctx context.Context, a XAutoClaimArgs) *XAutoClaimCm } func (c *Compat) XAutoClaimJustID(ctx context.Context, a XAutoClaimArgs) *XAutoClaimJustIDCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if a.Count > 0 { resp = c.client.Do(ctx, c.client.B().Xautoclaim().Key(a.Stream).Group(a.Group).Consumer(a.Consumer).MinIdleTime(strconv.FormatInt(formatMs(a.MinIdle), 10)).Start(a.Start).Count(a.Count).Justid().Build()) } else { @@ -1830,13 +1830,13 @@ func (c *Compat) XAutoClaimJustID(ctx context.Context, a XAutoClaimArgs) *XAutoC return newXAutoClaimJustIDCmd(resp) } -// xTrim If approx is true, add the "~" parameter, otherwise it is the default "=" (redis default). +// xTrim If approx is true, add the "~" parameter, otherwise it is the default "=" (valkey default). // example: // // XTRIM key MAXLEN/MINID threshold LIMIT limit. // XTRIM key MAXLEN/MINID ~ threshold LIMIT limit. // -// The redis-server version is lower than 6.2, please set limit to 0. +// The valkey-server version is lower than 6.2, please set limit to 0. func (c *Compat) xTrim(ctx context.Context, key, strategy string, approx bool, threshold string, limit int64) *IntCmd { cmd := c.client.B().Arbitrary("XTRIM").Keys(key).Args(strategy) @@ -1901,14 +1901,14 @@ func (c *Compat) XInfoConsumers(ctx context.Context, key, group string) *XInfoCo return newXInfoConsumersCmd(resp) } -// BZPopMax Redis `BZPOPMAX key [key ...] timeout` command. +// BZPopMax Valkey `BZPOPMAX key [key ...] timeout` command. func (c *Compat) BZPopMax(ctx context.Context, timeout time.Duration, keys ...string) *ZWithKeyCmd { cmd := c.client.B().Bzpopmax().Key(keys...).Timeout(float64(formatSec(timeout))).Build() resp := c.client.Do(ctx, cmd) return newZWithKeyCmd(resp) } -// BZPopMin Redis `BZPOPMIN key [key ...] timeout` command. +// BZPopMin Valkey `BZPOPMIN key [key ...] timeout` command. func (c *Compat) BZPopMin(ctx context.Context, timeout time.Duration, keys ...string) *ZWithKeyCmd { cmd := c.client.B().Bzpopmin().Key(keys...).Timeout(float64(formatSec(timeout))).Build() resp := c.client.Do(ctx, cmd) @@ -1924,17 +1924,17 @@ func (c *Compat) BZMPop(ctx context.Context, timeout time.Duration, order string return newZSliceWithKeyCmd(c.client.Do(ctx, cmd.Blocking())) } -// ZAdd Redis `ZADD key score member [score member ...]` command. +// ZAdd Valkey `ZADD key score member [score member ...]` command. func (c *Compat) ZAdd(ctx context.Context, key string, members ...Z) *IntCmd { return newIntCmd(c.zAddArgs(ctx, key, false, ZAddArgs{Members: members})) } -// ZAddNX Redis `ZADD key NX score member [score member ...]` command. +// ZAddNX Valkey `ZADD key NX score member [score member ...]` command. func (c *Compat) ZAddNX(ctx context.Context, key string, members ...Z) *IntCmd { return newIntCmd(c.zAddArgs(ctx, key, false, ZAddArgs{Members: members, NX: true})) } -// ZAddXX Redis `ZADD key XX score member [score member ...]` command. +// ZAddXX Valkey `ZADD key XX score member [score member ...]` command. func (c *Compat) ZAddXX(ctx context.Context, key string, members ...Z) *IntCmd { return newIntCmd(c.zAddArgs(ctx, key, false, ZAddArgs{Members: members, XX: true})) } @@ -1947,7 +1947,7 @@ func (c *Compat) ZAddGT(ctx context.Context, key string, members ...Z) *IntCmd { return newIntCmd(c.zAddArgs(ctx, key, false, ZAddArgs{Members: members, GT: true})) } -func (c *Compat) zAddArgs(ctx context.Context, key string, incr bool, args ZAddArgs) rueidis.RedisResult { +func (c *Compat) zAddArgs(ctx context.Context, key string, incr bool, args ZAddArgs) valkey.ValkeyResult { cmd := c.client.B().Arbitrary("ZADD").Keys(key) // The GT, LT and NX options are mutually exclusive. if args.NX { @@ -2053,7 +2053,7 @@ func (c *Compat) ZMScore(ctx context.Context, key string, members ...string) *Fl } func (c *Compat) ZPopMax(ctx context.Context, key string, count ...int64) *ZSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult switch len(count) { case 0: resp = c.client.Do(ctx, c.client.B().Zpopmax().Key(key).Build()) @@ -2067,7 +2067,7 @@ func (c *Compat) ZPopMax(ctx context.Context, key string, count ...int64) *ZSlic } func (c *Compat) ZPopMin(ctx context.Context, key string, count ...int64) *ZSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult switch len(count) { case 0: resp = c.client.Do(ctx, c.client.B().Zpopmin().Key(key).Build()) @@ -2080,7 +2080,7 @@ func (c *Compat) ZPopMin(ctx context.Context, key string, count ...int64) *ZSlic return newZSliceSingleCmd(resp) } -func (c *Compat) zRangeArgs(withScores bool, z ZRangeArgs) rueidis.Completed { +func (c *Compat) zRangeArgs(withScores bool, z ZRangeArgs) valkey.Completed { cmd := c.client.B().Arbitrary("ZRANGE").Keys(z.Key) if z.Rev && (z.ByScore || z.ByLex) { cmd = cmd.Args(str(z.Stop), str(z.Start)) @@ -2125,7 +2125,7 @@ func (c *Compat) ZRangeWithScores(ctx context.Context, key string, start, stop i } func (c *Compat) ZRangeByScore(ctx context.Context, key string, opt ZRangeBy) *StringSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.Do(ctx, c.client.B().Zrangebyscore().Key(key).Min(opt.Min).Max(opt.Max).Limit(opt.Offset, opt.Count).Build()) } else { @@ -2135,7 +2135,7 @@ func (c *Compat) ZRangeByScore(ctx context.Context, key string, opt ZRangeBy) *S } func (c *Compat) ZRangeByLex(ctx context.Context, key string, opt ZRangeBy) *StringSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.Do(ctx, c.client.B().Zrangebylex().Key(key).Min(opt.Min).Max(opt.Max).Limit(opt.Offset, opt.Count).Build()) } else { @@ -2145,7 +2145,7 @@ func (c *Compat) ZRangeByLex(ctx context.Context, key string, opt ZRangeBy) *Str } func (c *Compat) ZRangeByScoreWithScores(ctx context.Context, key string, opt ZRangeBy) *ZSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.Do(ctx, c.client.B().Zrangebyscore().Key(key).Min(opt.Min).Max(opt.Max).Withscores().Limit(opt.Offset, opt.Count).Build()) } else { @@ -2236,7 +2236,7 @@ func (c *Compat) ZRevRangeWithScores(ctx context.Context, key string, start, sto } func (c *Compat) ZRevRangeByScore(ctx context.Context, key string, opt ZRangeBy) *StringSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.Do(ctx, c.client.B().Zrevrangebyscore().Key(key).Max(opt.Max).Min(opt.Min).Limit(opt.Offset, opt.Count).Build()) } else { @@ -2246,7 +2246,7 @@ func (c *Compat) ZRevRangeByScore(ctx context.Context, key string, opt ZRangeBy) } func (c *Compat) ZRevRangeByLex(ctx context.Context, key string, opt ZRangeBy) *StringSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.Do(ctx, c.client.B().Zrevrangebylex().Key(key).Max(opt.Max).Min(opt.Min).Limit(opt.Offset, opt.Count).Build()) } else { @@ -2256,7 +2256,7 @@ func (c *Compat) ZRevRangeByLex(ctx context.Context, key string, opt ZRangeBy) * } func (c *Compat) ZRevRangeByScoreWithScores(ctx context.Context, key string, opt ZRangeBy) *ZSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.Do(ctx, c.client.B().Zrevrangebyscore().Key(key).Max(opt.Max).Min(opt.Min).Withscores().Limit(opt.Offset, opt.Count).Build()) } else { @@ -2340,25 +2340,25 @@ func (c *Compat) PFMerge(ctx context.Context, dest string, keys ...string) *Stat } func (c *Compat) BgRewriteAOF(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Bgrewriteaof().Build() }) } func (c *Compat) BgSave(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Bgsave().Build() }) } func (c *Compat) ClientKill(ctx context.Context, ipPort string) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ClientKill().IpPort(ipPort).Build() }) } func (c *Compat) ClientKillByFilter(ctx context.Context, keys ...string) *IntCmd { - return c.doIntCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doIntCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Arbitrary("CLIENT", "KILL").Args(keys...).Build() }) } @@ -2372,7 +2372,7 @@ func (c *Compat) ClientList(ctx context.Context) *StringCmd { func (c *Compat) ClientPause(ctx context.Context, dur time.Duration) *BoolCmd { var mu sync.Mutex ret := &BoolCmd{} - ret.err = c.doPrimaries(ctx, func(c rueidis.Client) error { + ret.err = c.doPrimaries(ctx, func(c valkey.Client) error { res, err := c.Do(ctx, c.B().ClientPause().Timeout(formatSec(dur)).Build()).ToString() if err == nil { mu.Lock() @@ -2387,7 +2387,7 @@ func (c *Compat) ClientPause(ctx context.Context, dur time.Duration) *BoolCmd { func (c *Compat) ClientUnpause(ctx context.Context) *BoolCmd { var mu sync.Mutex ret := &BoolCmd{} - ret.err = c.doPrimaries(ctx, func(c rueidis.Client) error { + ret.err = c.doPrimaries(ctx, func(c valkey.Client) error { res, err := c.Do(ctx, c.B().ClientUnpause().Build()).ToString() if err == nil { mu.Lock() @@ -2418,49 +2418,49 @@ func (c *Compat) ConfigGet(ctx context.Context, parameter string) *StringStringM } func (c *Compat) ConfigResetStat(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ConfigResetstat().Build() }) } func (c *Compat) ConfigSet(ctx context.Context, parameter, value string) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ConfigSet().ParameterValue().ParameterValue(parameter, value).Build() }) } func (c *Compat) ConfigRewrite(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ConfigRewrite().Build() }) } func (c *Compat) DBSize(ctx context.Context) *IntCmd { - return c.doIntCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doIntCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Dbsize().Build() }) } func (c *Compat) FlushAll(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Flushall().Build() }) } func (c *Compat) FlushAllAsync(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Flushall().Async().Build() }) } func (c *Compat) FlushDB(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Flushdb().Build() }) } func (c *Compat) FlushDBAsync(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Flushdb().Async().Build() }) } @@ -2478,25 +2478,25 @@ func (c *Compat) LastSave(ctx context.Context) *IntCmd { } func (c *Compat) Save(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Save().Build() }) } func (c *Compat) Shutdown(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Shutdown().Build() }) } func (c *Compat) ShutdownSave(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Shutdown().Save().Build() }) } func (c *Compat) ShutdownNoSave(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().Shutdown().Nosave().Build() }) } @@ -2526,7 +2526,7 @@ func (c *Compat) ReadWrite(ctx context.Context) *StatusCmd { } func (c *Compat) MemoryUsage(ctx context.Context, key string, samples ...int64) *IntCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult switch len(samples) { case 0: resp = c.client.Do(ctx, c.client.B().MemoryUsage().Key(key).Build()) @@ -2565,7 +2565,7 @@ func (c *Compat) ScriptExists(ctx context.Context, hashes ...string) *BoolSliceC for i := range hashes { ret.val[i] = true } - ret.err = c.doPrimaries(ctx, func(c rueidis.Client) error { + ret.err = c.doPrimaries(ctx, func(c valkey.Client) error { res, err := c.Do(ctx, c.B().ScriptExists().Sha1(hashes...).Build()).ToArray() if err == nil { mu.Lock() @@ -2582,55 +2582,55 @@ func (c *Compat) ScriptExists(ctx context.Context, hashes ...string) *BoolSliceC } func (c *Compat) ScriptFlush(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ScriptFlush().Build() }) } func (c *Compat) ScriptKill(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ScriptKill().Build() }) } func (c *Compat) ScriptLoad(ctx context.Context, script string) *StringCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ScriptLoad().Script(script).Build() }) } func (c *Compat) FunctionLoad(ctx context.Context, code string) *StringCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().FunctionLoad().FunctionCode(code).Build() }) } func (c *Compat) FunctionLoadReplace(ctx context.Context, code string) *StringCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().FunctionLoad().Replace().FunctionCode(code).Build() }) } func (c *Compat) FunctionDelete(ctx context.Context, libName string) *StringCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().FunctionDelete().LibraryName(libName).Build() }) } func (c *Compat) FunctionFlush(ctx context.Context) *StringCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().FunctionFlush().Build() }) } func (c *Compat) FunctionKill(ctx context.Context) *StringCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().FunctionKill().Build() }) } func (c *Compat) FunctionFlushAsync(ctx context.Context) *StringCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().FunctionFlush().Async().Build() }) } @@ -2651,7 +2651,7 @@ func (c *Compat) FunctionDump(ctx context.Context) *StringCmd { } func (c *Compat) FunctionRestore(ctx context.Context, libDump string) *StringCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().FunctionRestore().SerializedValue(libDump).Build() }) } @@ -2745,13 +2745,13 @@ func (c *Compat) ClusterReplicate(ctx context.Context, nodeID string) *StatusCmd } func (c *Compat) ClusterResetSoft(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ClusterReset().Soft().Build() }) } func (c *Compat) ClusterResetHard(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ClusterReset().Hard().Build() }) } @@ -2771,7 +2771,7 @@ func (c *Compat) ClusterKeySlot(ctx context.Context, key string) *IntCmd { func (c *Compat) ClusterGetKeysInSlot(ctx context.Context, slot int64, count int64) *StringSliceCmd { var mu sync.Mutex ret := &StringSliceCmd{} - ret.err = c.doPrimaries(ctx, func(c rueidis.Client) error { + ret.err = c.doPrimaries(ctx, func(c valkey.Client) error { cmd := c.B().ClusterGetkeysinslot().Slot(slot).Count(count).Build() resp, err := c.Do(ctx, cmd).AsStrSlice() if err == nil { @@ -2793,7 +2793,7 @@ func (c *Compat) ClusterCountFailureReports(ctx context.Context, nodeID string) func (c *Compat) ClusterCountKeysInSlot(ctx context.Context, slot int64) *IntCmd { var mu sync.Mutex ret := &IntCmd{} - ret.err = c.doPrimaries(ctx, func(c rueidis.Client) error { + ret.err = c.doPrimaries(ctx, func(c valkey.Client) error { cmd := c.B().ClusterCountkeysinslot().Slot(slot).Build() resp, err := c.Do(ctx, cmd).AsInt64() if err == nil { @@ -2819,7 +2819,7 @@ func (c *Compat) ClusterDelSlotsRange(ctx context.Context, min, max int64) *Stat } func (c *Compat) ClusterSaveConfig(ctx context.Context) *StatusCmd { - return c.doStringCmdPrimaries(ctx, func(c rueidis.Client) rueidis.Completed { + return c.doStringCmdPrimaries(ctx, func(c valkey.Client) valkey.Completed { return c.B().ClusterSaveconfig().Build() }) } @@ -2932,7 +2932,7 @@ func (c *Compat) GeoSearchStore(ctx context.Context, src, dest string, q GeoSear } func (c *Compat) GeoDist(ctx context.Context, key, member1, member2, unit string) *FloatCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult switch strings.ToUpper(unit) { case "M": resp = c.client.Do(ctx, c.client.B().Geodist().Key(key).Member1(member1).Member2(member2).M().Build()) @@ -2960,9 +2960,9 @@ func (c *Compat) ACLDryRun(ctx context.Context, username string, command ...any) return newStringCmd(resp) } -func (c *Compat) doPrimaries(ctx context.Context, fn func(c rueidis.Client) error) error { +func (c *Compat) doPrimaries(ctx context.Context, fn func(c valkey.Client) error) error { var firsterr atomic.Value - util.ParallelVals(c.maxp, c.client.Nodes(), func(client rueidis.Client) { + util.ParallelVals(c.maxp, c.client.Nodes(), func(client valkey.Client) { msgs, err := client.Do(ctx, client.B().Role().Build()).ToArray() if err == nil { if role, _ := msgs[0].ToString(); role == "master" { @@ -2979,10 +2979,10 @@ func (c *Compat) doPrimaries(ctx context.Context, fn func(c rueidis.Client) erro return nil } -func (c *Compat) doStringCmdPrimaries(ctx context.Context, fn func(c rueidis.Client) rueidis.Completed) *StringCmd { +func (c *Compat) doStringCmdPrimaries(ctx context.Context, fn func(c valkey.Client) valkey.Completed) *StringCmd { var mu sync.Mutex ret := &StringCmd{} - ret.err = c.doPrimaries(ctx, func(c rueidis.Client) error { + ret.err = c.doPrimaries(ctx, func(c valkey.Client) error { res, err := c.Do(ctx, fn(c)).ToString() if err == nil { mu.Lock() @@ -2994,10 +2994,10 @@ func (c *Compat) doStringCmdPrimaries(ctx context.Context, fn func(c rueidis.Cli return ret } -func (c *Compat) doIntCmdPrimaries(ctx context.Context, fn func(c rueidis.Client) rueidis.Completed) *IntCmd { +func (c *Compat) doIntCmdPrimaries(ctx context.Context, fn func(c valkey.Client) valkey.Completed) *IntCmd { var mu sync.Mutex ret := &IntCmd{} - ret.err = c.doPrimaries(ctx, func(c rueidis.Client) error { + ret.err = c.doPrimaries(ctx, func(c valkey.Client) error { res, err := c.Do(ctx, fn(c)).ToInt64() if err == nil { mu.Lock() @@ -4582,7 +4582,7 @@ func (c *Compat) JSONType(ctx context.Context, key, path string) *JSONSliceCmd { } func (c CacheCompat) BitCount(ctx context.Context, key string, bitCount *BitCount) *IntCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if bitCount == nil { resp = c.client.DoCache(ctx, c.client.B().Bitcount().Key(key).Cache(), c.ttl) } else { @@ -4592,7 +4592,7 @@ func (c CacheCompat) BitCount(ctx context.Context, key string, bitCount *BitCoun } func (c CacheCompat) BitPos(ctx context.Context, key string, bit int64, pos ...int64) *IntCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult switch len(pos) { case 0: resp = c.client.DoCache(ctx, c.client.B().Bitpos().Key(key).Bit(bit).Cache(), c.ttl) @@ -4607,7 +4607,7 @@ func (c CacheCompat) BitPos(ctx context.Context, key string, bit int64, pos ...i } func (c CacheCompat) BitPosSpan(ctx context.Context, key string, bit, start, end int64, span string) *IntCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if strings.ToLower(span) == "bit" { resp = c.client.DoCache(ctx, c.client.B().Bitpos().Key(key).Bit(bit).Start(start).End(end).Bit().Cache(), c.ttl) } else { @@ -4632,7 +4632,7 @@ func (c CacheCompat) FCallRO(ctx context.Context, function string, keys []string } func (c CacheCompat) GeoDist(ctx context.Context, key, member1, member2, unit string) *FloatCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult switch strings.ToUpper(unit) { case "M": resp = c.client.DoCache(ctx, c.client.B().Geodist().Key(key).Member1(member1).Member2(member2).M().Cache(), c.ttl) @@ -4667,7 +4667,7 @@ func (c CacheCompat) GeoRadius(ctx context.Context, key string, longitude, latit panic("GeoRadius does not support Store or StoreDist") } cmd = cmd.Args(query.args()...) - resp := c.client.DoCache(ctx, rueidis.Cacheable(cmd.Build()), c.ttl) + resp := c.client.DoCache(ctx, valkey.Cacheable(cmd.Build()), c.ttl) return newGeoLocationCmd(resp) } @@ -4678,14 +4678,14 @@ func (c CacheCompat) GeoRadiusByMember(ctx context.Context, key, member string, panic("GeoRadiusByMember does not support Store or StoreDist") } cmd = cmd.Args(query.args()...) - resp := c.client.DoCache(ctx, rueidis.Cacheable(cmd.Build()), c.ttl) + resp := c.client.DoCache(ctx, valkey.Cacheable(cmd.Build()), c.ttl) return newGeoLocationCmd(resp) } func (c CacheCompat) GeoSearch(ctx context.Context, key string, q GeoSearchQuery) *StringSliceCmd { cmd := c.client.B().Arbitrary("GEOSEARCH").Keys(key) cmd = cmd.Args(q.args()...) - resp := c.client.DoCache(ctx, rueidis.Cacheable(cmd.Build()), c.ttl) + resp := c.client.DoCache(ctx, valkey.Cacheable(cmd.Build()), c.ttl) return newStringSliceCmd(resp) } @@ -4769,7 +4769,7 @@ func (c CacheCompat) LPos(ctx context.Context, key string, element string, a LPo if a.MaxLen != 0 { cmd = cmd.Args("MAXLEN", strconv.FormatInt(a.MaxLen, 10)) } - resp := c.client.DoCache(ctx, rueidis.Cacheable(cmd.Build()), c.ttl) + resp := c.client.DoCache(ctx, valkey.Cacheable(cmd.Build()), c.ttl) return newIntCmd(resp) } @@ -4830,7 +4830,7 @@ func (c CacheCompat) SortRO(ctx context.Context, key string, sort Sort) *StringS if sort.Alpha { cmd = cmd.Args("ALPHA") } - resp := c.client.DoCache(ctx, rueidis.Cacheable(cmd.Build()), c.ttl) + resp := c.client.DoCache(ctx, valkey.Cacheable(cmd.Build()), c.ttl) return newStringSliceCmd(resp) } @@ -4876,7 +4876,7 @@ func (c CacheCompat) ZMScore(ctx context.Context, key string, members ...string) return newFloatSliceCmd(resp) } -func (c CacheCompat) zRangeArgs(withScores bool, z ZRangeArgs) rueidis.Cacheable { +func (c CacheCompat) zRangeArgs(withScores bool, z ZRangeArgs) valkey.Cacheable { cmd := c.client.B().Arbitrary("ZRANGE").Keys(z.Key) if z.Rev && (z.ByScore || z.ByLex) { cmd = cmd.Args(str(z.Stop), str(z.Start)) @@ -4897,7 +4897,7 @@ func (c CacheCompat) zRangeArgs(withScores bool, z ZRangeArgs) rueidis.Cacheable if withScores { cmd = cmd.Args("WITHSCORES") } - return rueidis.Cacheable(cmd.Build()) + return valkey.Cacheable(cmd.Build()) } func (c CacheCompat) ZRangeWithScores(ctx context.Context, key string, start, stop int64) *ZSliceCmd { @@ -4911,7 +4911,7 @@ func (c CacheCompat) ZRangeWithScores(ctx context.Context, key string, start, st } func (c CacheCompat) ZRangeByScore(ctx context.Context, key string, opt ZRangeBy) *StringSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.DoCache(ctx, c.client.B().Zrangebyscore().Key(key).Min(opt.Min).Max(opt.Max).Limit(opt.Offset, opt.Count).Cache(), c.ttl) } else { @@ -4921,7 +4921,7 @@ func (c CacheCompat) ZRangeByScore(ctx context.Context, key string, opt ZRangeBy } func (c CacheCompat) ZRangeByLex(ctx context.Context, key string, opt ZRangeBy) *StringSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.DoCache(ctx, c.client.B().Zrangebylex().Key(key).Min(opt.Min).Max(opt.Max).Limit(opt.Offset, opt.Count).Cache(), c.ttl) } else { @@ -4931,7 +4931,7 @@ func (c CacheCompat) ZRangeByLex(ctx context.Context, key string, opt ZRangeBy) } func (c CacheCompat) ZRangeByScoreWithScores(ctx context.Context, key string, opt ZRangeBy) *ZSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.DoCache(ctx, c.client.B().Zrangebyscore().Key(key).Min(opt.Min).Max(opt.Max).Withscores().Limit(opt.Offset, opt.Count).Cache(), c.ttl) } else { @@ -4977,7 +4977,7 @@ func (c CacheCompat) ZRevRangeWithScores(ctx context.Context, key string, start, } func (c CacheCompat) ZRevRangeByScore(ctx context.Context, key string, opt ZRangeBy) *StringSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.DoCache(ctx, c.client.B().Zrevrangebyscore().Key(key).Max(opt.Max).Min(opt.Min).Limit(opt.Offset, opt.Count).Cache(), c.ttl) } else { @@ -4987,7 +4987,7 @@ func (c CacheCompat) ZRevRangeByScore(ctx context.Context, key string, opt ZRang } func (c CacheCompat) ZRevRangeByLex(ctx context.Context, key string, opt ZRangeBy) *StringSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.DoCache(ctx, c.client.B().Zrevrangebylex().Key(key).Max(opt.Max).Min(opt.Min).Limit(opt.Offset, opt.Count).Cache(), c.ttl) } else { @@ -4997,7 +4997,7 @@ func (c CacheCompat) ZRevRangeByLex(ctx context.Context, key string, opt ZRangeB } func (c CacheCompat) ZRevRangeByScoreWithScores(ctx context.Context, key string, opt ZRangeBy) *ZSliceCmd { - var resp rueidis.RedisResult + var resp valkey.ValkeyResult if opt.Offset != 0 || opt.Count != 0 { resp = c.client.DoCache(ctx, c.client.B().Zrevrangebyscore().Key(key).Max(opt.Max).Min(opt.Min).Withscores().Limit(opt.Offset, opt.Count).Cache(), c.ttl) } else { @@ -5205,7 +5205,7 @@ func str(arg any) string { return strconv.FormatInt(v.Nanoseconds(), 10) case encoding.BinaryMarshaler: if data, err := v.MarshalBinary(); err == nil { - return rueidis.BinaryString(data) + return valkey.BinaryString(data) } } return fmt.Sprint(arg) @@ -5264,7 +5264,7 @@ func appendStructField(v reflect.Value) []string { typ := v.Type() dst := make([]string, 0, typ.NumField()) for i := 0; i < typ.NumField(); i++ { - tag := typ.Field(i).Tag.Get("redis") + tag := typ.Field(i).Tag.Get("valkey") if tag == "" || tag == "-" { continue } diff --git a/rueidiscompat/adapter_test.go b/valkeycompat/adapter_test.go similarity index 98% rename from rueidiscompat/adapter_test.go rename to valkeycompat/adapter_test.go index 65700f0..ebb31b9 100644 --- a/rueidiscompat/adapter_test.go +++ b/valkeycompat/adapter_test.go @@ -24,7 +24,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package rueidiscompat +package valkeycompat import ( "context" @@ -39,14 +39,14 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) type TimeValue struct { time.Time } -func (t *TimeValue) ScanRedis(s string) (err error) { +func (t *TimeValue) ScanValkey(s string) (err error) { t.Time, err = time.Parse(time.RFC3339Nano, s) return } @@ -59,10 +59,10 @@ func TestAdapter(t *testing.T) { var ( err error ctx context.Context - clientresp2 rueidis.Client - clusterresp2 rueidis.Client - clientresp3 rueidis.Client - clusterresp3 rueidis.Client + clientresp2 valkey.Client + clusterresp2 valkey.Client + clientresp3 valkey.Client + clusterresp3 valkey.Client adapterresp2 Cmdable adaptercluster2 Cmdable adapterresp3 Cmdable @@ -71,27 +71,27 @@ var ( var _ = BeforeSuite(func() { ctx = context.Background() - clientresp3, err = rueidis.NewClient(rueidis.ClientOption{ + clientresp3, err = valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6378"}, - ClientName: "rueidis", + ClientName: "valkey", }) Expect(err).NotTo(HaveOccurred()) - clusterresp3, err = rueidis.NewClient(rueidis.ClientOption{ + clusterresp3, err = valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:7010"}, - ClientName: "rueidis", + ClientName: "valkey", }) Expect(err).NotTo(HaveOccurred()) adapterresp3 = NewAdapter(clientresp3) adaptercluster3 = NewAdapter(clusterresp3) - clientresp2, err = rueidis.NewClient(rueidis.ClientOption{ + clientresp2, err = valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6356"}, - ClientName: "rueidis", + ClientName: "valkey", DisableCache: true, }) Expect(err).NotTo(HaveOccurred()) - clusterresp2, err = rueidis.NewClient(rueidis.ClientOption{ + clusterresp2, err = valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:7007"}, - ClientName: "rueidis", + ClientName: "valkey", DisableCache: true, }) Expect(err).NotTo(HaveOccurred()) @@ -263,7 +263,7 @@ func testAdapter(resp3 bool) { It("should ClientGetName", func() { r := adapter.ClientGetName(ctx) Expect(r.Err()).NotTo(HaveOccurred()) - Expect(r.Val()).To(Equal("rueidis")) + Expect(r.Val()).To(Equal("valkey")) }) It("should ConfigGet", func() { @@ -443,7 +443,7 @@ func testAdapter(resp3 bool) { Describe("debugging", func() { It("should MemoryUsage", func() { err := adapter.MemoryUsage(ctx, "foo").Err() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) err = adapter.Set(ctx, "foo", "bar", 0).Err() Expect(err).NotTo(HaveOccurred()) @@ -674,7 +674,7 @@ func testAdapter(resp3 bool) { idleTime := adapter.ObjectIdleTime(ctx, "key") Expect(idleTime.Err()).NotTo(HaveOccurred()) - // Redis returned milliseconds/1000, which may cause ObjectIdleTime to be at a critical value, + // Valkey returned milliseconds/1000, which may cause ObjectIdleTime to be at a critical value, // should be +1s to deal with the critical value problem. // if too much time (>1s) is used during command execution, it may also cause the test to fail. // so the ObjectIdleTime result should be <=now-start+1s @@ -759,7 +759,7 @@ func testAdapter(resp3 bool) { It("should RandomKey", func() { randomKey := adapter.RandomKey(ctx) - Expect(rueidis.IsRedisNil(randomKey.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(randomKey.Err())).To(BeTrue()) Expect(randomKey.Val()).To(Equal("")) set := adapter.Set(ctx, "key", "hello", 0) @@ -1318,7 +1318,7 @@ func testAdapter(resp3 bool) { It("should Get", func() { get := adapter.Get(ctx, "_") - Expect(rueidis.IsRedisNil(get.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(get.Err())).To(BeTrue()) Expect(get.Val()).To(Equal("")) set := adapter.Set(ctx, "key", "hello", 0) @@ -1435,7 +1435,7 @@ func testAdapter(resp3 bool) { Expect(getDel.Val()).To(Equal("value")) get := adapter.Get(ctx, "key") - Expect(rueidis.IsRedisNil(get.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(get.Err())).To(BeTrue()) }) } @@ -1498,11 +1498,11 @@ func testAdapter(resp3 bool) { // MSet struct type set struct { - Set1 string `redis:"set1"` - Set2 int16 `redis:"set2"` - Set3 time.Duration `redis:"set3"` - Set4 interface{} `redis:"set4"` - Set5 map[string]interface{} `redis:"-"` + Set1 string `valkey:"set1"` + Set2 int16 `valkey:"set2"` + Set3 time.Duration `valkey:"set3"` + Set4 interface{} `valkey:"set4"` + Set5 map[string]interface{} `valkey:"-"` } mSet = adapter.MSet(ctx, &set{ Set1: "val1", @@ -1534,9 +1534,9 @@ func testAdapter(resp3 bool) { Expect(res.Err()).NotTo(HaveOccurred()) type data struct { - Key1 string `redis:"key1"` - Key2 int `redis:"key2"` - Time TimeValue `redis:"time"` + Key1 string `valkey:"key1"` + Key2 int `valkey:"key2"` + Time TimeValue `valkey:"time"` } var d data Expect(res.Scan(&d)).NotTo(HaveOccurred()) @@ -1561,11 +1561,11 @@ func testAdapter(resp3 bool) { // set struct // MSet struct type set struct { - Set1 string `redis:"set1"` - Set2 int16 `redis:"set2"` - Set3 time.Duration `redis:"set3"` - Set4 interface{} `redis:"set4"` - Set5 map[string]interface{} `redis:"-"` + Set1 string `valkey:"set1"` + Set2 int16 `valkey:"set2"` + Set3 time.Duration `valkey:"set3"` + Set4 interface{} `valkey:"set4"` + Set5 map[string]interface{} `valkey:"-"` } mSetNX = adapter.MSetNX(ctx, &set{ Set1: "val1", @@ -1595,7 +1595,7 @@ func testAdapter(resp3 bool) { Expect(val).To(Equal("hello")) Eventually(func() bool { - return rueidis.IsRedisNil(adapter.Get(ctx, "key").Err()) + return valkey.IsValkeyNil(adapter.Get(ctx, "key").Err()) }, "2s", "100ms").Should(BeTrue()) }) @@ -1623,13 +1623,13 @@ func testAdapter(resp3 bool) { args := SetArgs{ ExpireAt: time.Now().AddDate(-3, 1, 1), } - // redis accepts a timestamp less than the current date + // valkey accepts a timestamp less than the current date // but returns nil when trying to get the key err := adapter.SetArgs(ctx, "key", "hello", args).Err() Expect(err).NotTo(HaveOccurred()) val, err := adapter.Get(ctx, "key").Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(val).To(Equal("")) }) @@ -1665,7 +1665,7 @@ func testAdapter(resp3 bool) { Mode: "nx", } val, err := adapter.SetArgs(ctx, "key", "hello", args).Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(val).To(Equal("")) }) @@ -1688,7 +1688,7 @@ func testAdapter(resp3 bool) { Expect(val).To(Equal("OK")) Eventually(func() bool { - return rueidis.IsRedisNil(adapter.Get(ctx, "key").Err()) + return valkey.IsValkeyNil(adapter.Get(ctx, "key").Err()) }, "1s", "100ms").Should(BeTrue()) }) @@ -1701,7 +1701,7 @@ func testAdapter(resp3 bool) { Mode: "nx", } val, err := adapter.SetArgs(ctx, "key", "world", args).Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(val).To(Equal("")) }) @@ -1710,7 +1710,7 @@ func testAdapter(resp3 bool) { Mode: "xx", } val, err := adapter.SetArgs(ctx, "key", "world", args).Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(val).To(Equal("")) }) @@ -1747,7 +1747,7 @@ func testAdapter(resp3 bool) { } val, err := adapter.SetArgs(ctx, "key", "world", args).Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(val).To(Equal("")) }) @@ -1759,7 +1759,7 @@ func testAdapter(resp3 bool) { } val, err := adapter.SetArgs(ctx, "key", "world", args).Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(val).To(Equal("")) }) @@ -1778,7 +1778,7 @@ func testAdapter(resp3 bool) { Expect(val).To(Equal("hello")) Eventually(func() bool { - return rueidis.IsRedisNil(adapter.Get(ctx, "key").Err()) + return valkey.IsValkeyNil(adapter.Get(ctx, "key").Err()) }, "1s", "100ms").Should(BeTrue()) }) @@ -1788,7 +1788,7 @@ func testAdapter(resp3 bool) { } val, err := adapter.SetArgs(ctx, "key", "hello", args).Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(val).To(Equal("")) }) @@ -1832,7 +1832,7 @@ func testAdapter(resp3 bool) { Expect(val).To(Equal("hello")) Eventually(func() bool { - return rueidis.IsRedisNil(adapter.Get(ctx, "key").Err()) + return valkey.IsValkeyNil(adapter.Get(ctx, "key").Err()) }, "1s", "100ms").Should(BeTrue()) }) @@ -1855,7 +1855,7 @@ func testAdapter(resp3 bool) { Expect(val).To(Equal("hello")) Eventually(func() bool { - return rueidis.IsRedisNil(adapter.Get(ctx, "foo").Err()) + return valkey.IsValkeyNil(adapter.Get(ctx, "foo").Err()) }, "2s", "100ms").Should(BeTrue()) }) @@ -1997,13 +1997,13 @@ func testAdapter(resp3 bool) { Expect(set.Err()).NotTo(HaveOccurred()) Expect(set.Val()).To(Equal("OK")) - range_ := adapter.SetRange(ctx, "key", 6, "Redis") + range_ := adapter.SetRange(ctx, "key", 6, "Valkey") Expect(range_.Err()).NotTo(HaveOccurred()) Expect(range_.Val()).To(Equal(int64(11))) get := adapter.Get(ctx, "key") Expect(get.Err()).NotTo(HaveOccurred()) - Expect(get.Val()).To(Equal("Hello Redis")) + Expect(get.Val()).To(Equal("Hello Valkey")) }) It("should StrLen", func() { @@ -2091,7 +2091,7 @@ func testAdapter(resp3 bool) { Expect(hGet.Val()).To(Equal("hello")) hGet = adapter.HGet(ctx, "hash", "key1") - Expect(rueidis.IsRedisNil(hGet.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(hGet.Err())).To(BeTrue()) Expect(hGet.Val()).To(Equal("")) }) @@ -2116,9 +2116,9 @@ func testAdapter(resp3 bool) { Expect(res.Err()).NotTo(HaveOccurred()) type data struct { - Key1 string `redis:"key1"` - Key2 int `redis:"key2"` - Time TimeValue `redis:"time"` + Key1 string `valkey:"key1"` + Key2 int `valkey:"key2"` + Time TimeValue `valkey:"time"` } var d data Expect(res.Scan(&d)).NotTo(HaveOccurred()) @@ -2131,9 +2131,9 @@ func testAdapter(resp3 bool) { })) type data2 struct { - Key1 string `redis:"key1"` - Key2 int `redis:"key2"` - Time time.Time `redis:"time"` + Key1 string `valkey:"key1"` + Key2 int `valkey:"key2"` + Time time.Time `valkey:"time"` } err = adapter.HSet(ctx, "hash", &data2{ Key1: "hello2", @@ -2253,14 +2253,14 @@ func testAdapter(resp3 bool) { // set struct // MSet struct type set struct { - Set1 string `redis:"set1"` - Set2 int16 `redis:"set2"` - Set3 time.Duration `redis:"set3"` - Set4 interface{} `redis:"set4"` - Set5 map[string]interface{} `redis:"-"` - Set6 string `redis:"set6,omitempty"` - Set7 *string `redis:"set7"` - Set8 *string `redis:"set8"` + Set1 string `valkey:"set1"` + Set2 int16 `valkey:"set2"` + Set3 time.Duration `valkey:"set3"` + Set4 interface{} `valkey:"set4"` + Set5 map[string]interface{} `valkey:"-"` + Set6 string `valkey:"set6,omitempty"` + Set7 *string `valkey:"set7"` + Set8 *string `valkey:"set8"` } str := "str" hSet = adapter.HSet(ctx, "hash", &set{ @@ -2428,7 +2428,7 @@ func testAdapter(resp3 bool) { It("should BLPop timeout", func() { val, err := adapter.BLPop(ctx, time.Second, "list1").Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(val).To(BeNil()) Expect(adapter.Ping(ctx).Err()).NotTo(HaveOccurred()) @@ -2478,7 +2478,7 @@ func testAdapter(resp3 bool) { It("should BRPopLPush", func() { _, err := adapter.BRPopLPush(ctx, "list1", "list2", time.Second).Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) err = adapter.RPush(ctx, "list1", "a", "b", "c").Err() Expect(err).NotTo(HaveOccurred()) @@ -2503,7 +2503,7 @@ func testAdapter(resp3 bool) { Expect(lIndex.Val()).To(Equal("World")) lIndex = adapter.LIndex(ctx, "list", 3) - Expect(rueidis.IsRedisNil(lIndex.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(lIndex.Err())).To(BeTrue()) Expect(lIndex.Val()).To(Equal("")) }) @@ -2588,7 +2588,7 @@ func testAdapter(resp3 bool) { Expect(val).To(Equal([]string{"a", "b", "c", "d"})) err = adapter.LMPop(ctx, "left", 10, "list1", "list2").Err() - Expect(err).To(Equal(rueidis.Nil)) + Expect(err).To(Equal(valkey.Nil)) err = adapter.Set(ctx, "list3", 1024, 0).Err() Expect(err).NotTo(HaveOccurred()) @@ -2664,7 +2664,7 @@ func testAdapter(resp3 bool) { It("should BLMPop timeout", func() { _, val, err := adapter.BLMPop(ctx, time.Second, "left", 1, "list1").Result() - Expect(err).To(Equal(rueidis.Nil)) + Expect(err).To(Equal(valkey.Nil)) Expect(val).To(BeNil()) Expect(adapter.Ping(ctx).Err()).NotTo(HaveOccurred()) @@ -2742,10 +2742,10 @@ func testAdapter(resp3 bool) { Expect(lPos.Val()).To(Equal(int64(1))) lPos = adapter.LPos(ctx, "list", "b", LPosArgs{Rank: 2, MaxLen: 1}) - Expect(rueidis.IsRedisNil(lPos.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(lPos.Err())).To(BeTrue()) lPos = adapter.LPos(ctx, "list", "z", LPosArgs{}) - Expect(rueidis.IsRedisNil(lPos.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(lPos.Err())).To(BeTrue()) }) It("should LPosCount", func() { @@ -3486,7 +3486,7 @@ func testAdapter(resp3 bool) { It("should BZPopMax timeout", func() { _, err := adapter.BZPopMax(ctx, time.Second, "zset1").Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(adapter.Ping(ctx).Err()).NotTo(HaveOccurred()) }) @@ -3562,7 +3562,7 @@ func testAdapter(resp3 bool) { It("should BZPopMin timeout", func() { _, err := adapter.BZPopMin(ctx, time.Second, "zset1").Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) Expect(adapter.Ping(ctx).Err()).NotTo(HaveOccurred()) }) @@ -4451,7 +4451,7 @@ func testAdapter(resp3 bool) { Expect(zRank.Val()).To(Equal(int64(2))) zRank = adapter.ZRank(ctx, "zset", "four") - Expect(rueidis.IsRedisNil(zRank.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(zRank.Err())).To(BeTrue()) Expect(zRank.Val()).To(Equal(int64(0))) }) @@ -4478,7 +4478,7 @@ func testAdapter(resp3 bool) { zRankWithScore = adapter.ZRankWithScore(ctx, "zset", "four") Expect(zRankWithScore.Err()).To(HaveOccurred()) - Expect(zRankWithScore.Err()).To(Equal(rueidis.Nil)) + Expect(zRankWithScore.Err()).To(Equal(valkey.Nil)) }) } @@ -4770,7 +4770,7 @@ func testAdapter(resp3 bool) { Expect(zRevRank.Val()).To(Equal(int64(2))) zRevRank = adapter.ZRevRank(ctx, "zset", "four") - Expect(rueidis.IsRedisNil(zRevRank.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(zRevRank.Err())).To(BeTrue()) Expect(zRevRank.Val()).To(Equal(int64(0))) }) @@ -4797,7 +4797,7 @@ func testAdapter(resp3 bool) { zRevRankWithScore = adapter.ZRevRankWithScore(ctx, "zset", "four") Expect(zRevRankWithScore.Err()).To(HaveOccurred()) - Expect(zRevRankWithScore.Err()).To(Equal(rueidis.Nil)) + Expect(zRevRankWithScore.Err()).To(Equal(valkey.Nil)) }) } @@ -5058,7 +5058,7 @@ func testAdapter(resp3 bool) { Values: map[string]any{"uno": "un"}, NoMkStream: true, }).Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) } id, err := adapter.XAdd(ctx, XAddArgs{ @@ -5333,7 +5333,7 @@ func testAdapter(resp3 bool) { })) _, err = adapter.XReadStreams(ctx, "stream", "3").Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) }) It("should XRead", func() { @@ -5358,7 +5358,7 @@ func testAdapter(resp3 bool) { Count: 1, Block: 100 * time.Millisecond, }).Result() - Expect(rueidis.IsRedisNil(err)).To(BeTrue()) + Expect(valkey.IsValkeyNil(err)).To(BeTrue()) }) Describe("group", func() { @@ -6052,8 +6052,8 @@ func testAdapter(resp3 bool) { }) It("should get geo distance with unit options", func() { - // From Redis CLI, note the difference in rounding in m vs - // km on Redis itself. + // From Valkey CLI, note the difference in rounding in m vs + // km on Valkey itself. // // GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" // GEODIST Sicily Palermo Catania m @@ -6603,7 +6603,7 @@ func testAdapterCache(resp3 bool) { local function f1(keys, args) local hash = keys[1] -- Get the key name - local time = redis.call('TIME')[1] -- Get the current time from the Redis server + local time = redis.call('TIME')[1] -- Get the current time from the Valkey server -- Add the current timestamp to the arguments that the user passed to the function, stored in args table.insert(args, '_updated_at') @@ -6779,7 +6779,7 @@ func testAdapterCache(resp3 bool) { LibraryNamePattern: "non_lib", WithCode: true, }).First() - Expect(err).To(Equal(rueidis.Nil)) + Expect(err).To(Equal(valkey.Nil)) }) It("Dump and restores all libraries", func() { @@ -7191,7 +7191,7 @@ func testAdapterCache(resp3 bool) { local function f1(keys, args) local hash = keys[1] -- Get the key name - local time = redis.call('TIME')[1] -- Get the current time from the Redis server + local time = redis.call('TIME')[1] -- Get the current time from the Valkey server -- Add the current timestamp to the arguments that the user passed to the function, stored in args table.insert(args, '_updated_at') @@ -7276,7 +7276,7 @@ func testAdapterCache(resp3 bool) { It("should Get", func() { get := adapter.Cache(time.Hour).Get(ctx, "_") - Expect(rueidis.IsRedisNil(get.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(get.Err())).To(BeTrue()) Expect(get.Val()).To(Equal("")) set := adapter.Set(ctx, "key", "hello", 0) @@ -7367,7 +7367,7 @@ func testAdapterCache(resp3 bool) { Expect(hGet.Val()).To(Equal("hello")) hGet = adapter.Cache(time.Hour).HGet(ctx, "hash", "key1") - Expect(rueidis.IsRedisNil(hGet.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(hGet.Err())).To(BeTrue()) Expect(hGet.Val()).To(Equal("")) }) @@ -7452,7 +7452,7 @@ func testAdapterCache(resp3 bool) { Expect(lIndex.Val()).To(Equal("World")) lIndex = adapter.Cache(time.Hour).LIndex(ctx, "list", 3) - Expect(rueidis.IsRedisNil(lIndex.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(lIndex.Err())).To(BeTrue()) Expect(lIndex.Val()).To(Equal("")) }) @@ -7490,10 +7490,10 @@ func testAdapterCache(resp3 bool) { Expect(lPos.Val()).To(Equal(int64(1))) lPos = adapter.Cache(time.Hour).LPos(ctx, "list", "b", LPosArgs{Rank: 2, MaxLen: 1}) - Expect(rueidis.IsRedisNil(lPos.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(lPos.Err())).To(BeTrue()) lPos = adapter.Cache(time.Hour).LPos(ctx, "list", "z", LPosArgs{}) - Expect(rueidis.IsRedisNil(lPos.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(lPos.Err())).To(BeTrue()) }) It("should LRange", func() { @@ -7926,7 +7926,7 @@ func testAdapterCache(resp3 bool) { Expect(zRank.Val()).To(Equal(int64(2))) zRank = adapter.Cache(time.Hour).ZRank(ctx, "zset", "four") - Expect(rueidis.IsRedisNil(zRank.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(zRank.Err())).To(BeTrue()) Expect(zRank.Val()).To(Equal(int64(0))) }) @@ -7952,7 +7952,7 @@ func testAdapterCache(resp3 bool) { zRankWithScore = adapter.Cache(time.Hour).ZRankWithScore(ctx, "zset", "four") Expect(zRankWithScore.Err()).To(HaveOccurred()) - Expect(zRankWithScore.Err()).To(Equal(rueidis.Nil)) + Expect(zRankWithScore.Err()).To(Equal(valkey.Nil)) }) It("should ZRevRange", func() { @@ -8150,7 +8150,7 @@ func testAdapterCache(resp3 bool) { Expect(zRevRank.Val()).To(Equal(int64(2))) zRevRank = adapter.Cache(time.Hour).ZRevRank(ctx, "zset", "four") - Expect(rueidis.IsRedisNil(zRevRank.Err())).To(BeTrue()) + Expect(valkey.IsValkeyNil(zRevRank.Err())).To(BeTrue()) Expect(zRevRank.Val()).To(Equal(int64(0))) }) @@ -8176,7 +8176,7 @@ func testAdapterCache(resp3 bool) { zRevRankWithScore = adapter.Cache(time.Hour).ZRevRankWithScore(ctx, "zset", "four") Expect(zRevRankWithScore.Err()).To(HaveOccurred()) - Expect(zRevRankWithScore.Err()).To(Equal(rueidis.Nil)) + Expect(zRevRankWithScore.Err()).To(Equal(valkey.Nil)) }) It("should ZScore", func() { @@ -8213,7 +8213,7 @@ func testAdapterCache(resp3 bool) { }})) _, _, err = adapter.ZMPop(ctx, "min", 1, "nosuchkey").Result() - Expect(err).To(Equal(rueidis.Nil)) + Expect(err).To(Equal(valkey.Nil)) err = adapter.ZAdd(ctx, "myzset", Z{Score: 1, Member: "one"}).Err() Expect(err).NotTo(HaveOccurred()) @@ -8380,7 +8380,7 @@ func testAdapterCache(resp3 bool) { It("should BZMPop timeout", func() { _, val, err := adapter.BZMPop(ctx, time.Second, "min", 1, "list1").Result() - Expect(err).To(Equal(rueidis.Nil)) + Expect(err).To(Equal(valkey.Nil)) Expect(val).To(BeNil()) Expect(adapter.Ping(ctx).Err()).NotTo(HaveOccurred()) @@ -8520,8 +8520,8 @@ func testAdapterCache(resp3 bool) { }) It("should get geo distance with unit options", func() { - // From Redis CLI, note the difference in rounding in m vs - // km on Redis itself. + // From Valkey CLI, note the difference in rounding in m vs + // km on Valkey itself. // // GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" // GEODIST Sicily Palermo Catania m @@ -9542,7 +9542,7 @@ func testAdapterCache(resp3 bool) { result, err = adapter.TSCreateWithArgs(ctx, "2", opt).Result() Expect(err).NotTo(HaveOccurred()) Expect(result).To(BeEquivalentTo("OK")) - opt = &TSOptions{Labels: map[string]string{"Redis": "Labs"}} + opt = &TSOptions{Labels: map[string]string{"Valkey": "Labs"}} result, err = adapter.TSCreateWithArgs(ctx, "3", opt).Result() Expect(err).NotTo(HaveOccurred()) Expect(result).To(BeEquivalentTo("OK")) @@ -9584,11 +9584,11 @@ func testAdapterCache(resp3 bool) { result, err = adapter.TSAddWithArgs(ctx, "2", 2, 3, opt).Result() Expect(err).NotTo(HaveOccurred()) Expect(result).To(BeEquivalentTo(2)) - opt = &TSOptions{Labels: map[string]string{"Redis": "Labs"}} + opt = &TSOptions{Labels: map[string]string{"Valkey": "Labs"}} result, err = adapter.TSAddWithArgs(ctx, "3", 3, 2, opt).Result() Expect(err).NotTo(HaveOccurred()) Expect(result).To(BeEquivalentTo(3)) - opt = &TSOptions{Labels: map[string]string{"Redis": "Labs", "Time": "Series"}, Retention: 10} + opt = &TSOptions{Labels: map[string]string{"Valkey": "Labs", "Time": "Series"}, Retention: 10} result, err = adapter.TSAddWithArgs(ctx, "4", 4, 2, opt).Result() Expect(err).NotTo(HaveOccurred()) Expect(result).To(BeEquivalentTo(4)) @@ -10815,8 +10815,8 @@ func testAdapterCache(resp3 bool) { cmd3 := adapter.JSONGet(ctx, "del1", "$") // go-redis's test assertion is wrong. // based on the result from redis/redis-stack:7.2.0-v3, - // cmd3.Err() should be rueidis.Nil, not nil - Expect(cmd3.Err()).To(Equal(rueidis.Nil)) + // cmd3.Err() should be valkey.Nil, not nil + Expect(cmd3.Err()).To(Equal(valkey.Nil)) Expect(cmd3.Val()).To(HaveLen(0)) }) diff --git a/rueidiscompat/command.go b/valkeycompat/command.go similarity index 90% rename from rueidiscompat/command.go rename to valkeycompat/command.go index f614597..0967bdd 100644 --- a/rueidiscompat/command.go +++ b/valkeycompat/command.go @@ -24,7 +24,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package rueidiscompat +package valkeycompat import ( "encoding/json" @@ -34,8 +34,8 @@ import ( "strconv" "time" - "github.com/redis/rueidis" - "github.com/redis/rueidis/internal/util" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/internal/util" ) type baseCmd[T any] struct { @@ -67,7 +67,7 @@ type Cmd struct { baseCmd[any] } -func newCmd(res rueidis.RedisResult) *Cmd { +func newCmd(res valkey.ValkeyResult) *Cmd { cmd := &Cmd{} val, err := res.ToAny() if err != nil { @@ -90,7 +90,7 @@ func toString(val any) (string, error) { case string: return val, nil default: - err := fmt.Errorf("redis: unexpected type=%T for String", val) + err := fmt.Errorf("valkey: unexpected type=%T for String", val) return "", err } } @@ -105,7 +105,7 @@ func (cmd *Cmd) Int() (int, error) { case string: return strconv.Atoi(val) default: - err := fmt.Errorf("redis: unexpected type=%T for Int", val) + err := fmt.Errorf("valkey: unexpected type=%T for Int", val) return 0, err } } @@ -124,7 +124,7 @@ func toInt64(val any) (int64, error) { case string: return strconv.ParseInt(val, 10, 64) default: - err := fmt.Errorf("redis: unexpected type=%T for Int64", val) + err := fmt.Errorf("valkey: unexpected type=%T for Int64", val) return 0, err } } @@ -143,7 +143,7 @@ func toUint64(val any) (uint64, error) { case string: return strconv.ParseUint(val, 10, 64) default: - err := fmt.Errorf("redis: unexpected type=%T for Uint64", val) + err := fmt.Errorf("valkey: unexpected type=%T for Uint64", val) return 0, err } } @@ -166,7 +166,7 @@ func toFloat32(val any) (float32, error) { } return f, nil default: - err := fmt.Errorf("redis: unexpected type=%T for Float32", val) + err := fmt.Errorf("valkey: unexpected type=%T for Float32", val) return 0, err } } @@ -185,7 +185,7 @@ func toFloat64(val any) (float64, error) { case string: return util.ToFloat64(val) default: - err := fmt.Errorf("redis: unexpected type=%T for Float64", val) + err := fmt.Errorf("valkey: unexpected type=%T for Float64", val) return 0, err } } @@ -204,7 +204,7 @@ func toBool(val any) (bool, error) { case string: return strconv.ParseBool(val) default: - err := fmt.Errorf("redis: unexpected type=%T for Bool", val) + err := fmt.Errorf("valkey: unexpected type=%T for Bool", val) return false, err } } @@ -217,7 +217,7 @@ func (cmd *Cmd) Slice() ([]any, error) { case []any: return val, nil default: - return nil, fmt.Errorf("redis: unexpected type=%T for Slice", val) + return nil, fmt.Errorf("valkey: unexpected type=%T for Slice", val) } } @@ -327,7 +327,7 @@ type StringCmd struct { baseCmd[string] } -func newStringCmd(res rueidis.RedisResult) *StringCmd { +func newStringCmd(res valkey.ValkeyResult) *StringCmd { cmd := &StringCmd{} val, err := res.ToString() cmd.SetErr(err) @@ -397,10 +397,10 @@ type BoolCmd struct { baseCmd[bool] } -func newBoolCmd(res rueidis.RedisResult) *BoolCmd { +func newBoolCmd(res valkey.ValkeyResult) *BoolCmd { cmd := &BoolCmd{} val, err := res.AsBool() - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { val = false err = nil } @@ -413,7 +413,7 @@ type IntCmd struct { baseCmd[int64] } -func newIntCmd(res rueidis.RedisResult) *IntCmd { +func newIntCmd(res valkey.ValkeyResult) *IntCmd { cmd := &IntCmd{} val, err := res.AsInt64() cmd.SetErr(err) @@ -429,7 +429,7 @@ type DurationCmd struct { baseCmd[time.Duration] } -func newDurationCmd(res rueidis.RedisResult, precision time.Duration) *DurationCmd { +func newDurationCmd(res valkey.ValkeyResult, precision time.Duration) *DurationCmd { cmd := &DurationCmd{} val, err := res.AsInt64() cmd.SetErr(err) @@ -443,7 +443,7 @@ func newDurationCmd(res rueidis.RedisResult, precision time.Duration) *DurationC type StatusCmd = StringCmd -func newStatusCmd(res rueidis.RedisResult) *StatusCmd { +func newStatusCmd(res valkey.ValkeyResult) *StatusCmd { cmd := &StatusCmd{} val, err := res.ToString() cmd.SetErr(err) @@ -458,7 +458,7 @@ type SliceCmd struct { // newSliceCmd returns SliceCmd according to input arguments, if the caller is JSONObjKeys, // set isJSONObjKeys to true. -func newSliceCmd(res rueidis.RedisResult, isJSONObjKeys bool, keys ...string) *SliceCmd { +func newSliceCmd(res valkey.ValkeyResult, isJSONObjKeys bool, keys ...string) *SliceCmd { cmd := &SliceCmd{keys: keys} arr, err := res.ToArray() if err != nil { @@ -494,7 +494,7 @@ func newSliceCmd(res rueidis.RedisResult, isJSONObjKeys bool, keys ...string) *S } // Scan scans the results from the map into a destination struct. The map keys -// are matched in the Redis struct fields by the `redis:"field"` tag. +// are matched in the Valkey struct fields by the `valkey:"field"` tag. // NOTE: result from JSON.ObjKeys should not call this. func (cmd *SliceCmd) Scan(dst any) error { if cmd.err != nil { @@ -507,7 +507,7 @@ type StringSliceCmd struct { baseCmd[[]string] } -func newStringSliceCmd(res rueidis.RedisResult) *StringSliceCmd { +func newStringSliceCmd(res valkey.ValkeyResult) *StringSliceCmd { cmd := &StringSliceCmd{} val, err := res.AsStrSlice() cmd.SetVal(val) @@ -520,7 +520,7 @@ type IntSliceCmd struct { val []int64 } -func newIntSliceCmd(res rueidis.RedisResult) *IntSliceCmd { +func newIntSliceCmd(res valkey.ValkeyResult) *IntSliceCmd { val, err := res.AsIntSlice() return &IntSliceCmd{val: val, err: err} } @@ -549,7 +549,7 @@ type BoolSliceCmd struct { baseCmd[[]bool] } -func newBoolSliceCmd(res rueidis.RedisResult) *BoolSliceCmd { +func newBoolSliceCmd(res valkey.ValkeyResult) *BoolSliceCmd { cmd := &BoolSliceCmd{} ints, err := res.AsIntSlice() if err != nil { @@ -568,7 +568,7 @@ type FloatSliceCmd struct { baseCmd[[]float64] } -func newFloatSliceCmd(res rueidis.RedisResult) *FloatSliceCmd { +func newFloatSliceCmd(res valkey.ValkeyResult) *FloatSliceCmd { cmd := &FloatSliceCmd{} val, err := res.AsFloatSlice() cmd.SetErr(err) @@ -580,7 +580,7 @@ type ZSliceCmd struct { baseCmd[[]Z] } -func newZSliceCmd(res rueidis.RedisResult) *ZSliceCmd { +func newZSliceCmd(res valkey.ValkeyResult) *ZSliceCmd { cmd := &ZSliceCmd{} scores, err := res.AsZScores() if err != nil { @@ -595,7 +595,7 @@ func newZSliceCmd(res rueidis.RedisResult) *ZSliceCmd { return cmd } -func newZSliceSingleCmd(res rueidis.RedisResult) *ZSliceCmd { +func newZSliceSingleCmd(res valkey.ValkeyResult) *ZSliceCmd { cmd := &ZSliceCmd{} s, err := res.AsZScore() if err != nil { @@ -610,7 +610,7 @@ type FloatCmd struct { baseCmd[float64] } -func newFloatCmd(res rueidis.RedisResult) *FloatCmd { +func newFloatCmd(res valkey.ValkeyResult) *FloatCmd { cmd := &FloatCmd{} val, err := res.AsFloat64() cmd.SetErr(err) @@ -624,7 +624,7 @@ type ScanCmd struct { cursor uint64 } -func newScanCmd(res rueidis.RedisResult) *ScanCmd { +func newScanCmd(res valkey.ValkeyResult) *ScanCmd { e, err := res.AsScanEntry() return &ScanCmd{cursor: e.Cursor, keys: e.Elements, err: err} } @@ -655,7 +655,7 @@ type KeyValueSliceCmd struct { baseCmd[[]KeyValue] } -func newKeyValueSliceCmd(res rueidis.RedisResult) *KeyValueSliceCmd { +func newKeyValueSliceCmd(res valkey.ValkeyResult) *KeyValueSliceCmd { cmd := &KeyValueSliceCmd{} arr, err := res.ToArray() for _, a := range arr { @@ -670,10 +670,10 @@ func newKeyValueSliceCmd(res rueidis.RedisResult) *KeyValueSliceCmd { type KeyValuesCmd struct { err error - val rueidis.KeyValues + val valkey.KeyValues } -func newKeyValuesCmd(res rueidis.RedisResult) *KeyValuesCmd { +func newKeyValuesCmd(res valkey.ValkeyResult) *KeyValuesCmd { ret := &KeyValuesCmd{} ret.val, ret.err = res.AsLMPop() return ret @@ -709,7 +709,7 @@ type KeyFlagsCmd struct { baseCmd[[]KeyFlags] } -func newKeyFlagsCmd(res rueidis.RedisResult) *KeyFlagsCmd { +func newKeyFlagsCmd(res valkey.ValkeyResult) *KeyFlagsCmd { ret := &KeyFlagsCmd{} if ret.err = res.Error(); ret.err == nil { kfs, _ := res.ToArray() @@ -730,7 +730,7 @@ type ZSliceWithKeyCmd struct { val []Z } -func newZSliceWithKeyCmd(res rueidis.RedisResult) *ZSliceWithKeyCmd { +func newZSliceWithKeyCmd(res valkey.ValkeyResult) *ZSliceWithKeyCmd { v, err := res.AsZMPop() if err != nil { return &ZSliceWithKeyCmd{err: err} @@ -767,7 +767,7 @@ type StringStringMapCmd struct { baseCmd[map[string]string] } -func newStringStringMapCmd(res rueidis.RedisResult) *StringStringMapCmd { +func newStringStringMapCmd(res valkey.ValkeyResult) *StringStringMapCmd { cmd := &StringStringMapCmd{} val, err := res.AsStrMap() cmd.SetErr(err) @@ -776,7 +776,7 @@ func newStringStringMapCmd(res rueidis.RedisResult) *StringStringMapCmd { } // Scan scans the results from the map into a destination struct. The map keys -// are matched in the Redis struct fields by the `redis:"field"` tag. +// are matched in the Valkey struct fields by the `valkey:"field"` tag. func (cmd *StringStringMapCmd) Scan(dest interface{}) error { if cmd.Err() != nil { return cmd.Err() @@ -800,7 +800,7 @@ type StringIntMapCmd struct { baseCmd[map[string]int64] } -func newStringIntMapCmd(res rueidis.RedisResult) *StringIntMapCmd { +func newStringIntMapCmd(res valkey.ValkeyResult) *StringIntMapCmd { cmd := &StringIntMapCmd{} val, err := res.AsIntMap() cmd.SetErr(err) @@ -812,7 +812,7 @@ type StringStructMapCmd struct { baseCmd[map[string]struct{}] } -func newStringStructMapCmd(res rueidis.RedisResult) *StringStructMapCmd { +func newStringStructMapCmd(res valkey.ValkeyResult) *StringStructMapCmd { cmd := &StringStructMapCmd{} strSlice, err := res.AsStrSlice() if err != nil { @@ -831,7 +831,7 @@ type XMessageSliceCmd struct { baseCmd[[]XMessage] } -func newXMessageSliceCmd(res rueidis.RedisResult) *XMessageSliceCmd { +func newXMessageSliceCmd(res valkey.ValkeyResult) *XMessageSliceCmd { cmd := &XMessageSliceCmd{} val, err := res.AsXRange() cmd.SetErr(err) @@ -842,7 +842,7 @@ func newXMessageSliceCmd(res rueidis.RedisResult) *XMessageSliceCmd { return cmd } -func newXMessage(r rueidis.XRangeEntry) XMessage { +func newXMessage(r valkey.XRangeEntry) XMessage { if r.FieldValues == nil { return XMessage{ID: r.ID, Values: nil} } @@ -862,7 +862,7 @@ type XStreamSliceCmd struct { baseCmd[[]XStream] } -func newXStreamSliceCmd(res rueidis.RedisResult) *XStreamSliceCmd { +func newXStreamSliceCmd(res valkey.ValkeyResult) *XStreamSliceCmd { cmd := &XStreamSliceCmd{} streams, err := res.AsXRead() if err != nil { @@ -892,7 +892,7 @@ type XPendingCmd struct { baseCmd[XPending] } -func newXPendingCmd(res rueidis.RedisResult) *XPendingCmd { +func newXPendingCmd(res valkey.ValkeyResult) *XPendingCmd { cmd := &XPendingCmd{} arr, err := res.ToArray() if err != nil { @@ -968,7 +968,7 @@ type XPendingExtCmd struct { baseCmd[[]XPendingExt] } -func newXPendingExtCmd(res rueidis.RedisResult) *XPendingExtCmd { +func newXPendingExtCmd(res valkey.ValkeyResult) *XPendingExtCmd { cmd := &XPendingExtCmd{} arrs, err := res.ToArray() if err != nil { @@ -1023,7 +1023,7 @@ type XAutoClaimCmd struct { val []XMessage } -func newXAutoClaimCmd(res rueidis.RedisResult) *XAutoClaimCmd { +func newXAutoClaimCmd(res valkey.ValkeyResult) *XAutoClaimCmd { arr, err := res.ToArray() if err != nil { return &XAutoClaimCmd{err: err} @@ -1073,7 +1073,7 @@ type XAutoClaimJustIDCmd struct { val []string } -func newXAutoClaimJustIDCmd(res rueidis.RedisResult) *XAutoClaimJustIDCmd { +func newXAutoClaimJustIDCmd(res valkey.ValkeyResult) *XAutoClaimJustIDCmd { arr, err := res.ToArray() if err != nil { return &XAutoClaimJustIDCmd{err: err} @@ -1126,7 +1126,7 @@ type XInfoGroupsCmd struct { baseCmd[[]XInfoGroup] } -func newXInfoGroupsCmd(res rueidis.RedisResult) *XInfoGroupsCmd { +func newXInfoGroupsCmd(res valkey.ValkeyResult) *XInfoGroupsCmd { cmd := &XInfoGroupsCmd{} arr, err := res.ToArray() if err != nil { @@ -1181,7 +1181,7 @@ type XInfoStreamCmd struct { baseCmd[XInfoStream] } -func newXInfoStreamCmd(res rueidis.RedisResult) *XInfoStreamCmd { +func newXInfoStreamCmd(res valkey.ValkeyResult) *XInfoStreamCmd { cmd := &XInfoStreamCmd{} kv, err := res.AsMap() if err != nil { @@ -1273,7 +1273,7 @@ type XInfoStreamFullCmd struct { baseCmd[XInfoStreamFull] } -func newXInfoStreamFullCmd(res rueidis.RedisResult) *XInfoStreamFullCmd { +func newXInfoStreamFullCmd(res valkey.ValkeyResult) *XInfoStreamFullCmd { cmd := &XInfoStreamFullCmd{} kv, err := res.AsMap() if err != nil { @@ -1324,7 +1324,7 @@ func newXInfoStreamFullCmd(res rueidis.RedisResult) *XInfoStreamFullCmd { return cmd } -func readStreamGroups(res rueidis.RedisMessage) ([]XInfoStreamGroup, error) { +func readStreamGroups(res valkey.ValkeyMessage) ([]XInfoStreamGroup, error) { arr, err := res.ToArray() if err != nil { return nil, err @@ -1368,7 +1368,7 @@ func readStreamGroups(res rueidis.RedisMessage) ([]XInfoStreamGroup, error) { return groups, nil } -func readXInfoStreamGroupPending(res rueidis.RedisMessage) ([]XInfoStreamGroupPending, error) { +func readXInfoStreamGroupPending(res valkey.ValkeyMessage) ([]XInfoStreamGroupPending, error) { arr, err := res.ToArray() if err != nil { return nil, err @@ -1405,7 +1405,7 @@ func readXInfoStreamGroupPending(res rueidis.RedisMessage) ([]XInfoStreamGroupPe return pending, nil } -func readXInfoStreamConsumers(res rueidis.RedisMessage) ([]XInfoStreamConsumer, error) { +func readXInfoStreamConsumers(res valkey.ValkeyMessage) ([]XInfoStreamConsumer, error) { arr, err := res.ToArray() if err != nil { return nil, err @@ -1472,7 +1472,7 @@ type XInfoConsumersCmd struct { baseCmd[[]XInfoConsumer] } -func newXInfoConsumersCmd(res rueidis.RedisResult) *XInfoConsumersCmd { +func newXInfoConsumersCmd(res valkey.ValkeyResult) *XInfoConsumersCmd { cmd := &XInfoConsumersCmd{} arr, err := res.ToArray() if err != nil { @@ -1526,7 +1526,7 @@ type ZWithKeyCmd struct { baseCmd[ZWithKey] } -func newZWithKeyCmd(res rueidis.RedisResult) *ZWithKeyCmd { +func newZWithKeyCmd(res valkey.ValkeyResult) *ZWithKeyCmd { cmd := &ZWithKeyCmd{} arr, err := res.ToArray() if err != nil { @@ -1566,7 +1566,7 @@ type RankWithScoreCmd struct { baseCmd[RankScore] } -func newRankWithScoreCmd(res rueidis.RedisResult) *RankWithScoreCmd { +func newRankWithScoreCmd(res valkey.ValkeyResult) *RankWithScoreCmd { ret := &RankWithScoreCmd{} if ret.err = res.Error(); ret.err == nil { vs, _ := res.ToArray() @@ -1582,7 +1582,7 @@ type TimeCmd struct { baseCmd[time.Time] } -func newTimeCmd(res rueidis.RedisResult) *TimeCmd { +func newTimeCmd(res valkey.ValkeyResult) *TimeCmd { cmd := &TimeCmd{} arr, err := res.ToArray() if err != nil { @@ -1622,7 +1622,7 @@ type ClusterSlotsCmd struct { baseCmd[[]ClusterSlot] } -func newClusterSlotsCmd(res rueidis.RedisResult) *ClusterSlotsCmd { +func newClusterSlotsCmd(res valkey.ValkeyResult) *ClusterSlotsCmd { cmd := &ClusterSlotsCmd{} arr, err := res.ToArray() if err != nil { @@ -1691,7 +1691,7 @@ func newClusterSlotsCmd(res rueidis.RedisResult) *ClusterSlotsCmd { return cmd } -func newClusterShardsCmd(res rueidis.RedisResult) *ClusterShardsCmd { +func newClusterShardsCmd(res valkey.ValkeyResult) *ClusterShardsCmd { cmd := &ClusterShardsCmd{} arr, err := res.ToArray() if err != nil { @@ -1795,7 +1795,7 @@ type GeoPosCmd struct { baseCmd[[]*GeoPos] } -func newGeoPosCmd(res rueidis.RedisResult) *GeoPosCmd { +func newGeoPosCmd(res valkey.ValkeyResult) *GeoPosCmd { cmd := &GeoPosCmd{} arr, err := res.ToArray() if err != nil { @@ -1806,7 +1806,7 @@ func newGeoPosCmd(res rueidis.RedisResult) *GeoPosCmd { for _, v := range arr { loc, err := v.ToArray() if err != nil { - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { val = append(val, nil) continue } @@ -1837,10 +1837,10 @@ func newGeoPosCmd(res rueidis.RedisResult) *GeoPosCmd { } type GeoLocationCmd struct { - baseCmd[[]rueidis.GeoLocation] + baseCmd[[]valkey.GeoLocation] } -func newGeoLocationCmd(res rueidis.RedisResult) *GeoLocationCmd { +func newGeoLocationCmd(res valkey.ValkeyResult) *GeoLocationCmd { ret := &GeoLocationCmd{} ret.val, ret.err = res.AsGeosearch() return ret @@ -1861,7 +1861,7 @@ type CommandsInfoCmd struct { baseCmd[map[string]CommandInfo] } -func newCommandsInfoCmd(res rueidis.RedisResult) *CommandsInfoCmd { +func newCommandsInfoCmd(res valkey.ValkeyResult) *CommandsInfoCmd { cmd := &CommandsInfoCmd{} arr, err := res.ToArray() if err != nil { @@ -1892,7 +1892,7 @@ func newCommandsInfoCmd(res rueidis.RedisResult) *CommandsInfoCmd { } _cmd.Flags, err = info[2].AsStrSlice() if err != nil { - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { _cmd.Flags = []string{} } else { cmd.SetErr(err) @@ -1926,7 +1926,7 @@ func newCommandsInfoCmd(res rueidis.RedisResult) *CommandsInfoCmd { } _cmd.ACLFlags, err = info[6].AsStrSlice() if err != nil { - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { _cmd.ACLFlags = []string{} } else { cmd.SetErr(err) @@ -2061,9 +2061,9 @@ type ZAddArgs struct { // ZRANGEBYLEX, // ZREVRANGEBYLEX. // -// Please pay attention to your redis-server version. +// Please pay attention to your valkey-server version. // -// Rev, ByScore, ByLex and Offset+Count options require redis-server 6.2.0 and higher. +// Rev, ByScore, ByLex and Offset+Count options require valkey-server 6.2.0 and higher. type ZRangeArgs struct { Start any Stop any @@ -2080,7 +2080,7 @@ type ZRangeBy struct { Offset, Count int64 } -type GeoLocation = rueidis.GeoLocation +type GeoLocation = valkey.GeoLocation // GeoRadiusQuery is used with GeoRadius to query geospatial index. type GeoRadiusQuery struct { @@ -2227,7 +2227,7 @@ type FunctionListCmd struct { baseCmd[[]Library] } -func newFunctionListCmd(res rueidis.RedisResult) *FunctionListCmd { +func newFunctionListCmd(res valkey.ValkeyResult) *FunctionListCmd { cmd := &FunctionListCmd{} arr, err := res.ToArray() if err != nil { @@ -2275,7 +2275,7 @@ func (cmd *FunctionListCmd) First() (*Library, error) { if len(cmd.val) > 0 { return &cmd.val[0], nil } - return nil, rueidis.Nil + return nil, valkey.Nil } func usePrecise(dur time.Duration) bool { @@ -2319,7 +2319,7 @@ type MapStringInterfaceSliceCmd struct { baseCmd[[]map[string]any] } -func newMapStringInterfaceSliceCmd(res rueidis.RedisResult) *MapStringInterfaceSliceCmd { +func newMapStringInterfaceSliceCmd(res valkey.ValkeyResult) *MapStringInterfaceSliceCmd { cmd := &MapStringInterfaceSliceCmd{} arr, err := res.ToArray() if err != nil { @@ -2379,18 +2379,18 @@ type CFInsertOptions struct { } type BFInfo struct { - Capacity int64 `redis:"Capacity"` - Size int64 `redis:"Size"` - Filters int64 `redis:"Number of filters"` - ItemsInserted int64 `redis:"Number of items inserted"` - ExpansionRate int64 `redis:"Expansion rate"` + Capacity int64 `valkey:"Capacity"` + Size int64 `valkey:"Size"` + Filters int64 `valkey:"Number of filters"` + ItemsInserted int64 `valkey:"Number of items inserted"` + ExpansionRate int64 `valkey:"Expansion rate"` } type BFInfoCmd struct { baseCmd[BFInfo] } -func newBFInfoCmd(res rueidis.RedisResult) *BFInfoCmd { +func newBFInfoCmd(res valkey.ValkeyResult) *BFInfoCmd { cmd := &BFInfoCmd{} info := BFInfo{} if err := res.Error(); err != nil { @@ -2425,7 +2425,7 @@ type ScanDumpCmd struct { baseCmd[ScanDump] } -func newScanDumpCmd(res rueidis.RedisResult) *ScanDumpCmd { +func newScanDumpCmd(res valkey.ValkeyResult) *ScanDumpCmd { cmd := &ScanDumpCmd{} scanDump := ScanDump{} if err := res.Error(); err != nil { @@ -2438,7 +2438,7 @@ func newScanDumpCmd(res rueidis.RedisResult) *ScanDumpCmd { return cmd } if len(arr) != 2 { - panic(fmt.Sprintf("wrong length of redis message, got %v, want %v", len(arr), 2)) + panic(fmt.Sprintf("wrong length of valkey message, got %v, want %v", len(arr), 2)) } iter, err := arr[0].AsInt64() if err != nil { @@ -2457,21 +2457,21 @@ func newScanDumpCmd(res rueidis.RedisResult) *ScanDumpCmd { } type CFInfo struct { - Size int64 `redis:"Size"` - NumBuckets int64 `redis:"Number of buckets"` - NumFilters int64 `redis:"Number of filters"` - NumItemsInserted int64 `redis:"Number of items inserted"` - NumItemsDeleted int64 `redis:"Number of items deleted"` - BucketSize int64 `redis:"Bucket size"` - ExpansionRate int64 `redis:"Expansion rate"` - MaxIteration int64 `redis:"Max iterations"` + Size int64 `valkey:"Size"` + NumBuckets int64 `valkey:"Number of buckets"` + NumFilters int64 `valkey:"Number of filters"` + NumItemsInserted int64 `valkey:"Number of items inserted"` + NumItemsDeleted int64 `valkey:"Number of items deleted"` + BucketSize int64 `valkey:"Bucket size"` + ExpansionRate int64 `valkey:"Expansion rate"` + MaxIteration int64 `valkey:"Max iterations"` } type CFInfoCmd struct { baseCmd[CFInfo] } -func newCFInfoCmd(res rueidis.RedisResult) *CFInfoCmd { +func newCFInfoCmd(res valkey.ValkeyResult) *CFInfoCmd { cmd := &CFInfoCmd{} info := CFInfo{} m, err := res.AsMap() @@ -2499,16 +2499,16 @@ func newCFInfoCmd(res rueidis.RedisResult) *CFInfoCmd { } type CMSInfo struct { - Width int64 `redis:"width"` - Depth int64 `redis:"depth"` - Count int64 `redis:"count"` + Width int64 `valkey:"width"` + Depth int64 `valkey:"depth"` + Count int64 `valkey:"count"` } type CMSInfoCmd struct { baseCmd[CMSInfo] } -func newCMSInfoCmd(res rueidis.RedisResult) *CMSInfoCmd { +func newCMSInfoCmd(res valkey.ValkeyResult) *CMSInfoCmd { cmd := &CMSInfoCmd{} info := CMSInfo{} m, err := res.AsIntMap() @@ -2531,17 +2531,17 @@ func newCMSInfoCmd(res rueidis.RedisResult) *CMSInfoCmd { } type TopKInfo struct { - K int64 `redis:"k"` - Width int64 `redis:"width"` - Depth int64 `redis:"depth"` - Decay float64 `redis:"decay"` + K int64 `valkey:"k"` + Width int64 `valkey:"width"` + Depth int64 `valkey:"depth"` + Decay float64 `valkey:"decay"` } type TopKInfoCmd struct { baseCmd[TopKInfo] } -func newTopKInfoCmd(res rueidis.RedisResult) *TopKInfoCmd { +func newTopKInfoCmd(res valkey.ValkeyResult) *TopKInfoCmd { cmd := &TopKInfoCmd{} info := TopKInfo{} m, err := res.ToMap() @@ -2585,7 +2585,7 @@ type MapStringIntCmd struct { baseCmd[map[string]int64] } -func newMapStringIntCmd(res rueidis.RedisResult) *MapStringIntCmd { +func newMapStringIntCmd(res valkey.ValkeyResult) *MapStringIntCmd { cmd := &MapStringIntCmd{} m, err := res.AsIntMap() if err != nil { @@ -2598,22 +2598,22 @@ func newMapStringIntCmd(res rueidis.RedisResult) *MapStringIntCmd { // Ref: https://redis.io/commands/tdigest.info/ type TDigestInfo struct { - Compression int64 `redis:"Compression"` - Capacity int64 `redis:"Capacity"` - MergedNodes int64 `redis:"Merged nodes"` - UnmergedNodes int64 `redis:"UnmergedNodes"` - MergedWeight int64 `redis:"MergedWeight"` - UnmergedWeight int64 `redis:"Unmerged weight"` - Observations int64 `redis:"Observations"` - TotalCompressions int64 `redis:"Total compressions"` - MemoryUsage int64 `redis:"Memory usage"` + Compression int64 `valkey:"Compression"` + Capacity int64 `valkey:"Capacity"` + MergedNodes int64 `valkey:"Merged nodes"` + UnmergedNodes int64 `valkey:"UnmergedNodes"` + MergedWeight int64 `valkey:"MergedWeight"` + UnmergedWeight int64 `valkey:"Unmerged weight"` + Observations int64 `valkey:"Observations"` + TotalCompressions int64 `valkey:"Total compressions"` + MemoryUsage int64 `valkey:"Memory usage"` } type TDigestInfoCmd struct { baseCmd[TDigestInfo] } -func newTDigestInfoCmd(res rueidis.RedisResult) *TDigestInfoCmd { +func newTDigestInfoCmd(res valkey.ValkeyResult) *TDigestInfoCmd { cmd := &TDigestInfoCmd{} info := TDigestInfo{} m, err := res.AsIntMap() @@ -2735,7 +2735,7 @@ type TSTimestampValueCmd struct { baseCmd[TSTimestampValue] } -func newTSTimestampValueCmd(res rueidis.RedisResult) *TSTimestampValueCmd { +func newTSTimestampValueCmd(res valkey.ValkeyResult) *TSTimestampValueCmd { cmd := &TSTimestampValueCmd{} val := TSTimestampValue{} if err := res.Error(); err != nil { @@ -2768,7 +2768,7 @@ type MapStringInterfaceCmd struct { baseCmd[map[string]any] } -func newMapStringInterfaceCmd(res rueidis.RedisResult) *MapStringInterfaceCmd { +func newMapStringInterfaceCmd(res valkey.ValkeyResult) *MapStringInterfaceCmd { cmd := &MapStringInterfaceCmd{} m, err := res.AsMap() if err != nil { @@ -2796,7 +2796,7 @@ type TSTimestampValueSliceCmd struct { baseCmd[[]TSTimestampValue] } -func newTSTimestampValueSliceCmd(res rueidis.RedisResult) *TSTimestampValueSliceCmd { +func newTSTimestampValueSliceCmd(res valkey.ValkeyResult) *TSTimestampValueSliceCmd { cmd := &TSTimestampValueSliceCmd{} msgSlice, err := res.ToArray() if err != nil { @@ -2830,7 +2830,7 @@ type MapStringSliceInterfaceCmd struct { baseCmd[map[string][]any] } -func newMapStringSliceInterfaceCmd(res rueidis.RedisResult) *MapStringSliceInterfaceCmd { +func newMapStringSliceInterfaceCmd(res valkey.ValkeyResult) *MapStringSliceInterfaceCmd { cmd := &MapStringSliceInterfaceCmd{} m, err := res.ToMap() if err != nil { @@ -2969,7 +2969,7 @@ func (cmd *JSONCmd) Result() (string, error) { return cmd.Val(), nil } -func newJSONCmd(res rueidis.RedisResult) *JSONCmd { +func newJSONCmd(res valkey.ValkeyResult) *JSONCmd { cmd := &JSONCmd{} msg, err := res.ToMessage() if err != nil { @@ -3002,7 +3002,7 @@ func newJSONCmd(res rueidis.RedisResult) *JSONCmd { for i, e := range arr { anyE, err := e.ToAny() if err != nil { - if err == rueidis.Nil { + if err == valkey.Nil { continue } cmd.SetErr(err) @@ -3034,7 +3034,7 @@ type IntPointerSliceCmd struct { } // newIntPointerSliceCmd initialises an IntPointerSliceCmd -func newIntPointerSliceCmd(res rueidis.RedisResult) *IntPointerSliceCmd { +func newIntPointerSliceCmd(res valkey.ValkeyResult) *IntPointerSliceCmd { cmd := &IntPointerSliceCmd{} arr, err := res.ToArray() if err != nil { @@ -3061,7 +3061,7 @@ type JSONSliceCmd struct { baseCmd[[]any] } -func newJSONSliceCmd(res rueidis.RedisResult) *JSONSliceCmd { +func newJSONSliceCmd(res valkey.ValkeyResult) *JSONSliceCmd { cmd := &JSONSliceCmd{} arr, err := res.ToArray() if err != nil { diff --git a/rueidiscompat/command_test.go b/valkeycompat/command_test.go similarity index 99% rename from rueidiscompat/command_test.go rename to valkeycompat/command_test.go index 07220de..b678085 100644 --- a/rueidiscompat/command_test.go +++ b/valkeycompat/command_test.go @@ -24,7 +24,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package rueidiscompat +package valkeycompat import ( "errors" diff --git a/rueidiscompat/go.mod b/valkeycompat/go.mod similarity index 69% rename from rueidiscompat/go.mod rename to valkeycompat/go.mod index 32e69b5..1502306 100644 --- a/rueidiscompat/go.mod +++ b/valkeycompat/go.mod @@ -1,13 +1,13 @@ -module github.com/redis/rueidis/rueidiscompat +module github.com/rueian/valkey-go/valkeycompat go 1.20 -replace github.com/redis/rueidis => ../ +replace github.com/rueian/valkey-go => ../ require ( github.com/onsi/ginkgo/v2 v2.15.0 github.com/onsi/gomega v1.31.1 - github.com/redis/rueidis v1.0.34 + github.com/rueian/valkey-go v1.0.34 ) require ( @@ -15,8 +15,8 @@ require ( github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect - golang.org/x/net v0.19.0 // indirect - golang.org/x/sys v0.17.0 // indirect + golang.org/x/net v0.24.0 // indirect + golang.org/x/sys v0.19.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/tools v0.16.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/rueidiscompat/go.sum b/valkeycompat/go.sum similarity index 90% rename from rueidiscompat/go.sum rename to valkeycompat/go.sum index 10a9ce5..fa1bb90 100644 --- a/rueidiscompat/go.sum +++ b/valkeycompat/go.sum @@ -21,10 +21,10 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= -golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= -golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= -golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA= diff --git a/rueidiscompat/hscan.go b/valkeycompat/hscan.go similarity index 93% rename from rueidiscompat/hscan.go rename to valkeycompat/hscan.go index a040140..f185995 100644 --- a/rueidiscompat/hscan.go +++ b/valkeycompat/hscan.go @@ -24,7 +24,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package rueidiscompat +package valkeycompat import ( "errors" @@ -39,7 +39,7 @@ type decoderFunc func(reflect.Value, string) error // Scanner is the interface implemented by themselves, // which will override the decoding behavior of decoderFunc. type Scanner interface { - ScanRedis(s string) error + ScanValkey(s string) error } var ( @@ -83,12 +83,12 @@ func Struct(dst interface{}) (StructValue, error) { // The destination to scan into should be a struct pointer. if v.Kind() != reflect.Ptr || v.IsNil() { - return StructValue{}, fmt.Errorf("redis.Scan(non-pointer %T)", dst) + return StructValue{}, fmt.Errorf("valkey.Scan(non-pointer %T)", dst) } v = v.Elem() if v.Kind() != reflect.Struct { - return StructValue{}, fmt.Errorf("redis.Scan(non-struct %T)", dst) + return StructValue{}, fmt.Errorf("valkey.Scan(non-struct %T)", dst) } return StructValue{ @@ -97,8 +97,8 @@ func Struct(dst interface{}) (StructValue, error) { }, nil } -// Scan scans the results from a key-value Redis map result set to a destination struct. -// The Redis keys are matched to the struct's field with the `redis` tag. +// Scan scans the results from a key-value Valkey map result set to a destination struct. +// The Valkey keys are matched to the struct's field with the `valkey` tag. // NOTE: vals' element's underlying type should be string func Scan(dst interface{}, keys []string, vals []interface{}) error { if len(keys) != len(vals) { @@ -225,5 +225,5 @@ func decodeSlice(f reflect.Value, s string) error { } func decodeUnsupported(v reflect.Value, s string) error { - return fmt.Errorf("redis.Scan(unsupported %s)", v.Type()) + return fmt.Errorf("valkey.Scan(unsupported %s)", v.Type()) } diff --git a/rueidiscompat/hscan_test.go b/valkeycompat/hscan_test.go similarity index 80% rename from rueidiscompat/hscan_test.go rename to valkeycompat/hscan_test.go index 8b5db9b..26869a4 100644 --- a/rueidiscompat/hscan_test.go +++ b/valkeycompat/hscan_test.go @@ -24,7 +24,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package rueidiscompat +package valkeycompat import ( "math" @@ -36,52 +36,52 @@ import ( ) type data struct { - Omit string `redis:"-"` + Omit string `valkey:"-"` Empty string - String string `redis:"string"` - Bytes []byte `redis:"byte"` - Int int `redis:"int"` - Int8 int8 `redis:"int8"` - Int16 int16 `redis:"int16"` - Int32 int32 `redis:"int32"` - Int64 int64 `redis:"int64"` - Uint uint `redis:"uint"` - Uint8 uint8 `redis:"uint8"` - Uint16 uint16 `redis:"uint16"` - Uint32 uint32 `redis:"uint32"` - Uint64 uint64 `redis:"uint64"` - Float float32 `redis:"float"` - Float64 float64 `redis:"float64"` - Bool bool `redis:"bool"` - StringPointer *string `redis:"stringPointer"` - IntPointer *int `redis:"intPointer"` - Int8Pointer *int8 `redis:"int8Pointer"` - Int16Pointer *int16 `redis:"int16Pointer"` - Int32Pointer *int32 `redis:"int32Pointer"` - Int64Pointer *int64 `redis:"int64Pointer"` - UintPointer *uint `redis:"uintPointer"` - Uint8Pointer *uint8 `redis:"uint8Pointer"` - Uint16Pointer *uint16 `redis:"uint16Pointer"` - Uint32Pointer *uint32 `redis:"uint32Pointer"` - Uint64Pointer *uint64 `redis:"uint64Pointer"` - FloatPointer *float32 `redis:"floatPointer"` - Float64Pointer *float64 `redis:"float64Pointer"` - BoolPointer *bool `redis:"boolPointer"` + String string `valkey:"string"` + Bytes []byte `valkey:"byte"` + Int int `valkey:"int"` + Int8 int8 `valkey:"int8"` + Int16 int16 `valkey:"int16"` + Int32 int32 `valkey:"int32"` + Int64 int64 `valkey:"int64"` + Uint uint `valkey:"uint"` + Uint8 uint8 `valkey:"uint8"` + Uint16 uint16 `valkey:"uint16"` + Uint32 uint32 `valkey:"uint32"` + Uint64 uint64 `valkey:"uint64"` + Float float32 `valkey:"float"` + Float64 float64 `valkey:"float64"` + Bool bool `valkey:"bool"` + StringPointer *string `valkey:"stringPointer"` + IntPointer *int `valkey:"intPointer"` + Int8Pointer *int8 `valkey:"int8Pointer"` + Int16Pointer *int16 `valkey:"int16Pointer"` + Int32Pointer *int32 `valkey:"int32Pointer"` + Int64Pointer *int64 `valkey:"int64Pointer"` + UintPointer *uint `valkey:"uintPointer"` + Uint8Pointer *uint8 `valkey:"uint8Pointer"` + Uint16Pointer *uint16 `valkey:"uint16Pointer"` + Uint32Pointer *uint32 `valkey:"uint32Pointer"` + Uint64Pointer *uint64 `valkey:"uint64Pointer"` + FloatPointer *float32 `valkey:"floatPointer"` + Float64Pointer *float64 `valkey:"float64Pointer"` + BoolPointer *bool `valkey:"boolPointer"` } type TimeRFC3339Nano struct { time.Time } -func (t *TimeRFC3339Nano) ScanRedis(s string) (err error) { +func (t *TimeRFC3339Nano) ScanValkey(s string) (err error) { t.Time, err = time.Parse(time.RFC3339Nano, s) return } type TimeData struct { - Name string `redis:"name"` - Time *TimeRFC3339Nano `redis:"login"` + Name string `valkey:"name"` + Time *TimeRFC3339Nano `valkey:"login"` } type i []interface{} @@ -172,12 +172,12 @@ var _ = Describe("Scan", func() { // Scan a different type with the same values to test that // the struct spec maps don't conflict. type data2 struct { - String string `redis:"string"` - Bytes []byte `redis:"byte"` - Int int `redis:"int"` - Uint uint `redis:"uint"` - Float float32 `redis:"float"` - Bool bool `redis:"bool"` + String string `valkey:"string"` + Bytes []byte `valkey:"byte"` + Int int `valkey:"int"` + Uint uint `valkey:"uint"` + Float float32 `valkey:"float"` + Bool bool `valkey:"bool"` } var d2 data2 Expect(Scan(&d2, keys, vals)).NotTo(HaveOccurred()) @@ -262,7 +262,7 @@ var _ = Describe("Scan", func() { It("should time.Time RFC3339Nano", func() { type TimeTime struct { - Time time.Time `redis:"time"` + Time time.Time `valkey:"time"` } now := time.Now() diff --git a/rueidiscompat/structmap.go b/valkeycompat/structmap.go similarity index 95% rename from rueidiscompat/structmap.go rename to valkeycompat/structmap.go index d259c47..b34d8bc 100644 --- a/rueidiscompat/structmap.go +++ b/valkeycompat/structmap.go @@ -24,7 +24,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package rueidiscompat +package valkeycompat import ( "encoding" @@ -49,7 +49,7 @@ func (s *structMap) get(t reflect.Type) *structSpec { return v.(*structSpec) } - spec := newStructSpec(t, "redis") + spec := newStructSpec(t, "valkey") s.m.Store(t, spec) return spec } @@ -136,7 +136,7 @@ func (s StructValue) Scan(key string, value string) error { if isPtr && v.Type().NumMethod() > 0 && v.CanInterface() { switch scan := v.Interface().(type) { case Scanner: - return scan.ScanRedis(value) + return scan.ScanValkey(value) case encoding.TextUnmarshaler: return scan.UnmarshalText([]byte(value)) } @@ -148,7 +148,7 @@ func (s StructValue) Scan(key string, value string) error { if err := field.fn(v, value); err != nil { t := s.value.Type() - return fmt.Errorf("cannot scan redis.result %s into struct field %s.%s of type %s, error-%s", + return fmt.Errorf("cannot scan valkey.result %s into struct field %s.%s of type %s, error-%s", value, t.Name(), t.Field(field.index).Name, t.Field(field.index).Type, err.Error()) } return nil diff --git a/valkeyhook/README.md b/valkeyhook/README.md new file mode 100644 index 0000000..1bc376e --- /dev/null +++ b/valkeyhook/README.md @@ -0,0 +1,65 @@ +# valkeyhook + +With `valkeyhook.WithHook`, users can easily intercept `valkey.Client` by implementing custom `valkeyhook.Hook` handler. + +This can be useful to change the behavior of `valkey.Client` or add other integrations such as observability, APM etc. + +## Example + +```go +package main + +import ( + "context" + "time" + + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/valkeyhook" +) + +type hook struct{} + +func (h *hook) Do(client valkey.Client, ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) { + // do whatever you want before client.Do + resp = client.Do(ctx, cmd) + // do whatever you want after client.Do + return +} + +func (h *hook) DoMulti(client valkey.Client, ctx context.Context, multi ...valkey.Completed) (resps []valkey.ValkeyResult) { + // do whatever you want before client.DoMulti + resps = client.DoMulti(ctx, multi...) + // do whatever you want after client.DoMulti + return +} + +func (h *hook) DoCache(client valkey.Client, ctx context.Context, cmd valkey.Cacheable, ttl time.Duration) (resp valkey.ValkeyResult) { + // do whatever you want before client.DoCache + resp = client.DoCache(ctx, cmd, ttl) + // do whatever you want after client.DoCache + return +} + +func (h *hook) DoMultiCache(client valkey.Client, ctx context.Context, multi ...valkey.CacheableTTL) (resps []valkey.ValkeyResult) { + // do whatever you want before client.DoMultiCache + resps = client.DoMultiCache(ctx, multi...) + // do whatever you want after client.DoMultiCache + return +} + +func (h *hook) Receive(client valkey.Client, ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) { + // do whatever you want before client.Receive + err = client.Receive(ctx, subscribe, fn) + // do whatever you want after client.Receive + return +} + +func main() { + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) + if err != nil { + panic(err) + } + client = valkeyhook.WithHook(client, &hook{}) + defer client.Close() +} +``` diff --git a/valkeyhook/go.mod b/valkeyhook/go.mod new file mode 100644 index 0000000..6be2ff9 --- /dev/null +++ b/valkeyhook/go.mod @@ -0,0 +1,16 @@ +module github.com/rueian/valkey-go/valkeyhook + +go 1.20 + +replace ( + github.com/rueian/valkey-go => ../ + github.com/rueian/valkey-go/mock => ../mock +) + +require ( + github.com/rueian/valkey-go v1.0.34 + github.com/rueian/valkey-go/mock v1.0.34 + go.uber.org/mock v0.4.0 +) + +require golang.org/x/sys v0.17.0 // indirect diff --git a/rueidishook/go.sum b/valkeyhook/go.sum similarity index 100% rename from rueidishook/go.sum rename to valkeyhook/go.sum diff --git a/valkeyhook/hook.go b/valkeyhook/hook.go new file mode 100644 index 0000000..bc3c330 --- /dev/null +++ b/valkeyhook/hook.go @@ -0,0 +1,173 @@ +package valkeyhook + +import ( + "context" + "time" + "unsafe" + + "github.com/rueian/valkey-go" +) + +var _ valkey.Client = (*hookclient)(nil) + +// Hook allows user to intercept valkey.Client by using WithHook +type Hook interface { + Do(client valkey.Client, ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) + DoMulti(client valkey.Client, ctx context.Context, multi ...valkey.Completed) (resps []valkey.ValkeyResult) + DoCache(client valkey.Client, ctx context.Context, cmd valkey.Cacheable, ttl time.Duration) (resp valkey.ValkeyResult) + DoMultiCache(client valkey.Client, ctx context.Context, multi ...valkey.CacheableTTL) (resps []valkey.ValkeyResult) + Receive(client valkey.Client, ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) + DoStream(client valkey.Client, ctx context.Context, cmd valkey.Completed) valkey.ValkeyResultStream + DoMultiStream(client valkey.Client, ctx context.Context, multi ...valkey.Completed) valkey.MultiValkeyResultStream +} + +// WithHook wraps valkey.Client with Hook and allows user to intercept valkey.Client +func WithHook(client valkey.Client, hook Hook) valkey.Client { + return &hookclient{client: client, hook: hook} +} + +type hookclient struct { + client valkey.Client + hook Hook +} + +func (c *hookclient) B() valkey.Builder { + return c.client.B() +} + +func (c *hookclient) Do(ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) { + return c.hook.Do(c.client, ctx, cmd) +} + +func (c *hookclient) DoMulti(ctx context.Context, multi ...valkey.Completed) (resp []valkey.ValkeyResult) { + return c.hook.DoMulti(c.client, ctx, multi...) +} + +func (c *hookclient) DoCache(ctx context.Context, cmd valkey.Cacheable, ttl time.Duration) (resp valkey.ValkeyResult) { + return c.hook.DoCache(c.client, ctx, cmd, ttl) +} + +func (c *hookclient) DoMultiCache(ctx context.Context, multi ...valkey.CacheableTTL) (resps []valkey.ValkeyResult) { + return c.hook.DoMultiCache(c.client, ctx, multi...) +} + +func (c *hookclient) DoStream(ctx context.Context, cmd valkey.Completed) valkey.ValkeyResultStream { + return c.hook.DoStream(c.client, ctx, cmd) +} + +func (c *hookclient) DoMultiStream(ctx context.Context, multi ...valkey.Completed) valkey.MultiValkeyResultStream { + return c.hook.DoMultiStream(c.client, ctx, multi...) +} + +func (c *hookclient) Dedicated(fn func(valkey.DedicatedClient) error) (err error) { + return c.client.Dedicated(func(client valkey.DedicatedClient) error { + return fn(&dedicated{client: &extended{DedicatedClient: client}, hook: c.hook}) + }) +} + +func (c *hookclient) Dedicate() (valkey.DedicatedClient, func()) { + client, cancel := c.client.Dedicate() + return &dedicated{client: &extended{DedicatedClient: client}, hook: c.hook}, cancel +} + +func (c *hookclient) Receive(ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) { + return c.hook.Receive(c.client, ctx, subscribe, fn) +} + +func (c *hookclient) Nodes() map[string]valkey.Client { + nodes := c.client.Nodes() + for addr, client := range nodes { + nodes[addr] = &hookclient{client: client, hook: c.hook} + } + return nodes +} + +func (c *hookclient) Close() { + c.client.Close() +} + +var _ valkey.DedicatedClient = (*dedicated)(nil) + +type dedicated struct { + client *extended + hook Hook +} + +func (d *dedicated) B() valkey.Builder { + return d.client.B() +} + +func (d *dedicated) Do(ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) { + return d.hook.Do(d.client, ctx, cmd) +} + +func (d *dedicated) DoMulti(ctx context.Context, multi ...valkey.Completed) (resp []valkey.ValkeyResult) { + return d.hook.DoMulti(d.client, ctx, multi...) +} + +func (d *dedicated) Receive(ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) { + return d.hook.Receive(d.client, ctx, subscribe, fn) +} + +func (d *dedicated) SetPubSubHooks(hooks valkey.PubSubHooks) <-chan error { + return d.client.SetPubSubHooks(hooks) +} + +func (d *dedicated) Close() { + d.client.Close() +} + +var _ valkey.Client = (*extended)(nil) + +type extended struct { + valkey.DedicatedClient +} + +func (e *extended) DoCache(ctx context.Context, cmd valkey.Cacheable, ttl time.Duration) (resp valkey.ValkeyResult) { + panic("DoCache() is not allowed with valkey.DedicatedClient") +} + +func (e *extended) DoMultiCache(ctx context.Context, multi ...valkey.CacheableTTL) (resp []valkey.ValkeyResult) { + panic("DoMultiCache() is not allowed with valkey.DedicatedClient") +} +func (c *extended) DoStream(ctx context.Context, cmd valkey.Completed) valkey.ValkeyResultStream { + panic("DoStream() is not allowed with valkey.DedicatedClient") +} + +func (c *extended) DoMultiStream(ctx context.Context, multi ...valkey.Completed) valkey.MultiValkeyResultStream { + panic("DoMultiStream() is not allowed with valkey.DedicatedClient") +} + +func (e *extended) Dedicated(fn func(valkey.DedicatedClient) error) (err error) { + panic("Dedicated() is not allowed with valkey.DedicatedClient") +} + +func (e *extended) Dedicate() (client valkey.DedicatedClient, cancel func()) { + panic("Dedicate() is not allowed with valkey.DedicatedClient") +} + +func (e *extended) Nodes() map[string]valkey.Client { + panic("Nodes() is not allowed with valkey.DedicatedClient") +} + +type result struct { + err error + val valkey.ValkeyMessage +} + +func NewErrorResult(err error) valkey.ValkeyResult { + r := result{err: err} + return *(*valkey.ValkeyResult)(unsafe.Pointer(&r)) +} + +type stream struct { + p *int + w *int + e error + n int +} + +func NewErrorResultStream(err error) valkey.ValkeyResultStream { + r := stream{e: err} + return *(*valkey.ValkeyResultStream)(unsafe.Pointer(&r)) +} diff --git a/rueidishook/hook_test.go b/valkeyhook/hook_test.go similarity index 54% rename from rueidishook/hook_test.go rename to valkeyhook/hook_test.go index 5356bae..576ea4c 100644 --- a/rueidishook/hook_test.go +++ b/valkeyhook/hook_test.go @@ -1,4 +1,4 @@ -package rueidishook +package valkeyhook import ( "context" @@ -7,127 +7,127 @@ import ( "testing" "time" - "github.com/redis/rueidis" - "github.com/redis/rueidis/mock" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/mock" "go.uber.org/mock/gomock" ) type hook struct{} -func (h *hook) Do(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) { +func (h *hook) Do(client valkey.Client, ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) { return client.Do(ctx, cmd) } -func (h *hook) DoMulti(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) (resps []rueidis.RedisResult) { +func (h *hook) DoMulti(client valkey.Client, ctx context.Context, multi ...valkey.Completed) (resps []valkey.ValkeyResult) { return client.DoMulti(ctx, multi...) } -func (h *hook) DoCache(client rueidis.Client, ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) (resp rueidis.RedisResult) { +func (h *hook) DoCache(client valkey.Client, ctx context.Context, cmd valkey.Cacheable, ttl time.Duration) (resp valkey.ValkeyResult) { return client.DoCache(ctx, cmd, ttl) } -func (h *hook) DoMultiCache(client rueidis.Client, ctx context.Context, multi ...rueidis.CacheableTTL) (resps []rueidis.RedisResult) { +func (h *hook) DoMultiCache(client valkey.Client, ctx context.Context, multi ...valkey.CacheableTTL) (resps []valkey.ValkeyResult) { return client.DoMultiCache(ctx, multi...) } -func (h *hook) Receive(client rueidis.Client, ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) { +func (h *hook) Receive(client valkey.Client, ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) { return client.Receive(ctx, subscribe, fn) } -func (h *hook) DoStream(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) rueidis.RedisResultStream { +func (h *hook) DoStream(client valkey.Client, ctx context.Context, cmd valkey.Completed) valkey.ValkeyResultStream { return client.DoStream(ctx, cmd) } -func (h *hook) DoMultiStream(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) rueidis.MultiRedisResultStream { +func (h *hook) DoMultiStream(client valkey.Client, ctx context.Context, multi ...valkey.Completed) valkey.MultiValkeyResultStream { return client.DoMultiStream(ctx, multi...) } type wronghook struct { - DoFn func(client rueidis.Client) + DoFn func(client valkey.Client) } -func (w *wronghook) Do(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) { +func (w *wronghook) Do(client valkey.Client, ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) { w.DoFn(client) - return rueidis.RedisResult{} + return valkey.ValkeyResult{} } -func (w *wronghook) DoMulti(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) (resps []rueidis.RedisResult) { +func (w *wronghook) DoMulti(client valkey.Client, ctx context.Context, multi ...valkey.Completed) (resps []valkey.ValkeyResult) { panic("implement me") } -func (w *wronghook) DoCache(client rueidis.Client, ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) (resp rueidis.RedisResult) { +func (w *wronghook) DoCache(client valkey.Client, ctx context.Context, cmd valkey.Cacheable, ttl time.Duration) (resp valkey.ValkeyResult) { panic("implement me") } -func (w *wronghook) DoMultiCache(client rueidis.Client, ctx context.Context, multi ...rueidis.CacheableTTL) (resps []rueidis.RedisResult) { +func (w *wronghook) DoMultiCache(client valkey.Client, ctx context.Context, multi ...valkey.CacheableTTL) (resps []valkey.ValkeyResult) { panic("implement me") } -func (w *wronghook) Receive(client rueidis.Client, ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) { +func (w *wronghook) Receive(client valkey.Client, ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) { panic("implement me") } -func (w *wronghook) DoStream(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) rueidis.RedisResultStream { +func (w *wronghook) DoStream(client valkey.Client, ctx context.Context, cmd valkey.Completed) valkey.ValkeyResultStream { panic("implement me") } -func (w *wronghook) DoMultiStream(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) rueidis.MultiRedisResultStream { +func (w *wronghook) DoMultiStream(client valkey.Client, ctx context.Context, multi ...valkey.Completed) valkey.MultiValkeyResultStream { panic("implement me") } -func testHooked(t *testing.T, hooked rueidis.Client, mocked *mock.Client) { +func testHooked(t *testing.T, hooked valkey.Client, mocked *mock.Client) { ctx := context.Background() { - mocked.EXPECT().Do(ctx, mock.Match("GET", "a")).Return(mock.Result(mock.RedisNil())) - if err := hooked.Do(ctx, hooked.B().Get().Key("a").Build()).Error(); !rueidis.IsRedisNil(err) { + mocked.EXPECT().Do(ctx, mock.Match("GET", "a")).Return(mock.Result(mock.ValkeyNil())) + if err := hooked.Do(ctx, hooked.B().Get().Key("a").Build()).Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { - mocked.EXPECT().DoCache(ctx, mock.Match("GET", "b"), time.Second).Return(mock.Result(mock.RedisNil())) - if err := hooked.DoCache(ctx, hooked.B().Get().Key("b").Cache(), time.Second).Error(); !rueidis.IsRedisNil(err) { + mocked.EXPECT().DoCache(ctx, mock.Match("GET", "b"), time.Second).Return(mock.Result(mock.ValkeyNil())) + if err := hooked.DoCache(ctx, hooked.B().Get().Key("b").Cache(), time.Second).Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { - mocked.EXPECT().DoMulti(ctx, mock.Match("GET", "c")).Return([]rueidis.RedisResult{mock.Result(mock.RedisNil())}) + mocked.EXPECT().DoMulti(ctx, mock.Match("GET", "c")).Return([]valkey.ValkeyResult{mock.Result(mock.ValkeyNil())}) for _, resp := range hooked.DoMulti(ctx, hooked.B().Get().Key("c").Build()) { - if err := resp.Error(); !rueidis.IsRedisNil(err) { + if err := resp.Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } } { - mocked.EXPECT().DoMultiCache(ctx, mock.Match("GET", "e")).Return([]rueidis.RedisResult{mock.Result(mock.RedisNil())}) - for _, resp := range hooked.DoMultiCache(ctx, rueidis.CT(hooked.B().Get().Key("e").Cache(), time.Second)) { - if err := resp.Error(); !rueidis.IsRedisNil(err) { + mocked.EXPECT().DoMultiCache(ctx, mock.Match("GET", "e")).Return([]valkey.ValkeyResult{mock.Result(mock.ValkeyNil())}) + for _, resp := range hooked.DoMultiCache(ctx, valkey.CT(hooked.B().Get().Key("e").Cache(), time.Second)) { + if err := resp.Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } } { - mocked.EXPECT().DoStream(ctx, mock.Match("GET", "e")).Return(mock.RedisResultStream(mock.RedisNil())) + mocked.EXPECT().DoStream(ctx, mock.Match("GET", "e")).Return(mock.ValkeyResultStream(mock.ValkeyNil())) s := hooked.DoStream(ctx, hooked.B().Get().Key("e").Build()) - if _, err := s.WriteTo(io.Discard); !rueidis.IsRedisNil(err) { + if _, err := s.WriteTo(io.Discard); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { - mocked.EXPECT().DoMultiStream(ctx, mock.Match("GET", "e"), mock.Match("GET", "f")).Return(mock.MultiRedisResultStream(mock.RedisNil())) + mocked.EXPECT().DoMultiStream(ctx, mock.Match("GET", "e"), mock.Match("GET", "f")).Return(mock.MultiValkeyResultStream(mock.ValkeyNil())) s := hooked.DoMultiStream(ctx, hooked.B().Get().Key("e").Build(), hooked.B().Get().Key("f").Build()) - if _, err := s.WriteTo(io.Discard); !rueidis.IsRedisNil(err) { + if _, err := s.WriteTo(io.Discard); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { - mocked.EXPECT().Receive(ctx, mock.Match("SUBSCRIBE", "a"), gomock.Any()).DoAndReturn(func(ctx context.Context, cmd any, fn func(msg rueidis.PubSubMessage)) error { - fn(rueidis.PubSubMessage{ + mocked.EXPECT().Receive(ctx, mock.Match("SUBSCRIBE", "a"), gomock.Any()).DoAndReturn(func(ctx context.Context, cmd any, fn func(msg valkey.PubSubMessage)) error { + fn(valkey.PubSubMessage{ Channel: "s", Message: "s", }) return errors.New("any") }) - if err := hooked.Receive(ctx, hooked.B().Subscribe().Channel("a").Build(), func(msg rueidis.PubSubMessage) { + if err := hooked.Receive(ctx, hooked.B().Subscribe().Channel("a").Build(), func(msg valkey.PubSubMessage) { if msg.Message != "s" && msg.Channel != "s" { t.Fatalf("unexpected val %v", msg) } @@ -136,7 +136,7 @@ func testHooked(t *testing.T, hooked rueidis.Client, mocked *mock.Client) { } } { - mocked.EXPECT().Nodes().Return(map[string]rueidis.Client{"addr": mocked}) + mocked.EXPECT().Nodes().Return(map[string]valkey.Client{"addr": mocked}) if nodes := hooked.Nodes(); nodes["addr"].(*hookclient).client != mocked { t.Fatalf("unexpected val %v", nodes) } @@ -149,31 +149,31 @@ func testHooked(t *testing.T, hooked rueidis.Client, mocked *mock.Client) { } } -func testHookedDedicated(t *testing.T, hooked rueidis.DedicatedClient, mocked *mock.DedicatedClient) { +func testHookedDedicated(t *testing.T, hooked valkey.DedicatedClient, mocked *mock.DedicatedClient) { ctx := context.Background() { - mocked.EXPECT().Do(ctx, mock.Match("GET", "a")).Return(mock.Result(mock.RedisNil())) - if err := hooked.Do(ctx, hooked.B().Get().Key("a").Build()).Error(); !rueidis.IsRedisNil(err) { + mocked.EXPECT().Do(ctx, mock.Match("GET", "a")).Return(mock.Result(mock.ValkeyNil())) + if err := hooked.Do(ctx, hooked.B().Get().Key("a").Build()).Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } { - mocked.EXPECT().DoMulti(ctx, mock.Match("GET", "c")).Return([]rueidis.RedisResult{mock.Result(mock.RedisNil())}) + mocked.EXPECT().DoMulti(ctx, mock.Match("GET", "c")).Return([]valkey.ValkeyResult{mock.Result(mock.ValkeyNil())}) for _, resp := range hooked.DoMulti(ctx, hooked.B().Get().Key("c").Build()) { - if err := resp.Error(); !rueidis.IsRedisNil(err) { + if err := resp.Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } } { - mocked.EXPECT().Receive(ctx, mock.Match("SUBSCRIBE", "a"), gomock.Any()).DoAndReturn(func(ctx context.Context, cmd any, fn func(msg rueidis.PubSubMessage)) error { - fn(rueidis.PubSubMessage{ + mocked.EXPECT().Receive(ctx, mock.Match("SUBSCRIBE", "a"), gomock.Any()).DoAndReturn(func(ctx context.Context, cmd any, fn func(msg valkey.PubSubMessage)) error { + fn(valkey.PubSubMessage{ Channel: "s", Message: "s", }) return errors.New("any") }) - if err := hooked.Receive(ctx, hooked.B().Subscribe().Channel("a").Build(), func(msg rueidis.PubSubMessage) { + if err := hooked.Receive(ctx, hooked.B().Subscribe().Channel("a").Build(), func(msg valkey.PubSubMessage) { if msg.Message != "s" && msg.Channel != "s" { t.Fatalf("unexpected val %v", msg) } @@ -182,8 +182,8 @@ func testHookedDedicated(t *testing.T, hooked rueidis.DedicatedClient, mocked *m } } { - mocked.EXPECT().SetPubSubHooks(rueidis.PubSubHooks{}) - hooked.SetPubSubHooks(rueidis.PubSubHooks{}) + mocked.EXPECT().SetPubSubHooks(valkey.PubSubHooks{}) + hooked.SetPubSubHooks(valkey.PubSubHooks{}) } { ch := make(chan struct{}) @@ -209,11 +209,11 @@ func TestWithHook(t *testing.T) { } { dc := mock.NewDedicatedClient(ctrl) - cb := func(c rueidis.DedicatedClient) error { + cb := func(c valkey.DedicatedClient) error { testHookedDedicated(t, c, dc) return errors.New("any") } - mocked.EXPECT().Dedicated(gomock.Any()).DoAndReturn(func(fn func(c rueidis.DedicatedClient) error) error { + mocked.EXPECT().Dedicated(gomock.Any()).DoAndReturn(func(fn func(c valkey.DedicatedClient) error) error { return fn(dc) }) if err := hooked.Dedicated(cb); err.Error() != "any" { @@ -228,7 +228,7 @@ func TestForbiddenMethodForDedicatedClient(t *testing.T) { mocked := mock.NewClient(ctrl) - shouldpanic := func(fn func(client rueidis.Client), msg string) { + shouldpanic := func(fn func(client valkey.Client), msg string) { defer func() { if err := recover().(string); err != msg { t.Fatalf("unexpected err %v", err) @@ -236,52 +236,52 @@ func TestForbiddenMethodForDedicatedClient(t *testing.T) { }() hooked := WithHook(mocked, &wronghook{DoFn: fn}) - mocked.EXPECT().Dedicated(gomock.Any()).DoAndReturn(func(fn func(c rueidis.DedicatedClient) error) error { + mocked.EXPECT().Dedicated(gomock.Any()).DoAndReturn(func(fn func(c valkey.DedicatedClient) error) error { return fn(mock.NewDedicatedClient(ctrl)) }) - hooked.Dedicated(func(client rueidis.DedicatedClient) error { + hooked.Dedicated(func(client valkey.DedicatedClient) error { return client.Do(context.Background(), client.B().Get().Key("").Build()).Error() }) } for _, c := range []struct { - fn func(client rueidis.Client) + fn func(client valkey.Client) msg string }{ { - fn: func(client rueidis.Client) { + fn: func(client valkey.Client) { client.DoCache(context.Background(), client.B().Get().Key("").Cache(), time.Second) }, - msg: "DoCache() is not allowed with rueidis.DedicatedClient", + msg: "DoCache() is not allowed with valkey.DedicatedClient", }, { - fn: func(client rueidis.Client) { + fn: func(client valkey.Client) { client.DoMultiCache(context.Background()) }, - msg: "DoMultiCache() is not allowed with rueidis.DedicatedClient", + msg: "DoMultiCache() is not allowed with valkey.DedicatedClient", }, { - fn: func(client rueidis.Client) { - client.Dedicated(func(client rueidis.DedicatedClient) error { return nil }) + fn: func(client valkey.Client) { + client.Dedicated(func(client valkey.DedicatedClient) error { return nil }) }, - msg: "Dedicated() is not allowed with rueidis.DedicatedClient", + msg: "Dedicated() is not allowed with valkey.DedicatedClient", }, { - fn: func(client rueidis.Client) { + fn: func(client valkey.Client) { client.Dedicate() }, - msg: "Dedicate() is not allowed with rueidis.DedicatedClient", + msg: "Dedicate() is not allowed with valkey.DedicatedClient", }, { - fn: func(client rueidis.Client) { + fn: func(client valkey.Client) { client.Nodes() }, - msg: "Nodes() is not allowed with rueidis.DedicatedClient", + msg: "Nodes() is not allowed with valkey.DedicatedClient", }, { - fn: func(client rueidis.Client) { + fn: func(client valkey.Client) { client.DoStream(context.Background(), client.B().Get().Key("").Build()) }, - msg: "DoStream() is not allowed with rueidis.DedicatedClient", + msg: "DoStream() is not allowed with valkey.DedicatedClient", }, { - fn: func(client rueidis.Client) { + fn: func(client valkey.Client) { client.DoMultiStream(context.Background(), client.B().Get().Key("").Build()) }, - msg: "DoMultiStream() is not allowed with rueidis.DedicatedClient", + msg: "DoMultiStream() is not allowed with valkey.DedicatedClient", }, } { shouldpanic(c.fn, c.msg) diff --git a/rueidislock/README.md b/valkeylock/README.md similarity index 63% rename from rueidislock/README.md rename to valkeylock/README.md index a7b401f..61adca8 100644 --- a/rueidislock/README.md +++ b/valkeylock/README.md @@ -1,19 +1,19 @@ -# rueidislock +# valkeylock -A [Redis Distributed Lock Pattern](https://redis.io/docs/reference/patterns/distributed-locks/) enhanced by [Client Side Caching](https://redis.io/docs/manual/client-side-caching/). +A [Valkey Distributed Lock Pattern](https://redis.io/docs/reference/patterns/distributed-locks/) enhanced by [Client Side Caching](https://redis.io/docs/manual/client-side-caching/). ```go package main import ( "context" - "github.com/redis/rueidis" - "github.com/redis/rueidis/rueidislock" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/valkeylock" ) func main() { - locker, err := rueidislock.NewLocker(rueidislock.LockerOption{ - ClientOption: rueidis.ClientOption{InitAddress: []string{"node1:6379", "node2:6380", "node3:6379"}}, + locker, err := valkeylock.NewLocker(valkeylock.LockerOption{ + ClientOption: valkey.ClientOption{InitAddress: []string{"node1:6379", "node2:6380", "node3:6379"}}, KeyMajority: 2, // please make sure that all your `Locker`s share the same KeyMajority }) if err != nil { @@ -35,9 +35,9 @@ func main() { } ``` -## Features backed by the Redis Client Side Caching +## Features backed by the Valkey Client Side Caching * The returned `ctx` will be canceled automatically and immediately once the `KeyMajority` is not held anymore, for example: - * Redis down. + * Valkey down. * Related keys has been deleted by other program or administrator. * The waiting `Locker.WithContext` will try acquiring the lock again automatically and immediately once it has been released by someone even from other program. @@ -45,13 +45,13 @@ func main() { When the `locker.WithContext` is invoked, it will: -1. Try acquiring 3 keys (given that `KeyMajority` is 2), which are `rueidislock:0:my_lock`, `rueidislock:1:my_lock` and `rueidislock:2:my_lock`, by sending redis command `SET NX PXAT` or `SET NX PX` if `FallbackSETPX` is set. +1. Try acquiring 3 keys (given that `KeyMajority` is 2), which are `valkeylock:0:my_lock`, `valkeylock:1:my_lock` and `valkeylock:2:my_lock`, by sending valkey command `SET NX PXAT` or `SET NX PX` if `FallbackSETPX` is set. 2. If the `KeyMajority` is satisfied within the `KeyValidity` duration, the invocation is successful and a `ctx` is returned as the lock. 3. If the invocation is not successful, it will wait for client-side caching notification to retry again. 4. If the invocation is successful, the `Locker` will extend the `ctx` validity periodically and also watch client-side caching notification for canceling the `ctx` if the `KeyMajority` is not held anymore. ### Disable Client Side Caching -Some Redis provider doesn't support client-side caching, ex. Google Cloud Memorystore. +Some Valkey provider doesn't support client-side caching, ex. Google Cloud Memorystore. You can disable client-side caching by setting `ClientOption.DisableCache` to `true`. -Please note that when the client-side caching is disabled, rueidislock will only try to re-acquire locks for every ExtendInterval. \ No newline at end of file +Please note that when the client-side caching is disabled, valkeylock will only try to re-acquire locks for every ExtendInterval. \ No newline at end of file diff --git a/rueidislock/lock.go b/valkeylock/lock.go similarity index 82% rename from rueidislock/lock.go rename to valkeylock/lock.go index a2f417d..d7d4971 100644 --- a/rueidislock/lock.go +++ b/valkeylock/lock.go @@ -1,4 +1,4 @@ -package rueidislock +package valkeylock import ( "context" @@ -11,7 +11,7 @@ import ( "sync/atomic" "time" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) var sources sync.Pool @@ -22,44 +22,44 @@ func init() { // LockerOption should be passed to NewLocker to construct a Locker type LockerOption struct { - // ClientBuilder can be used to modify rueidis.Client used by Locker - ClientBuilder func(option rueidis.ClientOption) (rueidis.Client, error) - // KeyPrefix is the prefix of redis key for locks. Default value is "rueidislock". + // ClientBuilder can be used to modify valkey.Client used by Locker + ClientBuilder func(option valkey.ClientOption) (valkey.Client, error) + // KeyPrefix is the prefix of valkey key for locks. Default value is "valkeylock". KeyPrefix string - // ClientOption is passed to rueidis.NewClient or LockerOption.ClientBuilder to build a rueidis.Client - ClientOption rueidis.ClientOption + // ClientOption is passed to valkey.NewClient or LockerOption.ClientBuilder to build a valkey.Client + ClientOption valkey.ClientOption // KeyValidity is the validity duration of locks and will be extended periodically by the ExtendInterval. Default value is 5s. KeyValidity time.Duration // ExtendInterval is the interval to extend KeyValidity. Default value is 1s. ExtendInterval time.Duration - // TryNextAfter is the timeout duration before trying the next redis key for locks. Default value is 20ms. + // TryNextAfter is the timeout duration before trying the next valkey key for locks. Default value is 20ms. TryNextAfter time.Duration - // KeyMajority is at least how many redis keys in a total of KeyMajority*2-1 should be acquired to be a valid lock. + // KeyMajority is at least how many valkey keys in a total of KeyMajority*2-1 should be acquired to be a valid lock. // Default value is 2. KeyMajority int32 // NoLoopTracking will use NOLOOP in the CLIENT TRACKING command to avoid unnecessary notifications and thus have better performance. - // This can only be enabled if all your redis nodes >= 7.0.5. (https://github.com/redis/redis/pull/11052) + // This can only be enabled if all your valkey nodes >= 7.0.5. (https://github.com/redis/redis/pull/11052) NoLoopTracking bool - // Use SET PX instead of SET PXAT when acquiring locks to be compatible with Redis < 6.2 + // Use SET PX instead of SET PXAT when acquiring locks to be compatible with Valkey < 6.2 FallbackSETPX bool } -// Locker is the interface of rueidislock +// Locker is the interface of valkeylock type Locker interface { - // WithContext acquires a distributed redis lock by name by waiting for it. It may return ErrLockerClosed. + // WithContext acquires a distributed valkey lock by name by waiting for it. It may return ErrLockerClosed. WithContext(ctx context.Context, name string) (context.Context, context.CancelFunc, error) - // TryWithContext tries to acquire a distributed redis lock by name without waiting. It may return ErrNotLocked. + // TryWithContext tries to acquire a distributed valkey lock by name without waiting. It may return ErrNotLocked. TryWithContext(ctx context.Context, name string) (context.Context, context.CancelFunc, error) - // Client exports the underlying rueidis.Client - Client() rueidis.Client - // Close closes the underlying rueidis.Client + // Client exports the underlying valkey.Client + Client() valkey.Client + // Close closes the underlying valkey.Client Close() } -// NewLocker creates the distributed Locker backed by redis client side caching +// NewLocker creates the distributed Locker backed by valkey client side caching func NewLocker(option LockerOption) (Locker, error) { if option.KeyPrefix == "" { - option.KeyPrefix = "rueidislock" + option.KeyPrefix = "valkeylock" } if option.KeyValidity <= 0 { option.KeyValidity = time.Second * 5 @@ -100,7 +100,7 @@ func NewLocker(option LockerOption) (Locker, error) { if option.ClientBuilder != nil { impl.client, err = option.ClientBuilder(option.ClientOption) } else { - impl.client, err = rueidis.NewClient(option.ClientOption) + impl.client, err = valkey.NewClient(option.ClientOption) } if err != nil { return nil, err @@ -109,7 +109,7 @@ func NewLocker(option LockerOption) (Locker, error) { } type locker struct { - client rueidis.Client + client valkey.Client gates map[string]*gate prefix string validity time.Duration @@ -143,7 +143,7 @@ func random() string { binary.BigEndian.PutUint64(val[8:16], src.Uint64()) binary.BigEndian.PutUint64(val[16:24], src.Uint64()) sources.Put(src) - return rueidis.BinaryString(val) + return valkey.BinaryString(val) } func keyname(prefix, name string, i int32) string { @@ -160,7 +160,7 @@ func keyname(prefix, name string, i int32) string { func (m *locker) acquire(ctx context.Context, key, val string, deadline time.Time) (err error) { ctx, cancel := context.WithTimeout(ctx, m.timeout) - var set rueidis.Completed + var set valkey.Completed if m.setpx { set = m.client.B().Set().Key(key).Value(val).Nx().PxMilliseconds(m.validity.Milliseconds()).Build() } else { @@ -168,13 +168,13 @@ func (m *locker) acquire(ctx context.Context, key, val string, deadline time.Tim } resp := m.client.DoMulti(ctx, set, m.client.B().Get().Key(key).Build()) cancel() - if err = resp[0].Error(); rueidis.IsRedisNil(err) { + if err = resp[0].Error(); valkey.IsValkeyNil(err) { return ErrNotLocked } return err } -func (m *locker) script(ctx context.Context, script *rueidis.Lua, key, val string, deadline time.Time) error { +func (m *locker) script(ctx context.Context, script *valkey.Lua, key, val string, deadline time.Time) error { ctx, cancel := context.WithDeadline(ctx, deadline) resp := script.Exec(ctx, m.client, []string{key}, []string{val, strconv.FormatInt(deadline.UnixMilli(), 10)}) cancel() @@ -228,7 +228,7 @@ func (m *locker) trygate(name string) (g *gate) { return g } -func (m *locker) onInvalidations(messages []rueidis.RedisMessage) { +func (m *locker) onInvalidations(messages []valkey.ValkeyMessage) { if messages == nil { m.mu.RLock() for _, g := range m.gates { @@ -375,7 +375,7 @@ func (m *locker) WithContext(ctx context.Context, name string) (context.Context, } } -func (m *locker) Client() rueidis.Client { +func (m *locker) Client() valkey.Client { return m.client } @@ -390,8 +390,8 @@ func (m *locker) Close() { } var ( - delkey = rueidis.NewLuaScript(`if redis.call("GET",KEYS[1]) == ARGV[1] then return redis.call("DEL",KEYS[1]) else return 0 end`) - extend = rueidis.NewLuaScript(`if redis.call("GET",KEYS[1]) == ARGV[1] then return redis.call("PEXPIREAT",KEYS[1],ARGV[2]) else return 0 end`) + delkey = valkey.NewLuaScript(`if redis.call("GET",KEYS[1]) == ARGV[1] then return redis.call("DEL",KEYS[1]) else return 0 end`) + extend = valkey.NewLuaScript(`if redis.call("GET",KEYS[1]) == ARGV[1] then return redis.call("PEXPIREAT",KEYS[1],ARGV[2]) else return 0 end`) ) // ErrNotLocked is returned from the Locker.TryWithContext when it fails diff --git a/rueidislock/lock_test.go b/valkeylock/lock_test.go similarity index 95% rename from rueidislock/lock_test.go rename to valkeylock/lock_test.go index 2ac5e7e..635d955 100644 --- a/rueidislock/lock_test.go +++ b/valkeylock/lock_test.go @@ -1,4 +1,4 @@ -package rueidislock +package valkeylock import ( "context" @@ -9,14 +9,14 @@ import ( "testing" "time" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) var address = []string{"127.0.0.1:6379"} func newLocker(t *testing.T, noLoop, setpx, nocsc bool) *locker { impl, err := NewLocker(LockerOption{ - ClientOption: rueidis.ClientOption{InitAddress: address, DisableCache: nocsc}, + ClientOption: valkey.ClientOption{InitAddress: address, DisableCache: nocsc}, NoLoopTracking: noLoop, FallbackSETPX: setpx, }) @@ -26,8 +26,8 @@ func newLocker(t *testing.T, noLoop, setpx, nocsc bool) *locker { return impl.(*locker) } -func newClient(t *testing.T) rueidis.Client { - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: address}) +func newClient(t *testing.T) valkey.Client { + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: address}) if err != nil { t.Fatal(err) } @@ -35,11 +35,11 @@ func newClient(t *testing.T) rueidis.Client { } func TestNewLocker(t *testing.T) { - l, err := NewLocker(LockerOption{ClientOption: rueidis.ClientOption{InitAddress: nil}}) + l, err := NewLocker(LockerOption{ClientOption: valkey.ClientOption{InitAddress: nil}}) if err == nil { t.Fatal(err) } - l, err = NewLocker(LockerOption{ClientOption: rueidis.ClientOption{InitAddress: address}}) + l, err = NewLocker(LockerOption{ClientOption: valkey.ClientOption{InitAddress: address}}) if err != nil { t.Fatal(err) } @@ -57,11 +57,11 @@ func TestNewLocker(t *testing.T) { } func TestNewLocker_WithClientBuilder(t *testing.T) { - var client rueidis.Client + var client valkey.Client l, err := NewLocker(LockerOption{ - ClientOption: rueidis.ClientOption{InitAddress: address}, - ClientBuilder: func(option rueidis.ClientOption) (_ rueidis.Client, err error) { - client, err = rueidis.NewClient(option) + ClientOption: valkey.ClientOption{InitAddress: address}, + ClientBuilder: func(option valkey.ClientOption) (_ valkey.Client, err error) { + client, err = valkey.NewClient(option) return client, err }, }) @@ -565,7 +565,7 @@ func TestLocker_RetryErrLockerClosed(t *testing.T) { func TestLocker_Flush(t *testing.T) { test := func(t *testing.T, noLoop, setpx, nocsc bool) { - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: address}) + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: address}) if err != nil { t.Fatal(err) } diff --git a/valkeyotel/README.md b/valkeyotel/README.md new file mode 100644 index 0000000..bf2d990 --- /dev/null +++ b/valkeyotel/README.md @@ -0,0 +1,33 @@ +# OpenTelemetry Tracing & Connection Metrics + +Use `valkeyotel.NewClient` to create a client with OpenTelemetry Tracing and Connection Metrics enabled. +Builtin connection metrics are: +- `valkey_dial_attempt`: number of dial attempts +- `valkey_dial_success`: number of successful dials +- `valkey_dial_conns`: number of connections +- `valkey_dial_latency`: dial latency in seconds + +Client side caching metrics: +- `valkey_do_cache_miss`: number of cache miss on client side +- `valkey_do_cache_hits`: number of cache hits on client side + +```golang +package main + +import ( + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/valkeyotel" +) + +func main() { + client, err := valkeyotel.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) + if err != nil { + panic(err) + } + defer client.Close() +} +``` + +See [valkeyhook](../valkeyhook) if you want more customizations. + +Note: `valkeyotel.NewClient` is not supported on go1.18 and go1.19 builds. [Reference](https://github.com/redis/rueidis/issues/442#issuecomment-1886993707) \ No newline at end of file diff --git a/rueidisotel/go.mod b/valkeyotel/go.mod similarity index 74% rename from rueidisotel/go.mod rename to valkeyotel/go.mod index a2bde84..f87e93a 100644 --- a/rueidisotel/go.mod +++ b/valkeyotel/go.mod @@ -1,11 +1,11 @@ -module github.com/redis/rueidis/rueidisotel +module github.com/rueian/valkey-go/valkeyotel go 1.20 -replace github.com/redis/rueidis => ../ +replace github.com/rueian/valkey-go => ../ require ( - github.com/redis/rueidis v1.0.34 + github.com/rueian/valkey-go v1.0.34 go.opentelemetry.io/otel v1.24.0 go.opentelemetry.io/otel/metric v1.24.0 go.opentelemetry.io/otel/sdk v1.24.0 diff --git a/rueidisotel/go.sum b/valkeyotel/go.sum similarity index 100% rename from rueidisotel/go.sum rename to valkeyotel/go.sum diff --git a/rueidisotel/metrics.go b/valkeyotel/metrics.go similarity index 83% rename from rueidisotel/metrics.go rename to valkeyotel/metrics.go index 44d6da4..51107fa 100644 --- a/rueidisotel/metrics.go +++ b/valkeyotel/metrics.go @@ -1,4 +1,4 @@ -package rueidisotel +package valkeyotel import ( "context" @@ -7,7 +7,7 @@ import ( "sync/atomic" "time" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" @@ -56,11 +56,11 @@ func WithHistogramOption(histogramOption HistogramOption) Option { // NewClient creates a new Client. // The following metrics are recorded: -// - rueidis_dial_attempt: number of dial attempts -// - rueidis_dial_success: number of successful dials -// - rueidis_dial_conns: number of active connections -// - rueidis_dial_latency: dial latency in seconds -func NewClient(clientOption rueidis.ClientOption, opts ...Option) (rueidis.Client, error) { +// - valkey_dial_attempt: number of dial attempts +// - valkey_dial_success: number of successful dials +// - valkey_dial_conns: number of active connections +// - valkey_dial_latency: dial latency in seconds +func NewClient(clientOption valkey.ClientOption, opts ...Option) (valkey.Client, error) { oclient, err := newClient(opts...) if err != nil { return nil, err @@ -72,23 +72,23 @@ func NewClient(clientOption rueidis.ClientOption, opts ...Option) (rueidis.Clien metrics := dialMetrics{mAttrs: oclient.mAttrs} - metrics.attempt, err = oclient.meter.Int64Counter("rueidis_dial_attempt") + metrics.attempt, err = oclient.meter.Int64Counter("valkey_dial_attempt") if err != nil { return nil, err } - metrics.success, err = oclient.meter.Int64Counter("rueidis_dial_success") + metrics.success, err = oclient.meter.Int64Counter("valkey_dial_success") if err != nil { return nil, err } - metrics.counts, err = oclient.meter.Int64UpDownCounter("rueidis_dial_conns") + metrics.counts, err = oclient.meter.Int64UpDownCounter("valkey_dial_conns") if err != nil { return nil, err } metrics.latency, err = oclient.meter.Float64Histogram( - "rueidis_dial_latency", + "valkey_dial_latency", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(oclient.histogramOption.Buckets...), ) @@ -97,7 +97,7 @@ func NewClient(clientOption rueidis.ClientOption, opts ...Option) (rueidis.Clien } clientOption.DialFn = trackDialing(metrics, clientOption.DialFn) - cli, err := rueidis.NewClient(clientOption) + cli, err := valkey.NewClient(clientOption) if err != nil { return nil, err } @@ -129,11 +129,11 @@ func newClient(opts ...Option) (*otelclient, error) { cli.tracer = cli.tracerProvider.Tracer(name) // Now create the counters using the meter var err error - cli.cscMiss, err = cli.meter.Int64Counter("rueidis_do_cache_miss") + cli.cscMiss, err = cli.meter.Int64Counter("valkey_do_cache_miss") if err != nil { return nil, err } - cli.cscHits, err = cli.meter.Int64Counter("rueidis_do_cache_hits") + cli.cscHits, err = cli.meter.Int64Counter("valkey_do_cache_hits") if err != nil { return nil, err } diff --git a/rueidisotel/metrics_test.go b/valkeyotel/metrics_test.go similarity index 83% rename from rueidisotel/metrics_test.go rename to valkeyotel/metrics_test.go index c2be606..8532917 100644 --- a/rueidisotel/metrics_test.go +++ b/valkeyotel/metrics_test.go @@ -1,4 +1,4 @@ -package rueidisotel +package valkeyotel import ( "context" @@ -11,12 +11,12 @@ import ( "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/metric/metricdata" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) func TestNewClient(t *testing.T) { t.Run("client option only", func(t *testing.T) { - c, err := NewClient(rueidis.ClientOption{ + c, err := NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, DialFn: func(dst string, dialer *net.Dialer, _ *tls.Config) (conn net.Conn, err error) { return dialer.Dial("tcp", dst) @@ -32,7 +32,7 @@ func TestNewClient(t *testing.T) { mr := metric.NewManualReader() meterProvider := metric.NewMeterProvider(metric.WithReader(mr)) c, err := NewClient( - rueidis.ClientOption{ + valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, DialFn: func(dst string, dialer *net.Dialer, _ *tls.Config) (conn net.Conn, err error) { return dialer.Dial("tcp", dst) @@ -48,7 +48,7 @@ func TestNewClient(t *testing.T) { t.Run("dial latency histogram option", func(t *testing.T) { c, err := NewClient( - rueidis.ClientOption{ + valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, DialFn: func(dst string, dialer *net.Dialer, _ *tls.Config) (conn net.Conn, err error) { return dialer.Dial("tcp", dst) @@ -65,7 +65,7 @@ func TestNewClient(t *testing.T) { }) t.Run("DialFn by default", func(t *testing.T) { - _, err := NewClient(rueidis.ClientOption{ + _, err := NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, }, ) @@ -77,7 +77,7 @@ func TestNewClient(t *testing.T) { func TestNewClientError(t *testing.T) { t.Run("invalid client option", func(t *testing.T) { - _, err := NewClient(rueidis.ClientOption{ + _, err := NewClient(valkey.ClientOption{ InitAddress: []string{""}, DialFn: func(dst string, dialer *net.Dialer, _ *tls.Config) (conn net.Conn, err error) { return dialer.Dial("tcp", dst) @@ -93,15 +93,15 @@ func TestNewClientMeterError(t *testing.T) { tests := []struct { name string }{ - {"rueidis_dial_attempt"}, {"rueidis_dial_success"}, {"rueidis_do_cache_miss"}, - {"rueidis_do_cache_hits"}, {"rueidis_dial_conns"}, {"rueidis_dial_latency"}, + {"valkey_dial_attempt"}, {"valkey_dial_success"}, {"valkey_do_cache_miss"}, + {"valkey_do_cache_hits"}, {"valkey_dial_conns"}, {"valkey_dial_latency"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { meterProvider := &MockMeterProvider{testName: tt.name} _, err := NewClient( - rueidis.ClientOption{ + valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, }, WithMeterProvider(meterProvider), @@ -118,7 +118,7 @@ func TestTrackDialing(t *testing.T) { mr := metric.NewManualReader() meterProvider := metric.NewMeterProvider(metric.WithReader(mr)) c, err := NewClient( - rueidis.ClientOption{ + valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, DialFn: func(dst string, dialer *net.Dialer, _ *tls.Config) (conn net.Conn, err error) { return dialer.Dial("tcp", dst) @@ -134,19 +134,19 @@ func TestTrackDialing(t *testing.T) { if err := mr.Collect(context.Background(), &metrics); err != nil { t.Fatal(err) } - attempt := int64CountMetric(metrics, "rueidis_dial_attempt") + attempt := int64CountMetric(metrics, "valkey_dial_attempt") if attempt != 1 { t.Errorf("attempt: got %d, want 1", attempt) } - success := int64CountMetric(metrics, "rueidis_dial_success") + success := int64CountMetric(metrics, "valkey_dial_success") if success != 1 { t.Errorf("success: got %d, want 1", success) } - conns := int64CountMetric(metrics, "rueidis_dial_conns") + conns := int64CountMetric(metrics, "valkey_dial_conns") if conns != 1 { t.Errorf("conns: got %d, want 1", conns) } - dialLatency := float64HistogramMetric(metrics, "rueidis_dial_latency") + dialLatency := float64HistogramMetric(metrics, "valkey_dial_latency") if dialLatency == 0 { t.Error("dial latency: got 0, want > 0") } @@ -157,7 +157,7 @@ func TestTrackDialing(t *testing.T) { if err := mr.Collect(context.Background(), &metrics); err != nil { t.Fatal(err) } - conns = int64CountMetric(metrics, "rueidis_dial_conns") + conns = int64CountMetric(metrics, "valkey_dial_conns") if conns != 0 { t.Errorf("conns: got %d, want 0", conns) } @@ -167,7 +167,7 @@ func TestTrackDialing(t *testing.T) { mr := metric.NewManualReader() meterProvider := metric.NewMeterProvider(metric.WithReader(mr)) c, err := NewClient( - rueidis.ClientOption{ + valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, DialFn: func(dst string, dialer *net.Dialer, _ *tls.Config) (conn net.Conn, err error) { return dialer.Dial("tcp", dst) @@ -186,7 +186,7 @@ func TestTrackDialing(t *testing.T) { if err := mr.Collect(context.Background(), &metrics); err != nil { t.Fatal(err) } - conns := int64CountMetric(metrics, "rueidis_dial_conns") + conns := int64CountMetric(metrics, "valkey_dial_conns") if conns != 0 { t.Errorf("conns: got %d, want 0", conns) } @@ -196,7 +196,7 @@ func TestTrackDialing(t *testing.T) { mr := metric.NewManualReader() meterProvider := metric.NewMeterProvider(metric.WithReader(mr)) _, err := NewClient( - rueidis.ClientOption{ + valkey.ClientOption{ InitAddress: []string{""}, DialFn: func(dst string, dialer *net.Dialer, _ *tls.Config) (conn net.Conn, err error) { return dialer.Dial("tcp", dst) @@ -212,19 +212,19 @@ func TestTrackDialing(t *testing.T) { if err := mr.Collect(context.Background(), &metrics); err != nil { t.Fatal(err) } - attempt := int64CountMetric(metrics, "rueidis_dial_attempt") + attempt := int64CountMetric(metrics, "valkey_dial_attempt") if attempt != 1 { t.Errorf("attempt: got %d, want 1", attempt) } - success := int64CountMetric(metrics, "rueidis_dial_success") + success := int64CountMetric(metrics, "valkey_dial_success") if success != 0 { t.Errorf("success: got %d, want 0", success) } - conns := int64CountMetric(metrics, "rueidis_dial_conns") + conns := int64CountMetric(metrics, "valkey_dial_conns") if conns != 0 { t.Errorf("conns: got %d, want 0", conns) } - dialLatency := float64HistogramMetric(metrics, "rueidis_dial_latency") + dialLatency := float64HistogramMetric(metrics, "valkey_dial_latency") if dialLatency != 0 { t.Error("dial latency: got 0, want 0") } diff --git a/rueidisotel/trace.go b/valkeyotel/trace.go similarity index 75% rename from rueidisotel/trace.go rename to valkeyotel/trace.go index 307f720..2001e68 100644 --- a/rueidisotel/trace.go +++ b/valkeyotel/trace.go @@ -1,4 +1,4 @@ -package rueidisotel +package valkeyotel import ( "context" @@ -10,22 +10,22 @@ import ( "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/trace" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) var ( - name = "github.com/redis/rueidis" + name = "github.com/rueian/valkey-go" kind = trace.WithSpanKind(trace.SpanKindClient) - dbattr = attribute.String("db.system", "redis") + dbattr = attribute.String("db.system", "valkey") dbstmt = attribute.Key("db.statement") ) -var _ rueidis.Client = (*otelclient)(nil) +var _ valkey.Client = (*otelclient)(nil) -// WithClient creates a new rueidis.Client with OpenTelemetry tracing enabled. +// WithClient creates a new valkey.Client with OpenTelemetry tracing enabled. // // Deprecated: use NewClient() instead. -func WithClient(client rueidis.Client, opts ...Option) rueidis.Client { +func WithClient(client valkey.Client, opts ...Option) valkey.Client { cli, err := newClient(opts...) if err != nil { panic(err) @@ -51,7 +51,7 @@ func WithTracerProvider(provider trace.TracerProvider) Option { } } -// WithDBStatement tells the tracing hook to add raw redis commands to db.statement attribute. +// WithDBStatement tells the tracing hook to add raw valkey commands to db.statement attribute. func WithDBStatement(f StatementFunc) Option { return func(o *otelclient) { o.dbStmtFunc = f @@ -62,7 +62,7 @@ func WithDBStatement(f StatementFunc) Option { type StatementFunc func(cmdTokens []string) string type otelclient struct { - client rueidis.Client + client valkey.Client meterProvider metric.MeterProvider tracerProvider trace.TracerProvider tracer trace.Tracer @@ -75,11 +75,11 @@ type otelclient struct { dbStmtFunc StatementFunc } -func (o *otelclient) B() rueidis.Builder { +func (o *otelclient) B() valkey.Builder { return o.client.B() } -func (o *otelclient) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) { +func (o *otelclient) Do(ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) { ctx, span := o.start(ctx, first(cmd.Commands()), sum(cmd.Commands()), o.tAttrs) if o.dbStmtFunc != nil { span.SetAttributes(dbstmt.String(o.dbStmtFunc(cmd.Commands()))) @@ -90,14 +90,14 @@ func (o *otelclient) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidi return } -func (o *otelclient) DoMulti(ctx context.Context, multi ...rueidis.Completed) (resp []rueidis.RedisResult) { +func (o *otelclient) DoMulti(ctx context.Context, multi ...valkey.Completed) (resp []valkey.ValkeyResult) { ctx, span := o.start(ctx, multiFirst(multi), multiSum(multi), o.tAttrs) resp = o.client.DoMulti(ctx, multi...) o.end(span, firstError(resp)) return } -func (o *otelclient) DoStream(ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResultStream) { +func (o *otelclient) DoStream(ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResultStream) { ctx, span := o.start(ctx, first(cmd.Commands()), sum(cmd.Commands()), o.tAttrs) if o.dbStmtFunc != nil { span.SetAttributes(dbstmt.String(o.dbStmtFunc(cmd.Commands()))) @@ -108,21 +108,21 @@ func (o *otelclient) DoStream(ctx context.Context, cmd rueidis.Completed) (resp return } -func (o *otelclient) DoMultiStream(ctx context.Context, multi ...rueidis.Completed) (resp rueidis.MultiRedisResultStream) { +func (o *otelclient) DoMultiStream(ctx context.Context, multi ...valkey.Completed) (resp valkey.MultiValkeyResultStream) { ctx, span := o.start(ctx, multiFirst(multi), multiSum(multi), o.tAttrs) resp = o.client.DoMultiStream(ctx, multi...) o.end(span, resp.Error()) return } -func (o *otelclient) DoCache(ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) (resp rueidis.RedisResult) { +func (o *otelclient) DoCache(ctx context.Context, cmd valkey.Cacheable, ttl time.Duration) (resp valkey.ValkeyResult) { ctx, span := o.start(ctx, first(cmd.Commands()), sum(cmd.Commands()), o.tAttrs) if o.dbStmtFunc != nil { span.SetAttributes(dbstmt.String(o.dbStmtFunc(cmd.Commands()))) } resp = o.client.DoCache(ctx, cmd, ttl) - if resp.NonRedisError() == nil { + if resp.NonValkeyError() == nil { if resp.IsCacheHit() { o.cscHits.Add(ctx, 1, o.mAttrs) } else { @@ -133,11 +133,11 @@ func (o *otelclient) DoCache(ctx context.Context, cmd rueidis.Cacheable, ttl tim return } -func (o *otelclient) DoMultiCache(ctx context.Context, multi ...rueidis.CacheableTTL) (resps []rueidis.RedisResult) { +func (o *otelclient) DoMultiCache(ctx context.Context, multi ...valkey.CacheableTTL) (resps []valkey.ValkeyResult) { ctx, span := o.start(ctx, multiCacheableFirst(multi), multiCacheableSum(multi), o.tAttrs) resps = o.client.DoMultiCache(ctx, multi...) for _, resp := range resps { - if resp.NonRedisError() == nil { + if resp.NonValkeyError() == nil { if resp.IsCacheHit() { o.cscHits.Add(ctx, 1, o.mAttrs) } else { @@ -149,8 +149,8 @@ func (o *otelclient) DoMultiCache(ctx context.Context, multi ...rueidis.Cacheabl return } -func (o *otelclient) Dedicated(fn func(rueidis.DedicatedClient) error) (err error) { - return o.client.Dedicated(func(client rueidis.DedicatedClient) error { +func (o *otelclient) Dedicated(fn func(valkey.DedicatedClient) error) (err error) { + return o.client.Dedicated(func(client valkey.DedicatedClient) error { return fn(&dedicated{ client: client, tAttrs: o.tAttrs, @@ -160,7 +160,7 @@ func (o *otelclient) Dedicated(fn func(rueidis.DedicatedClient) error) (err erro }) } -func (o *otelclient) Dedicate() (rueidis.DedicatedClient, func()) { +func (o *otelclient) Dedicate() (valkey.DedicatedClient, func()) { client, cancel := o.client.Dedicate() return &dedicated{ client: client, @@ -170,7 +170,7 @@ func (o *otelclient) Dedicate() (rueidis.DedicatedClient, func()) { }, cancel } -func (o *otelclient) Receive(ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) { +func (o *otelclient) Receive(ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) { ctx, span := o.start(ctx, first(subscribe.Commands()), sum(subscribe.Commands()), o.tAttrs) if o.dbStmtFunc != nil { span.SetAttributes(dbstmt.String(o.dbStmtFunc(subscribe.Commands()))) @@ -181,7 +181,7 @@ func (o *otelclient) Receive(ctx context.Context, subscribe rueidis.Completed, f return } -func (o *otelclient) Nodes() map[string]rueidis.Client { +func (o *otelclient) Nodes() map[string]valkey.Client { nodes := o.client.Nodes() for addr, client := range nodes { nodes[addr] = &otelclient{ @@ -205,20 +205,20 @@ func (o *otelclient) Close() { o.client.Close() } -var _ rueidis.DedicatedClient = (*dedicated)(nil) +var _ valkey.DedicatedClient = (*dedicated)(nil) type dedicated struct { - client rueidis.DedicatedClient + client valkey.DedicatedClient tracer trace.Tracer tAttrs trace.SpanStartEventOption dbStmtFunc StatementFunc } -func (d *dedicated) B() rueidis.Builder { +func (d *dedicated) B() valkey.Builder { return d.client.B() } -func (d *dedicated) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) { +func (d *dedicated) Do(ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) { ctx, span := d.start(ctx, first(cmd.Commands()), sum(cmd.Commands()), d.tAttrs) if d.dbStmtFunc != nil { span.SetAttributes(dbstmt.String(d.dbStmtFunc(cmd.Commands()))) @@ -229,14 +229,14 @@ func (d *dedicated) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidis return } -func (d *dedicated) DoMulti(ctx context.Context, multi ...rueidis.Completed) (resp []rueidis.RedisResult) { +func (d *dedicated) DoMulti(ctx context.Context, multi ...valkey.Completed) (resp []valkey.ValkeyResult) { ctx, span := d.start(ctx, multiFirst(multi), multiSum(multi), d.tAttrs) resp = d.client.DoMulti(ctx, multi...) d.end(span, firstError(resp)) return } -func (d *dedicated) Receive(ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) { +func (d *dedicated) Receive(ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) { ctx, span := d.start(ctx, first(subscribe.Commands()), sum(subscribe.Commands()), d.tAttrs) if d.dbStmtFunc != nil { span.SetAttributes(dbstmt.String(d.dbStmtFunc(subscribe.Commands()))) @@ -247,7 +247,7 @@ func (d *dedicated) Receive(ctx context.Context, subscribe rueidis.Completed, fn return } -func (d *dedicated) SetPubSubHooks(hooks rueidis.PubSubHooks) <-chan error { +func (d *dedicated) SetPubSubHooks(hooks valkey.PubSubHooks) <-chan error { return d.client.SetPubSubHooks(hooks) } @@ -266,30 +266,30 @@ func sum(s []string) (v int) { return v } -func firstError(s []rueidis.RedisResult) error { +func firstError(s []valkey.ValkeyResult) error { for _, result := range s { - if err := result.Error(); err != nil && !rueidis.IsRedisNil(err) { + if err := result.Error(); err != nil && !valkey.IsValkeyNil(err) { return err } } return nil } -func multiSum(multi []rueidis.Completed) (v int) { +func multiSum(multi []valkey.Completed) (v int) { for _, cmd := range multi { v += sum(cmd.Commands()) } return v } -func multiCacheableSum(multi []rueidis.CacheableTTL) (v int) { +func multiCacheableSum(multi []valkey.CacheableTTL) (v int) { for _, cmd := range multi { v += sum(cmd.Cmd.Commands()) } return v } -func multiFirst(multi []rueidis.Completed) string { +func multiFirst(multi []valkey.Completed) string { if len(multi) == 0 { return "" } @@ -315,7 +315,7 @@ func multiFirst(multi []rueidis.Completed) string { return sb.String() } -func multiCacheableFirst(multi []rueidis.CacheableTTL) string { +func multiCacheableFirst(multi []valkey.CacheableTTL) string { if len(multi) == 0 { return "" } @@ -361,7 +361,7 @@ func startSpan(tracer trace.Tracer, ctx context.Context, op string, size int, at } func endSpan(span trace.Span, err error) { - if err != nil && !rueidis.IsRedisNil(err) { + if err != nil && !valkey.IsValkeyNil(err) { span.RecordError(err) span.SetStatus(codes.Error, err.Error()) } else { diff --git a/rueidisotel/trace_test.go b/valkeyotel/trace_test.go similarity index 84% rename from rueidisotel/trace_test.go rename to valkeyotel/trace_test.go index a9e1145..bd1fd90 100644 --- a/rueidisotel/trace_test.go +++ b/valkeyotel/trace_test.go @@ -1,4 +1,4 @@ -package rueidisotel +package valkeyotel import ( "context" @@ -19,7 +19,7 @@ import ( metricapi "go.opentelemetry.io/otel/metric" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) var ( @@ -62,7 +62,7 @@ func (m *mockMeter) Float64Histogram(name string, options ...metricapi.Float64Hi } func TestWithClientGlobalProvider(t *testing.T) { - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { t.Fatal(err) } @@ -86,7 +86,7 @@ func TestWithClientGlobalProvider(t *testing.T) { } func TestWithClient(t *testing.T) { - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { t.Fatal(err) } @@ -111,18 +111,18 @@ func TestWithClient(t *testing.T) { testWithClient(t, client, exp, mxp) } -func testWithClient(t *testing.T, client rueidis.Client, exp *tracetest.InMemoryExporter, mxp metric.Reader) { +func testWithClient(t *testing.T, client valkey.Client, exp *tracetest.InMemoryExporter, mxp metric.Reader) { ctx := context.Background() // test empty trace - var emptyCompletedArr []rueidis.Completed + var emptyCompletedArr []valkey.Completed resps := client.DoMulti(ctx, emptyCompletedArr...) if resps != nil { t.Error("unexpected response : ", resps) } validateTrace(t, exp, "", codes.Ok) - var emtpyCacheableArr []rueidis.CacheableTTL + var emtpyCacheableArr []valkey.CacheableTTL resps = client.DoMultiCache(ctx, emtpyCacheableArr...) if resps != nil { t.Error("unexpected response : ", resps) @@ -151,39 +151,39 @@ func testWithClient(t *testing.T, client rueidis.Client, exp *tracetest.InMemory // first DoMultiCache client.DoMultiCache(ctx, - rueidis.CT(client.B().Get().Key("key1").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key2").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key3").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key4").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key5").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key6").Cache(), time.Minute)) + valkey.CT(client.B().Get().Key("key1").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key2").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key3").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key4").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key5").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key6").Cache(), time.Minute)) validateTrace(t, exp, "GET GET GET GET GET", codes.Ok) // second DoMultiCache client.DoMultiCache(ctx, - rueidis.CT(client.B().Get().Key("key1").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key2").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key3").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key4").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key5").Cache(), time.Minute), - rueidis.CT(client.B().Get().Key("key6").Cache(), time.Minute)) + valkey.CT(client.B().Get().Key("key1").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key2").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key3").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key4").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key5").Cache(), time.Minute), + valkey.CT(client.B().Get().Key("key6").Cache(), time.Minute)) validateTrace(t, exp, "GET GET GET GET GET", codes.Ok) metrics := metricdata.ResourceMetrics{} if err := mxp.Collect(ctx, &metrics); err != nil { t.Fatalf("unexpected err %v", err) } - validateMetrics(t, metrics, "rueidis_do_cache_miss", 7) // 1 (DoCache) + 6 (DoMultiCache) - validateMetrics(t, metrics, "rueidis_do_cache_hits", 7) // 1 (DoCache) + 6 (DoMultiCache) + validateMetrics(t, metrics, "valkey_do_cache_miss", 7) // 1 (DoCache) + 6 (DoMultiCache) + validateMetrics(t, metrics, "valkey_do_cache_hits", 7) // 1 (DoCache) + 6 (DoMultiCache) ctx2, cancel := context.WithTimeout(ctx, time.Second/2) - client.Receive(ctx2, client.B().Subscribe().Channel("ch").Build(), func(msg rueidis.PubSubMessage) {}) + client.Receive(ctx2, client.B().Subscribe().Channel("ch").Build(), func(msg valkey.PubSubMessage) {}) cancel() validateTrace(t, exp, "SUBSCRIBE", codes.Error) var hookCh <-chan error - client.Dedicated(func(client rueidis.DedicatedClient) error { + client.Dedicated(func(client valkey.DedicatedClient) error { client.Do(ctx, client.B().Set().Key("key").Value("val").Build()) validateTrace(t, exp, "SET", codes.Ok) @@ -205,11 +205,11 @@ func testWithClient(t *testing.T, client rueidis.Client, exp *tracetest.InMemory validateTrace(t, exp, "unknown", codes.Error) ctx2, cancel := context.WithTimeout(ctx, time.Second/2) - client.Receive(ctx2, client.B().Subscribe().Channel("ch").Build(), func(msg rueidis.PubSubMessage) {}) + client.Receive(ctx2, client.B().Subscribe().Channel("ch").Build(), func(msg valkey.PubSubMessage) {}) cancel() validateTrace(t, exp, "SUBSCRIBE", codes.Error) - hookCh = client.SetPubSubHooks(rueidis.PubSubHooks{OnMessage: func(m rueidis.PubSubMessage) {}}) + hookCh = client.SetPubSubHooks(valkey.PubSubHooks{OnMessage: func(m valkey.PubSubMessage) {}}) client.Close() @@ -240,11 +240,11 @@ func testWithClient(t *testing.T, client rueidis.Client, exp *tracetest.InMemory validateTrace(t, exp, "unknown", codes.Error) ctx2, cancel := context.WithTimeout(ctx, time.Second/2) - c.Receive(ctx2, c.B().Subscribe().Channel("ch").Build(), func(msg rueidis.PubSubMessage) {}) + c.Receive(ctx2, c.B().Subscribe().Channel("ch").Build(), func(msg valkey.PubSubMessage) {}) cancel() validateTrace(t, exp, "SUBSCRIBE", codes.Error) - hookCh = c.SetPubSubHooks(rueidis.PubSubHooks{OnMessage: func(m rueidis.PubSubMessage) {}}) + hookCh = c.SetPubSubHooks(valkey.PubSubHooks{OnMessage: func(m valkey.PubSubMessage) {}}) c.Close() } @@ -317,7 +317,7 @@ func TestWithDBStatement(t *testing.T) { } func TestWithClientSimple(t *testing.T) { - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { t.Fatal(err) } @@ -381,7 +381,7 @@ func validateMetrics(t *testing.T, metrics metricdata.ResourceMetrics, name stri } func ExampleWithClient_openTelemetry() { - client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) + client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } diff --git a/rueidisprob/README.md b/valkeyprob/README.md similarity index 82% rename from rueidisprob/README.md rename to valkeyprob/README.md index 2d529b5..9810fee 100644 --- a/rueidisprob/README.md +++ b/valkeyprob/README.md @@ -1,6 +1,6 @@ -# rueidisprob +# valkeyprob -A Probabilistic Data Structures without Redis Stack. +A Probabilistic Data Structures without Valkey Stack. ## Features @@ -20,19 +20,19 @@ import ( "context" "fmt" - "github.com/redis/rueidis" - "github.com/redis/rueidis/rueidisprob" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/valkeyprob" ) func main() { - client, err := rueidis.NewClient(rueidis.ClientOption{ + client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"localhost:6379"}, }) if err != nil { panic(err) } - bf, err := rueidisprob.NewBloomFilter(client, "bloom_filter", 1000, 0.01) + bf, err := valkeyprob.NewBloomFilter(client, "bloom_filter", 1000, 0.01) err = bf.Add(context.Background(), "hello") if err != nil { @@ -74,19 +74,19 @@ import ( "context" "fmt" - "github.com/redis/rueidis" - "github.com/redis/rueidis/rueidisprob" + "github.com/rueian/valkey-go" + "github.com/rueian/valkey-go/valkeyprob" ) func main() { - client, err := rueidis.NewClient(rueidis.ClientOption{ + client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"localhost:6379"}, }) if err != nil { panic(err) } - cbf, err := rueidisprob.NewCountingBloomFilter(client, "counting_bloom_filter", 1000, 0.01) + cbf, err := valkeyprob.NewCountingBloomFilter(client, "counting_bloom_filter", 1000, 0.01) err = cbf.Add(context.Background(), "hello") if err != nil { diff --git a/rueidisprob/bloomfilter.go b/valkeyprob/bloomfilter.go similarity index 92% rename from rueidisprob/bloomfilter.go rename to valkeyprob/bloomfilter.go index 9cc62fb..4681f10 100644 --- a/rueidisprob/bloomfilter.go +++ b/valkeyprob/bloomfilter.go @@ -1,4 +1,4 @@ -package rueidisprob +package valkeyprob import ( "context" @@ -6,7 +6,7 @@ import ( "math" "strconv" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) const ( @@ -108,14 +108,14 @@ var ( ErrBitsSizeTooLarge = errors.New("bits size is too large") ) -// BloomFilter based on Redis Bitmaps. +// BloomFilter based on Valkey Bitmaps. // BloomFilter uses 128-bit murmur3 hash function. type BloomFilter interface { // Add adds an item to the Bloom filter. Add(ctx context.Context, key string) error // AddMulti adds one or more items to the Bloom filter. - // NOTE: If keys are too many, it can block the Redis server for a long time. + // NOTE: If keys are too many, it can block the Valkey server for a long time. AddMulti(ctx context.Context, keys []string) error // Exists checks if an item is in the Bloom filter. @@ -136,10 +136,10 @@ type BloomFilter interface { } type bloomFilter struct { - client rueidis.Client + client valkey.Client // name is the name of the Bloom filter. - // It is used as a key in the Redis. + // It is used as a key in the Valkey. name string // counter is the name of the counter. @@ -152,18 +152,18 @@ type bloomFilter struct { // size is the number of bits to use. size uint - addMultiScript *rueidis.Lua + addMultiScript *valkey.Lua addMultiKeys []string - existsMultiScript *rueidis.Lua + existsMultiScript *valkey.Lua existsMultiKeys []string } // NewBloomFilter creates a new Bloom filter. -// NOTE: 'name:c' is used as a counter key in the Redis +// NOTE: 'name:c' is used as a counter key in the Valkey // to keep track of the number of items in the Bloom filter for Count method. func NewBloomFilter( - client rueidis.Client, + client valkey.Client, name string, expectedNumberOfItems uint, falsePositiveRate float64, @@ -198,9 +198,9 @@ func NewBloomFilter( hashIterations: hashIterations, hashIterationString: strconv.FormatUint(uint64(hashIterations), 10), size: size, - addMultiScript: rueidis.NewLuaScript(bloomFilterAddMultiScript), + addMultiScript: valkey.NewLuaScript(bloomFilterAddMultiScript), addMultiKeys: []string{bfName, counterName}, - existsMultiScript: rueidis.NewLuaScript(bloomFilterExistsMultiScript), + existsMultiScript: valkey.NewLuaScript(bloomFilterExistsMultiScript), existsMultiKeys: []string{bfName}, }, nil } @@ -278,7 +278,7 @@ func (c *bloomFilter) ExistsMulti(ctx context.Context, keys []string) ([]bool, e for i, el := range arr { v, err := el.AsBool() if err != nil { - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { result[i] = false continue } @@ -326,7 +326,7 @@ func (c *bloomFilter) Count(ctx context.Context) (uint, error) { Build(), ) if resp.Error() != nil { - if rueidis.IsRedisNil(resp.Error()) { + if valkey.IsValkeyNil(resp.Error()) { return 0, nil } diff --git a/rueidisprob/bloomfilter_test.go b/valkeyprob/bloomfilter_test.go similarity index 98% rename from rueidisprob/bloomfilter_test.go rename to valkeyprob/bloomfilter_test.go index cc59c8a..d6ff0a3 100644 --- a/rueidisprob/bloomfilter_test.go +++ b/valkeyprob/bloomfilter_test.go @@ -1,4 +1,4 @@ -package rueidisprob +package valkeyprob import ( "context" @@ -7,14 +7,14 @@ import ( "strconv" "testing" - "github.com/redis/rueidis" + "github.com/rueian/valkey-go" ) var address = []string{"127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003"} -func setup() (rueidis.Client, func() error, error) { - client, err := rueidis.NewClient( - rueidis.ClientOption{InitAddress: address}, +func setup() (valkey.Client, func() error, error) { + client, err := valkey.NewClient( + valkey.ClientOption{InitAddress: address}, ) if err != nil { return nil, func() error { return nil }, err @@ -760,8 +760,8 @@ func TestBloomFilterDelete(t *testing.T) { Key("{test}"). Build(), ) - if !rueidis.IsRedisNil(resp.Error()) { - t.Error("Error is not rueidis.ErrNil") + if !valkey.IsValkeyNil(resp.Error()) { + t.Error("Error is not valkey.ErrNil") } resp = client.Do( @@ -771,8 +771,8 @@ func TestBloomFilterDelete(t *testing.T) { Key("{test}:c"). Build(), ) - if !rueidis.IsRedisNil(resp.Error()) { - t.Error("Error is not rueidis.ErrNil") + if !valkey.IsValkeyNil(resp.Error()) { + t.Error("Error is not valkey.ErrNil") } }) diff --git a/rueidisprob/countingbloomfilter.go b/valkeyprob/countingbloomfilter.go similarity index 93% rename from rueidisprob/countingbloomfilter.go rename to valkeyprob/countingbloomfilter.go index 28136ac..2ccb65a 100644 --- a/rueidisprob/countingbloomfilter.go +++ b/valkeyprob/countingbloomfilter.go @@ -1,11 +1,12 @@ -package rueidisprob +package valkeyprob import ( "context" "errors" - "github.com/redis/rueidis" "math" "strconv" + + "github.com/rueian/valkey-go" ) var ( @@ -119,7 +120,7 @@ type CountingBloomFilter interface { Add(ctx context.Context, key string) error // AddMulti adds one or more items to the Counting Bloom Filter. - // NOTE: If keys are too many, it can block the Redis server for a long time. + // NOTE: If keys are too many, it can block the Valkey server for a long time. AddMulti(ctx context.Context, keys []string) error // Exists checks if an item is in the Counting Bloom Filter. @@ -134,7 +135,7 @@ type CountingBloomFilter interface { Remove(ctx context.Context, key string) error // RemoveMulti removes one or more items from the Counting Bloom Filter. - // NOTE: If keys are too many, it can block the Redis server for a long time. + // NOTE: If keys are too many, it can block the Valkey server for a long time. RemoveMulti(ctx context.Context, keys []string) error // Delete deletes the Counting Bloom Filter. @@ -155,10 +156,10 @@ type CountingBloomFilter interface { } type countingBloomFilter struct { - client rueidis.Client + client valkey.Client // name is the name of the Counting Bloom Filter. - // It is used as a key in the Redis. + // It is used as a key in the Valkey. name string // counter is the name of the counter. @@ -171,19 +172,19 @@ type countingBloomFilter struct { // size is the number of bits to use. size uint - addMultiScript *rueidis.Lua + addMultiScript *valkey.Lua addMultiKeys []string - removeMultiScript *rueidis.Lua + removeMultiScript *valkey.Lua removeMultiKeys []string } // NewCountingBloomFilter creates a new Counting Bloom Filter. -// NOTE: 'name:cbf:c' is used as a counter key in the Redis and -// 'name:cbf' is used as a filter key in the Redis +// NOTE: 'name:cbf:c' is used as a counter key in the Valkey and +// 'name:cbf' is used as a filter key in the Valkey // to keep track of the number of items in the Counting Bloom Filter for Count method. func NewCountingBloomFilter( - client rueidis.Client, + client valkey.Client, name string, expectedNumberOfItems uint, falsePositiveRate float64, @@ -216,9 +217,9 @@ func NewCountingBloomFilter( hashIterations: hashIterations, hashIterationString: strconv.FormatUint(uint64(hashIterations), 10), size: size, - addMultiScript: rueidis.NewLuaScript(countingBloomFilterAddMultiScript), + addMultiScript: valkey.NewLuaScript(countingBloomFilterAddMultiScript), addMultiKeys: []string{bfName, counterName}, - removeMultiScript: rueidis.NewLuaScript(countingBloomFilterRemoveMultiScript), + removeMultiScript: valkey.NewLuaScript(countingBloomFilterRemoveMultiScript), removeMultiKeys: []string{bfName, counterName}, }, nil } @@ -292,7 +293,7 @@ func (f *countingBloomFilter) ExistsMulti(ctx context.Context, keys []string) ([ for i, message := range messages { cnt, err := message.AsUint64() if err != nil { - if !rueidis.IsRedisNil(err) { + if !valkey.IsValkeyNil(err) { return nil, err } @@ -381,7 +382,7 @@ func (f *countingBloomFilter) ItemMinCountMulti(ctx context.Context, keys []stri for i, message := range messages { cnt, err := message.AsUint64() if err != nil { - if !rueidis.IsRedisNil(err) { + if !valkey.IsValkeyNil(err) { return nil, err } @@ -411,7 +412,7 @@ func (f *countingBloomFilter) Count(ctx context.Context) (uint, error) { ) count, err := resp.AsUint64() if err != nil { - if rueidis.IsRedisNil(err) { + if valkey.IsValkeyNil(err) { return 0, nil } diff --git a/rueidisprob/countingbloomfilter_test.go b/valkeyprob/countingbloomfilter_test.go similarity index 99% rename from rueidisprob/countingbloomfilter_test.go rename to valkeyprob/countingbloomfilter_test.go index 0888e4c..34655cb 100644 --- a/rueidisprob/countingbloomfilter_test.go +++ b/valkeyprob/countingbloomfilter_test.go @@ -1,12 +1,13 @@ -package rueidisprob +package valkeyprob import ( "context" "errors" - "github.com/redis/rueidis" "math/rand" "strconv" "testing" + + "github.com/rueian/valkey-go" ) func TestNewCountingBloomFilter(t *testing.T) { @@ -1139,8 +1140,8 @@ func TestCountingBloomFilterDelete(t *testing.T) { Key("{test}:cbf"). Build(), ) - if !rueidis.IsRedisNil(resp.Error()) { - t.Error("Error is not rueidis.ErrNil") + if !valkey.IsValkeyNil(resp.Error()) { + t.Error("Error is not valkey.ErrNil") } resp = client.Do( @@ -1150,8 +1151,8 @@ func TestCountingBloomFilterDelete(t *testing.T) { Key("{test}:cbf:c"). Build(), ) - if !rueidis.IsRedisNil(resp.Error()) { - t.Error("Error is not rueidis.ErrNil") + if !valkey.IsValkeyNil(resp.Error()) { + t.Error("Error is not valkey.ErrNil") } }) diff --git a/valkeyprob/go.mod b/valkeyprob/go.mod new file mode 100644 index 0000000..d4c91e0 --- /dev/null +++ b/valkeyprob/go.mod @@ -0,0 +1,12 @@ +module github.com/rueian/valkey-go/valkeyprob + +go 1.20.0 + +replace github.com/rueian/valkey-go => ../ + +require ( + github.com/rueian/valkey-go v1.0.34 + github.com/twmb/murmur3 v1.1.8 +) + +require golang.org/x/sys v0.17.0 // indirect diff --git a/rueidisprob/go.sum b/valkeyprob/go.sum similarity index 100% rename from rueidisprob/go.sum rename to valkeyprob/go.sum diff --git a/rueidisprob/index.go b/valkeyprob/index.go similarity index 91% rename from rueidisprob/index.go rename to valkeyprob/index.go index cf871af..149c5da 100644 --- a/rueidisprob/index.go +++ b/valkeyprob/index.go @@ -1,4 +1,4 @@ -package rueidisprob +package valkeyprob import "github.com/twmb/murmur3"