before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
}
}
// FindPortAndBind binds the server to the given host and port
func (s *AsyncServer) FindPortAndBind() error {
serverFD, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
if err != nil {
return err
}
s.serverFD = serverFD
if err := syscall.SetsockoptInt(serverFD, syscall.SOL_SOCKET, syscall.S... | Shall we handle this condition here for [ParseIP](https://pkg.go.dev/net#ParseIP)?
> If s is not a valid textual representation of an IP address, ParseIP returns nil. | // FindPortAndBind binds the server to the given host and port
func (s *AsyncServer) FindPortAndBind() (err error) {
serverFD, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
if err != nil {
return err
}
s.serverFD = serverFD
// Close the socket on exit if an error occurs
defer func() {
if err... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.5 | suggestion | 167 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | lucifercr07 | JyotinderSingh |
"time"
"github.com/charmbracelet/log"
"github.com/dicedb/dice/config"
"github.com/dicedb/dice/core"
"github.com/dicedb/dice/core/iomultiplexer"
"github.com/dicedb/dice/internal/constants"
"github.com/dicedb/dice/server/utils"
)
type AsyncServer struct {
serverFD int
ctx context.Context
... | There is no need to create a context in the internal function, instead have it in the main and propagate it to each respective method associated with this function | "syscall"
"time"
"github.com/charmbracelet/log"
"github.com/dicedb/dice/config"
"github.com/dicedb/dice/core"
"github.com/dicedb/dice/core/iomultiplexer"
"github.com/dicedb/dice/internal/constants"
"github.com/dicedb/dice/server/utils"
)
var ErrAborted = errors.New("server received ABORT command")
var ErrInva... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.429 | suggestion | 163 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | AshwinKul28 | JyotinderSingh |
log.Error(err)
return true
}
encodedResult := core.Encode(core.CreatePushResponse(&query, &queryResult), false)
clients.Range(func(clientKey, _ interface{}) bool {
clientFd := clientKey.(int)
_, err := syscall.Write(clientFd, encodedResult)
if err != nil {
s.store.Re... | Shall we defer socket close here in case any of the below operation fails?
```
defer func() {
if err != nil {
syscall.Close(serverFD)
}
}()
``` |
encodedResult := core.Encode(core.CreatePushResponse(&query, &queryResult), false)
clients.Range(func(clientKey, _ interface{}) bool {
clientFd := clientKey.(int)
_, err := syscall.Write(clientFd, encodedResult)
if err != nil {
s.store.RemoveWatcher(query, clientFd)
}
ret... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.714 | bug | 182 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | lucifercr07 | JyotinderSingh |
ctx: ctx,
cancel: cancel,
wg: wg,
maxClients: 20000,
connectedClients: make(map[int]*core.Client),
store: core.NewStore(),
lastCronExecTime: utils.GetCurrentTime(),
cronFrequency: 1 * time.Second,
}
}
// SetupUsers initializes the default user f... | ```suggestion
func (s *AsyncServer) WatchKeys(ctx context.Context) {
```
Context can be passed here. And later we can think do we really want to wait on the context? I mean that case is required or not, for graceful shutdown we can have other ways. | maxClients: config.ServerMaxClients,
connectedClients: make(map[int]*core.Client),
store: core.NewStore(),
multiplexerPollTimeout: config.ServerMultiplexerPollTimeout,
lastCronExecTime: utils.GetCurrentTime(),
cronFrequency: config.ServerCronFrequency,
}
}
... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.786 | suggestion | 252 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | AshwinKul28 | JyotinderSingh |
// FindPortAndBind binds the server to the given host and port
func (s *AsyncServer) FindPortAndBind() error {
serverFD, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
if err != nil {
return err
}
s.serverFD = serverFD
if err := syscall.SetsockoptInt(serverFD, syscall.SOL_SOCKET, syscall.SO_REUS... | Same thought, we can pass the context here.
```suggestion
func (s *AsyncServer) Run(ctx context.Context) error {
``` | if err != nil {
return err
}
s.serverFD = serverFD
// Close the socket on exit if an error occurs
defer func() {
if err != nil {
if err := syscall.Close(serverFD); err != nil {
log.Warn("failed to close server socket", "error", err)
}
}
}()
if err := syscall.SetsockoptInt(serverFD, syscall.SOL_... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.857 | suggestion | 120 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | AshwinKul28 | JyotinderSingh |
type AsyncServer struct {
serverFD int
ctx context.Context
cancel context.CancelFunc
wg *sync.WaitGroup
maxClients int
multiplexer iomultiplexer.IOMultiplexer
connectedClients map[int]*core.Client
store *core.Store
lastCronExecTime time.Time
c... | nit: Shall we make this as part of config? |
var ErrAborted = errors.New("server received ABORT command")
var ErrInvalidIPAddress = errors.New("invalid IP address")
type AsyncServer struct {
serverFD int
maxClients int
multiplexer iomultiplexer.IOMultiplexer
multiplexerPollTimeout time.Duration
connectedClients ma... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.071 | question | 42 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | lucifercr07 | JyotinderSingh |
}
s.wg.Add(1)
go s.WatchKeys()
if err := syscall.Listen(s.serverFD, s.maxClients); err != nil {
return err
}
var err error
s.multiplexer, err = iomultiplexer.New(s.maxClients)
if err != nil {
return err
}
defer s.multiplexer.Close()
if err := s.multiplexer.Subscribe(iomultiplexer.Event{
Fd: s.serve... | `syscall.Listen` wouldn't be suffice to limit maxClients to be connected to server as it represents the backlog. Shall we add an explicit check also? | }
// Run starts the server, accepts connections, and handles client requests
func (s *AsyncServer) Run(ctx context.Context) error {
defer func(fd int) {
err := syscall.Close(fd)
if err != nil {
log.Warn("failed to close server socket", "error", err)
}
}(s.serverFD)
watchCtx, cancelWatch := context.WithCan... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.5 | question | 149 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | lucifercr07 | JyotinderSingh |
"github.com/dicedb/dice/server/utils"
)
type AsyncServer struct {
serverFD int
ctx context.Context
cancel context.CancelFunc
wg *sync.WaitGroup
maxClients int
multiplexer iomultiplexer.IOMultiplexer
connectedClients map[int]*core.Client
store ... | Shall this be made concurrent map as not thread-safe? | "github.com/dicedb/dice/internal/constants"
"github.com/dicedb/dice/server/utils"
)
var ErrAborted = errors.New("server received ABORT command")
var ErrInvalidIPAddress = errors.New("invalid IP address")
type AsyncServer struct {
serverFD int
maxClients int
multiplexer iomult... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.357 | question | 54 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | lucifercr07 | JyotinderSingh |
core.DeleteExpiredKeys(s.store)
s.lastCronExecTime = utils.GetCurrentTime()
}
events, err := s.multiplexer.Poll(-1)
if err != nil {
// Check for context cancellation on error
if s.ctx.Err() != nil {
s.initiateShutdown()
return nil
}
continue
}
for _, event := range eve... | nit: Would `s.initiateShutdown()` have the same affect here and maintain consistent error handling? | return err
}
defer func(multiplexer iomultiplexer.IOMultiplexer) {
err := multiplexer.Close()
if err != nil {
log.Warn("failed to close multiplexer", "error", err)
}
}(s.multiplexer)
if err := s.multiplexer.Subscribe(iomultiplexer.Event{
Fd: s.serverFD,
Op: iomultiplexer.OpRead,
}); err != nil {
... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.5 | question | 99 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | lucifercr07 | JyotinderSingh |
if s.ctx.Err() != nil {
s.initiateShutdown()
return nil
}
continue
}
for _, event := range events {
if event.Fd == s.serverFD {
fd, _, err := syscall.Accept(s.serverFD)
if err != nil {
log.Warn(err)
continue
}
s.connectedClients[fd] = core.NewClient(fd)
... | nit: Would s.initiateShutdown() have the same affect here and maintain consistent error handling? | }
}(s.multiplexer)
if err := s.multiplexer.Subscribe(iomultiplexer.Event{
Fd: s.serverFD,
Op: iomultiplexer.OpRead,
}); err != nil {
return err
}
err = s.eventLoop(ctx)
cancelWatch()
wg.Wait()
return err
}
// eventLoop listens for events and handles client requests. It also runs a cron job to delet... | @@ -17,247 +16,211 @@ import (
"github.com/dicedb/dice/server/utils"
)
-var cronFrequency time.Duration = 1 * time.Second
-var lastCronExecTime time.Time = utils.GetCurrentTime()
-
-const EngineStatusWAITING int32 = 1 << 1
-const EngineStatusBUSY int32 = 1 << 2
-const EngineStatusSHUTTINGDOWN int32 = 1 << 3
-const... | server/async_tcp.go | 26 | Go | 0.357 | question | 97 | 51 | 51 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | lucifercr07 | JyotinderSingh |
func main() {
setupFlags()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Handle SIGTERM and SIGINT
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)
// Initialize the AsyncServer
asyncServer := server.NewAsyncServer()
// Find a port and bind it... | This comment may be removed now. | func main() {
setupFlags()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Handle SIGTERM and SIGINT
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)
// Initialize the AsyncServer
asyncServer := server.NewAsyncServer()
// Find a port and bind it... | @@ -24,29 +25,46 @@ func setupFlags() {
func main() {
setupFlags()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
// Handle SIGTERM and SIGINT
- var sigs chan os.Signal = make(chan os.Signal, 1)
+ sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)... | main.go | 26 | Go | 0.143 | suggestion | 32 | 47 | 46 | false | Reorganize async server code | 410 | DiceDB/dice | 10,326 | C | soumya-codes | JyotinderSingh |
store.PutAll(insertMap)
return RespOK
}
// evalGET returns the value for the queried key in args
// The key should be the only param in args
// The RESP value of the key is encoded and then returned
// evalGET returns RespNIL if key is expired or it does not exist
func evalGET(args []string, store *Store) []byte {
... | Please remove this function as encoding is to be done as part of `toEncodedMessage()`.
`WrongTypeErr` is already used at multiple places, we can follow the same pattern.
Ref: `return diceerrors.NewErrWithMessage(diceerrors.WrongTypeErr)` |
store.PutAll(insertMap)
return RespOK
}
// evalGET returns the value for the queried key in args
// The key should be the only param in args
// The RESP value of the key is encoded and then returned
// evalGET returns RespNIL if key is expired or it does not exist
func evalGET(args []string, store *Store) []byte {
... | @@ -261,6 +261,11 @@ func evalGET(args []string, store *Store) []byte {
return RespNIL
}
+ // If the object exists, check if it is a set object.
+ if err := assertType(obj.TypeEncoding, ObjTypeSet); err == nil {
+ return diceerrors.NewErrSetType() | core/eval.go | 26 | Go | 0.786 | bug | 239 | 51 | 51 | false | #411: Add asserts checking non-set commands: addresses #411 | 413 | DiceDB/dice | 10,326 | C | lucifercr07 | apoorvyadav1111 |
}
store.PutAll(insertMap)
return RespOK
}
// evalGET returns the value for the queried key in args
// The key should be the only param in args
// The RESP value of the key is encoded and then returned
// evalGET returns RespNIL if key is expired or it does not exist
func evalGET(args []string, store *Store) []byte... | Shall L270 i.e `switch _, oEnc := ExtractTypeEncoding(obj); oEnc` shouldn't handle this case?
Any specific reasons to introduce this check here? | }
store.PutAll(insertMap)
return RespOK
}
// evalGET returns the value for the queried key in args
// The key should be the only param in args
// The RESP value of the key is encoded and then returned
// evalGET returns RespNIL if key is expired or it does not exist
func evalGET(args []string, store *Store) []byte... | @@ -261,6 +261,11 @@ func evalGET(args []string, store *Store) []byte {
return RespNIL
}
+ // If the object exists, check if it is a set object.
+ if err := assertType(obj.TypeEncoding, ObjTypeSet); err == nil { | core/eval.go | 26 | Go | 0.714 | refactor | 145 | 51 | 51 | false | #411: Add asserts checking non-set commands: addresses #411 | 413 | DiceDB/dice | 10,326 | C | lucifercr07 | apoorvyadav1111 |
}
}
func (w *QueryWatcher) Run(ctx context.Context) {
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
w.Watch(ctx)
}()
<-ctx.Done()
wg.Wait()
}
// Watch watches for changes in keys and notifies clients
func (w *QueryWatcher) Watch(ctx context.Context) {
for {
select {
case event := <-Wa... | Just realised this event should be captured in an independent goroutine, otherwise the subscription/unsubscription flows remain blocked as long as this goroutine is executing a query. | }
func (w *QueryWatcher) Run(ctx context.Context) {
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
w.listenForSubscriptions(ctx)
}()
wg.Add(1)
go func() {
defer wg.Done()
w.watchKeys(ctx)
}()
<-ctx.Done()
wg.Wait()
}
// listenForSubscriptions listens for query subscriptions and unsub... | @@ -0,0 +1,122 @@
+package core
+
+import (
+ "context"
+ "github.com/charmbracelet/log"
+ "sync"
+ "syscall"
+)
+
+// WatchEvent Event to notify clients about changes in query results due to key updates
+type WatchEvent struct {
+ Key string
+ Operation string
+ Value *Obj
+}
+
+// WatchSubscription Event to... | core/query_watcher.go | 26 | Go | 0.429 | suggestion | 183 | 51 | 51 | false | Move QWATCH logic to QueryWatcher | 416 | DiceDB/dice | 10,326 | C | JyotinderSingh | JyotinderSingh |
package core
import (
"context"
"github.com/charmbracelet/log"
"sync"
"syscall"
)
// WatchEvent Event to notify clients about changes in query results due to key updates
type WatchEvent struct {
Key string
Operation string
Value *Obj
}
// WatchSubscription Event to watch/unwatch a query
type WatchSu... | I think we do not need the Value field as of now. | package core
import (
"context"
"github.com/charmbracelet/log"
"sync"
"syscall"
)
// WatchEvent Event to notify clients about changes in query results due to key updates
type WatchEvent struct {
Key string
Operation string
}
// WatchSubscription Event to watch/unwatch a query
type WatchSubscription struc... | @@ -0,0 +1,122 @@
+package core
+
+import (
+ "context"
+ "github.com/charmbracelet/log"
+ "sync"
+ "syscall"
+)
+
+// WatchEvent Event to notify clients about changes in query results due to key updates
+type WatchEvent struct {
+ Key string
+ Operation string
+ Value *Obj | core/query_watcher.go | 14 | Go | 0.071 | suggestion | 49 | 39 | 39 | false | Move QWATCH logic to QueryWatcher | 416 | DiceDB/dice | 10,326 | C | soumya-codes | JyotinderSingh |
package core
import (
"context"
"github.com/charmbracelet/log"
"sync"
"syscall"
)
// WatchEvent Event to notify clients about changes in query results due to key updates
type WatchEvent struct {
Key string
Operation string
Value *Obj
}
// WatchSubscription Event to watch/unwatch a query
type WatchSu... | How about moving WatchChan and WatchSubscriptionChan inside the store given that it's liefecycle is tightly coupled with the store. This way we can avoid making the channels global. | package core
import (
"context"
"github.com/charmbracelet/log"
"sync"
"syscall"
)
// WatchEvent Event to notify clients about changes in query results due to key updates
type WatchEvent struct {
Key string
Operation string
}
// WatchSubscription Event to watch/unwatch a query
type WatchSubscription struc... | @@ -0,0 +1,122 @@
+package core
+
+import (
+ "context"
+ "github.com/charmbracelet/log"
+ "sync"
+ "syscall"
+)
+
+// WatchEvent Event to notify clients about changes in query results due to key updates
+type WatchEvent struct {
+ Key string
+ Operation string
+ Value *Obj
+}
+
+// WatchSubscription Event to... | core/query_watcher.go | 24 | Go | 0.429 | suggestion | 181 | 49 | 49 | false | Move QWATCH logic to QueryWatcher | 416 | DiceDB/dice | 10,326 | C | soumya-codes | JyotinderSingh |
name string
commands []string
expected []interface{}
}{
{
name: "PFADD with one key-value pair",
commands: []string{"PFADD hll0 v1", "PFCOUNT hll0"},
expected: []interface{}{int64(1), int64(1)},
},
{
name: "PFADD with multiple key-value pairs",
commands: []string{"PFADD hll a b c... | Could you add another test case that verifies behaviour when you call PFCOUNT with multiple HLLs and one or more HLLs don't actually exist. | name string
commands []string
expected []interface{}
}{
{
name: "PFADD with one key-value pair",
commands: []string{"PFADD hll0 v1", "PFCOUNT hll0"},
expected: []interface{}{int64(1), int64(1)},
},
{
name: "PFADD with multiple key-value pairs",
commands: []string{"PFADD hll a b c... | @@ -0,0 +1,51 @@
+package tests
+
+// All commands related to Hyperloglog are part of this test class
+// PFADD, PFCOUNT, PFMERGE, PFDEBUG, PFSELFTEST etc.
+import (
+ "gotest.tools/v3/assert"
+ "testing"
+)
+
+func TestHyperLogLogCommands(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ testCase... | tests/hyperloglog_test.go | 26 | Go | 0.429 | suggestion | 139 | 38 | 45 | false | #238: PFADD/PFCOUNT implementation | 422 | DiceDB/dice | 10,326 | C | JyotinderSingh | lucifercr07 |
package server
import (
"context"
"fmt"
"net"
"sync"
"testing"
"time"
"github.com/dicedb/dice/integration_tests/commands"
"gotest.tools/v3/assert"
"github.com/dicedb/dice/config"
)
func getConnection() (net.Conn, error) {
conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", maxConnTestOptions.Port))
... | This can be a local variable of the test function | package server
import (
"context"
"fmt"
"log/slog"
"net"
"sync"
"testing"
"time"
"gotest.tools/v3/assert"
commands "github.com/dicedb/dice/integration_tests/commands/async"
)
func getConnection(port int) (net.Conn, error) {
conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
if err != nil {
... | @@ -0,0 +1,59 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/dicedb/dice/integration_tests/commands"
+ "gotest.tools/v3/assert"
+
+ "github.com/dicedb/dice/config"
+)
+
+func getConnection() (net.Conn, error) {
+ conn, err := net.Dial("tcp", fmt.Sprintf("localho... | integration_tests/server/max_conn_test.go | 25 | Go | 0.071 | suggestion | 49 | 50 | 50 | false | #415: Adding check for controlling the max TCP connections | 426 | DiceDB/dice | 10,326 | C | JyotinderSingh | ayush571995 |
if err != nil {
return nil, err
}
return conn, nil
}
var maxConnTestOptions = commands.TestServerOptions{
Port: 8741,
}
func TestMaxConnection(t *testing.T) {
var wg sync.WaitGroup
commands.RunTestServer(context.Background(), &wg, maxConnTestOptions)
time.Sleep(2 * time.Second)
var maxConnLimit = config.T... | Why do we need to add a sleep here? | if err != nil {
return nil, err
}
return conn, nil
}
func TestMaxConnection(t *testing.T) {
var wg sync.WaitGroup
var maxConnTestOptions = commands.TestServerOptions{
Port: 8741,
MaxClients: 50,
Logger: slog.Default(),
}
commands.RunTestServer(context.Background(), &wg, maxConnTestOptions)
t... | @@ -0,0 +1,59 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/dicedb/dice/integration_tests/commands"
+ "gotest.tools/v3/assert"
+
+ "github.com/dicedb/dice/config"
+)
+
+func getConnection() (net.Conn, error) {
+ conn, err := net.Dial("tcp", fmt.Sprintf("localho... | integration_tests/server/max_conn_test.go | 26 | Go | 0.071 | question | 35 | 42 | 39 | false | #415: Adding check for controlling the max TCP connections | 426 | DiceDB/dice | 10,326 | C | JyotinderSingh | ayush571995 |
time.Sleep(2 * time.Second)
var maxConnLimit = config.TestServerMaxClients + 2
connections := make([]net.Conn, maxConnLimit)
for i := 0; i < maxConnLimit; i++ {
conn, err := getConnection()
if err == nil {
connections[i] = conn
} else {
t.Fatalf("unexpected error while getting connection %d: %v", i, e... | Why do we need this when we already have a waitgroup | commands.RunTestServer(context.Background(), &wg, maxConnTestOptions)
time.Sleep(2 * time.Second)
var maxConnLimit = maxConnTestOptions.MaxClients + 2
connections := make([]net.Conn, maxConnLimit)
for i := 0; i < maxConnLimit; i++ {
conn, err := getConnection(maxConnTestOptions.Port)
if err == nil {
conne... | @@ -0,0 +1,59 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/dicedb/dice/integration_tests/commands"
+ "gotest.tools/v3/assert"
+
+ "github.com/dicedb/dice/config"
+)
+
+func getConnection() (net.Conn, error) {
+ conn, err := net.Dial("tcp", fmt.Sprintf("localho... | integration_tests/server/max_conn_test.go | 26 | Go | 0.214 | suggestion | 52 | 29 | 26 | false | #415: Adding check for controlling the max TCP connections | 426 | DiceDB/dice | 10,326 | C | JyotinderSingh | ayush571995 |
// NewAsyncServer initializes a new AsyncServer
func NewAsyncServer(shardManager *shard.ShardManager, watchChan chan dstore.WatchEvent) *AsyncServer {
return &AsyncServer{
maxClients: config.DiceConfig.Server.MaxClients,
connectedClients: make(map[int]*comm.Client),
shardManager: shar... | We shouldn't need to define a new method like this. | }
// NewAsyncServer initializes a new AsyncServer
func NewAsyncServer(shardManager *shard.ShardManager, watchChan chan dstore.WatchEvent, logger *slog.Logger) *AsyncServer {
return &AsyncServer{
maxClients: config.DiceConfig.Server.MaxClients,
connectedClients: make(map[int]*comm.Client),
shar... | @@ -55,6 +55,19 @@ func NewAsyncServer(shardManager *shard.ShardManager, watchChan chan dstore.Watc
}
}
+// NewAsyncTestServer initializes a new TestAsyncServer which reads test config
+func NewAsyncTestServer(shardManager *shard.ShardManager, watchChan chan dstore.WatchEvent) *AsyncServer {
+ return &AsyncServer{... | internal/server/server.go | 26 | Go | 0.286 | suggestion | 51 | 51 | 51 | false | #415: Adding check for controlling the max TCP connections | 426 | DiceDB/dice | 10,326 | C | JyotinderSingh | ayush571995 |
if event.Fd == s.serverFD {
if err := s.acceptConnection(); err != nil {
s.logger.Warn(err.Error())
}
} else {
if err := s.handleClientEvent(event); err != nil {
if errors.Is(err, ErrAborted) {
s.logger.Debug("Received abort command, initiating graceful shutdown")
return... | Ideally it's not a good practice have same number of maxClients value as the backlog queue max number which is being set during `listen()`. Shouldn't be a blocker for this PR, but we should revisit this later. | if event.Fd == s.serverFD {
if err := s.acceptConnection(); err != nil {
s.logger.Warn(err.Error())
// Close the event FD on error
if closeErr := syscall.Close(event.Fd); closeErr != nil {
s.logger.Error("Failed to close event FD:", slog.Any("error", closeErr))
}
}
} els... | @@ -238,6 +242,10 @@ func (s *AsyncServer) eventLoop(ctx context.Context) error {
// acceptConnection accepts a new client connection and subscribes to read events on the connection.
func (s *AsyncServer) acceptConnection() error {
+ if len(s.connectedClients) > s.maxClients { | internal/server/server.go | 26 | Go | 0.643 | suggestion | 209 | 51 | 51 | false | #415: Adding check for controlling the max TCP connections | 426 | DiceDB/dice | 10,326 | C | lucifercr07 | ayush571995 |
return Encode(obj.Value, false)
}
// evalJSONDEL delete a value that the given json path include in.
// Returns RespZero if key is expired or it does not exist
// Returns encoded error response if incorrect number of arguments
// Returns an integer reply specified as the number of paths deleted (0 or more)
func evalJ... | L346-L353 has similar sort of code and is used in another places as well example `JSON.CLEAR, JSON.GET` etc. May be we can extract out as function like below:
```
func assertTypeAndEncoding(typeEncoding, expectedType, expectedEncoding uint8) error {
if err := assertType(typeEncoding, expectedType); err != nil {
... | return Encode(obj.Value, false)
}
// evalJSONDEL delete a value that the given json path include in.
// Returns RespZero if key is expired or it does not exist
// Returns encoded error response if incorrect number of arguments
// Returns an integer reply specified as the number of paths deleted (0 or more)
func evalJ... | @@ -321,6 +321,64 @@ func evalGETDEL(args []string, store *Store) []byte {
return Encode(obj.Value, false)
}
+// evalJSONDEL delete a value that the given json path include in.
+// Returns RespZero if key is expired or it does not exist
+// Returns encoded error response if incorrect number of arguments
+// Return... | core/eval.go | 26 | Go | 1 | bug | 568 | 51 | 51 | false | #419: feat: add support for command [JSON.DEL] | 428 | DiceDB/dice | 10,326 | C | lucifercr07 | jujiale |
{
commands: []string{"HSET key field value", "HSET key field2 value_new", "HGETALL key"},
expected: []interface{}{ONE, ONE, []string{"field", "value", "field2", "value_new"}},
},
{
commands: []string{"HGETALL key3"},
expected: []interface{}{[]interface{}{}},
},
{
commands: []string{"SET key fie... | did this because results can be unordered. | testCases := []TestCase{
{
commands: []string{"HSET key_hGetAll field value", "HSET key_hGetAll field2 value_new", "HGETALL key_hGetAll"},
expected: []interface{}{ONE, ONE, []string{"field", "value", "field2", "value_new"}},
},
{
commands: []string{"HGETALL key_hGetAll01"},
expected: []interface{}{[]... | @@ -0,0 +1,54 @@
+package tests
+
+import (
+ "gotest.tools/v3/assert"
+ "reflect"
+ "testing"
+)
+
+func TestHGETALL(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ testCases := []TestCase{
+ {
+ commands: []string{"HSET key field value", "HSET key field2 value_new", "HGETALL key"},
+ expe... | tests/hgetall_test.go | 26 | Go | 0.143 | suggestion | 42 | 42 | 47 | false | #257: Feat: Added support for HGETALL | 431 | DiceDB/dice | 10,326 | C | raghavbabbar | raghavbabbar |
commands: []string{"SET key_hGetAll02 field", "HGETALL key_hGetAll02"},
expected: []interface{}{"OK", "WRONGTYPE Operation against a key holding the wrong kind of value"},
},
{
commands: []string{"HGETALL key_hGetAll03 x", "HGETALL"},
expected: []interface{}{"ERR wrong number of arguments for 'hgetall' ... | made map because as results can be in unordered state too. | {
commands: []string{"SET key_hGetAll02 field", "HGETALL key_hGetAll02"},
expected: []interface{}{"OK", "WRONGTYPE Operation against a key holding the wrong kind of value"},
},
{
commands: []string{"HGETALL key_hGetAll03 x", "HGETALL"},
expected: []interface{}{"ERR wrong number of arguments for 'hgeta... | @@ -0,0 +1,58 @@
+package tests
+
+import (
+ "gotest.tools/v3/assert"
+ "reflect"
+ "testing"
+)
+
+func TestHGETALL(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ testCases := []TestCase{
+ {
+ commands: []string{"HSET key_hGetAll field value", "HSET key_hGetAll field2 value_new", "HGETALL... | tests/hgetall_test.go | 26 | Go | 0.286 | suggestion | 58 | 37 | 38 | false | #257: Feat: Added support for HGETALL | 431 | DiceDB/dice | 10,326 | C | raghavbabbar | raghavbabbar |
store.Put(key, obj)
return Encode(numKeys, false)
}
func evalHGETALL(args []string, store *Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrArity("HGETALL")
}
key := args[0]
obj := store.Get(key)
var hashMap HashMap
var results []string
if obj != nil {
switch currentVal := obj.Value.(type... | Let's use assertTypeEncoding for this check, and please do the same for existing evalHSET method. | if len(args) == 0 {
return diceerrors.NewErrArity("TOUCH")
}
count := 0
for _, key := range args {
if store.Get(key) != nil {
count++
}
}
return Encode(count, false)
}
func evalLPUSH(args []string, store *Store) []byte {
if len(args) < 2 {
return diceerrors.NewErrArity("LPUSH")
}
obj := store.Ge... | @@ -2469,6 +2469,34 @@ func evalHSET(args []string, store *Store) []byte {
return Encode(numKeys, false)
}
+func evalHGETALL(args []string, store *Store) []byte {
+ if len(args) != 1 {
+ return diceerrors.NewErrArity("HGETALL")
+ }
+
+ key := args[0]
+
+ obj := store.Get(key)
+
+ var hashMap HashMap
+ var results... | core/eval.go | 26 | Go | 0.429 | suggestion | 97 | 51 | 51 | false | #257: Feat: Added support for HGETALL | 431 | DiceDB/dice | 10,326 | C | JyotinderSingh | raghavbabbar |
func TestHGETALL(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
testCases := []TestCase{
{
commands: []string{"HSET key_hGetAll field value", "HSET key_hGetAll field2 value_new", "HGETALL key_hGetAll"},
expected: []interface{}{ONE, ONE, []string{"field", "value", "field2", "value_new"}},
... | Run cleanup logic using defer to cleanup the keys after the test is done. That may also be the reason why your tests were failing earlier. All integration tests share the same server, therefore each test needs to ensure it cleans up its resources once its done. | func TestHGETALL(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
defer fireCommand(conn, "DEL key_hGetAll key_hGetAll02")
testCases := []TestCase{
{
commands: []string{"HSET key_hGetAll field value", "HSET key_hGetAll field2 value_new", "HGETALL key_hGetAll"},
expected: []interface{}{ONE, O... | @@ -0,0 +1,58 @@
+package tests
+
+import (
+ "gotest.tools/v3/assert"
+ "reflect"
+ "testing"
+)
+
+func TestHGETALL(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ testCases := []TestCase{
+ {
+ commands: []string{"HSET key_hGetAll field value", "HSET key_hGetAll field2 value_new", "HGETALL... | tests/hgetall_test.go | 26 | Go | 0.429 | bug | 261 | 51 | 51 | false | #257: Feat: Added support for HGETALL | 431 | DiceDB/dice | 10,326 | C | JyotinderSingh | raghavbabbar |
buf := bytes.NewBuffer(b)
for _, b := range value.([]int64) {
buf.Write(Encode(b, false))
}
return []byte(fmt.Sprintf("*%d\r\n%s", len(v), buf.Bytes()))
case error:
return []byte(fmt.Sprintf("-%s\r\n", v))
case dstore.WatchEvent:
var b []byte
buf := bytes.NewBuffer(b)
we := value.(dstore.WatchEvent... | @aashraybhandar1 can you please rebase once and validate, this call would error out as `DiceCmdMeta` is part of `eval` now.
Also I believe we should keep type as `[]interface{}` we have similar response in `QWATCH` you can take a reference of `CreatePushResponse` function may be. | buf := bytes.NewBuffer(b)
for _, b := range value.([]int64) {
buf.Write(Encode(b, false))
}
return []byte(fmt.Sprintf("*%d\r\n%s", len(v), buf.Bytes()))
case error:
return []byte(fmt.Sprintf("-%s\r\n", v))
case dstore.WatchEvent:
var b []byte
buf := bytes.NewBuffer(b)
we := value.(dstore.WatchEvent... | @@ -205,6 +205,26 @@ func Encode(value interface{}, isSimple bool) []byte {
return []byte(fmt.Sprintf("*%d\r\n%s", len(v), buf.Bytes()))
case map[string]bool:
return RespNIL
+ case []DiceCmdMeta: | internal/clientio/resp.go | 26 | Go | 0.786 | suggestion | 281 | 51 | 31 | false | Added support for COMMAND command | 458 | DiceDB/dice | 10,326 | C | lucifercr07 | aashraybhandar1 |
DiceCmds["RENAME"] = renameCmdMeta
DiceCmds["GETEX"] = getexCmdMeta
DiceCmds["PTTL"] = pttlCmdMeta
DiceCmds["HSET"] = hsetCmdMeta
DiceCmds["OBJECT"] = objectCmdMeta
DiceCmds["TOUCH"] = touchCmdMeta
DiceCmds["LPUSH"] = lpushCmdMeta
DiceCmds["RPOP"] = rpopCmdMeta
DiceCmds["RPUSH"] = rpushCmdMeta
DiceCmds["LPOP"... | Shall we keep parity with redis output? For `COMMAND` e.g. our output for `HELLO`
```
0.0.0.0:7379> command
1) 1) "HELLO"
2) (integer) -1
3) 1) "BeginIndex"
2) (integer) 0
3) "LastKey"
4) (integer) 0
5) "Step"
6) (integer) 0
```
Redis output:
```
205) 1) "hello"... | DiceCmds["RENAME"] = renameCmdMeta
DiceCmds["GETEX"] = getexCmdMeta
DiceCmds["PTTL"] = pttlCmdMeta
DiceCmds["HSET"] = hsetCmdMeta
DiceCmds["OBJECT"] = objectCmdMeta
DiceCmds["TOUCH"] = touchCmdMeta
DiceCmds["LPUSH"] = lpushCmdMeta
DiceCmds["RPOP"] = rpopCmdMeta
DiceCmds["RPUSH"] = rpushCmdMeta
DiceCmds["LPOP"... | @@ -686,3 +686,26 @@ func init() {
DiceCmds["PFADD"] = pfAddCmdMeta
DiceCmds["PFCOUNT"] = pfCountCmdMeta
}
+
+func convertKeySpecsToSlice(keySpecs KeySpecs) []interface{} { | internal/eval/commands.go | 26 | Go | 1 | security | 1,256 | 48 | 39 | false | Added support for COMMAND command | 458 | DiceDB/dice | 10,326 | C | lucifercr07 | aashraybhandar1 |
package tests
import (
"fmt"
"net"
"testing"
"gotest.tools/v3/assert"
)
func TestCommandDefault(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
t.Run("Command should not be empty", func(t *testing.T) {
commands := getCommandDefault(conn)
assert.Assert(t, len(commands) > 0,
fmt.Sprintf(... | Shall we add more test cases here?
Like assert number of command matches the number defined in `DiceCmds = map[string]DiceCmdMeta{}`
Also few negative scenarios as part of unit tests. | package tests
import (
"fmt"
"net"
"testing"
eval "github.com/dicedb/dice/internal/eval"
"gotest.tools/v3/assert"
)
func TestCommandDefault(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
commands := getCommandDefault(conn)
t.Run("Command should not be empty", func(t *testing.T) {
assert.... | @@ -0,0 +1,45 @@
+package tests
+
+import (
+ "fmt"
+ "net"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestCommandDefault(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ t.Run("Command should not be empty", func(t *testing.T) { | tests/command_default_test.go | 17 | Go | 0.5 | nitpick | 185 | 42 | 42 | false | Added support for COMMAND command | 458 | DiceDB/dice | 10,326 | C | lucifercr07 | aashraybhandar1 |
// WatchSubscription represents a subscription to watch a query.
WatchSubscription struct {
Subscribe bool // true for subscribe, false for unsubscribe
Query DSQLQuery // query to watch
ClientFD int // client file descriptor
CacheChan chan *[]dstore.Ke... | The fingerprinting mechanism is probably internal to the query watcher, we can make it private.
Also maybe a better name for this is `fingerprintToQueryMap` | Query DSQLQuery // query to watch
ClientFD int // client file descriptor
CacheChan chan *[]dstore.KeyValue // channel to receive cache data for this query
}
// AdhocQueryResult represents the result of an adhoc query.
AdhocQueryResult struct {
Result *[]dstore.DSQ... | @@ -37,11 +40,12 @@ type (
ResponseChan chan AdhocQueryResult
}
- // QueryWatcher watches for changes in keys and notifies clients.
- QueryWatcher struct {
- WatchList sync.Map // WatchList is a map of queries to their respective clients, type: map[DSQLQuery]*sync.Map[int]struct{}
- Qu... | internal/querywatcher/query_watcher.go | 26 | Go | 0.571 | suggestion | 157 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
// AdhocQuery represents an adhoc query request.
AdhocQuery struct {
Query DSQLQuery
ResponseChan chan AdhocQueryResult
}
// QWatchManager watches for changes in keys and notifies clients.
QWatchManager struct {
WatchList sync.Map // WatchList is a map of fingerp... | I think a better name might be QueryManager. This component could be used to serve ad-hoc queries in the future (query execution without subscriptions) so tying the name to a particular command may not be a good idea. | Query DSQLQuery
ResponseChan chan AdhocQueryResult
}
// QueryManager watches for changes in keys and notifies clients.
QueryManager struct {
WatchList sync.Map // WatchList is a map of query string to their respective clients, type: map[string]*sync.Map[int]struct{}
QueryCach... | @@ -53,23 +57,23 @@ var (
AdhocQueryChan chan AdhocQuery
)
-// NewQueryWatcher initializes a new QueryWatcher.
-func NewQueryWatcher() *QueryWatcher {
+// NewQWatchManager initializes a new QWatchManager.
+func NewQWatchManager() *QWatchManager { | internal/querywatcher/query_watcher.go | 26 | Go | 0.5 | suggestion | 217 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
} else {
w.removeWatcher(&event.Query, event.ClientFD)
}
case <-ctx.Done():
return
}
}
}
// watchKeys watches for changes in keys and notifies clients.
func (w *QWatchManager) watchKeys(ctx context.Context, watchChan <-chan dstore.WatchEvent) {
for {
select {
case event := <-watchChan:
w.proc... | nit: shouldn't we use `//` style comments here? I am not familiar with what the recommend styling guide is for comments in golang, so I'm happy to be corrected here. | }
}
}
// watchKeys watches for changes in keys and notifies clients.
func (w *QueryManager) watchKeys(ctx context.Context, watchChan <-chan dstore.WatchEvent) {
for {
select {
case event := <-watchChan:
w.processWatchEvent(event)
case <-ctx.Done():
return
}
}
}
// processWatchEvent processes a sing... | @@ -121,35 +125,55 @@ func (w *QueryWatcher) watchKeys(ctx context.Context, watchChan <-chan dstore.Wa
}
// processWatchEvent processes a single watch event.
-func (w *QueryWatcher) processWatchEvent(event dstore.WatchEvent) {
- w.WatchList.Range(func(key, value interface{}) bool {
- query := key.(DSQLQuery)
- cl... | internal/querywatcher/query_watcher.go | 26 | Go | 0.571 | suggestion | 165 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
log.Warnf("Fingerprint not found in cacheStore: %s", fingerPrint)
return true
}
clients := value.(*sync.Map)
/*
For all the clients that are watching this fingerprint, we need to find the queries they had requested to run, and then send them responses based on the queries they had fired.
*/
clients.... | I'm a little confused about this looping mechanism here.
Shouldn't it be structured as follows:
```golang
w.WatchList.Range(
// Looping over all queries.
query := key.(DSQLQuery)
clients := value.(*sync.Map)
if !regex.WildCardMatch() {
// continue if no match
}
// 1. If... | return true
}
w.updateQueryCache(query.Fingerprint, event)
queryResult, err := w.runQuery(&query)
if err != nil {
log.Error(err)
return true
}
w.notifyClients(&query, clients, queryResult)
return true
})
}
// updateQueryCache updates the query cache based on the watch event.
func (w *QueryMa... | @@ -121,35 +125,55 @@ func (w *QueryWatcher) watchKeys(ctx context.Context, watchChan <-chan dstore.Wa
}
// processWatchEvent processes a single watch event.
-func (w *QueryWatcher) processWatchEvent(event dstore.WatchEvent) {
- w.WatchList.Range(func(key, value interface{}) bool {
- query := key.(DSQLQuery)
- cl... | internal/querywatcher/query_watcher.go | 26 | Go | 0.857 | performance | 893 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
_, err := syscall.Write(clientFD, encodedResult)
if err != nil {
w.removeWatcher(query, clientFD)
}
}
// serveAdhocQueries listens for adhoc queries, executes them, and sends the result back to the client.
func (w *QWatchManager) serveAdhocQueries(ctx context.Context) {
for {
select {
case query := <-AdhocQu... | I don't think sha256 is a good choice here since we don't care about cryptographic security. We want something fast, maybe something like FarmHash? | result, err := w.runQuery(&query.Query)
query.ResponseChan <- AdhocQueryResult{
Result: result,
Fingerprint: query.Query.Fingerprint,
Err: err,
}
case <-ctx.Done():
return
}
}
}
// addWatcher adds a client as a watcher to a query.
func (w *QueryManager) addWatcher(query *DSQLQ... | @@ -163,35 +187,56 @@ func (w *QueryWatcher) updateQueryCache(query *DSQLQuery, event dstore.WatchEven
}
}
-// notifyClients notifies all clients watching a query about the new result.
-func (w *QueryWatcher) notifyClients(query *DSQLQuery, clients *sync.Map, queryResult *[]dstore.DSQLQueryResultRow) {
+// notifyC... | internal/querywatcher/query_watcher.go | 26 | Go | 0.5 | security | 147 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
func (w *QWatchManager) serveAdhocQueries(ctx context.Context) {
for {
select {
case query := <-AdhocQueryChan:
result, err := w.runQuery(&query.Query)
query.ResponseChan <- AdhocQueryResult{
Result: result,
Fingerprint: generateQueryFingerprint(&query.Query),
Err: err,
}
case <... | Can queryFingerprint be part of the DSQLQuery instance so we do not have to re-calculate it every time the query is executed? | return
}
}
}
// addWatcher adds a client as a watcher to a query.
func (w *QueryManager) addWatcher(query *DSQLQuery, clientFD int, cacheChan chan *[]dstore.KeyValue) {
queryString := query.String()
clients, _ := w.WatchList.LoadOrStore(queryString, &sync.Map{})
clients.(*sync.Map).Store(clientFD, struct{}{}... | @@ -163,35 +187,56 @@ func (w *QueryWatcher) updateQueryCache(query *DSQLQuery, event dstore.WatchEven
}
}
-// notifyClients notifies all clients watching a query about the new result.
-func (w *QueryWatcher) notifyClients(query *DSQLQuery, clients *sync.Map, queryResult *[]dstore.DSQLQueryResultRow) {
+// notifyC... | internal/querywatcher/query_watcher.go | 26 | Go | 0.357 | question | 126 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | soumya-codes | pratikpandey21 |
}
}
// processWatchEvent processes a single watch event.
func (w *QWatchManager) processWatchEvent(event dstore.WatchEvent) {
/*
Iterate over the watchlist to go through all fingerprints and the corresponding client connections to those fingerprints
*/
w.WatchList.Range(func(fingerPrint, value interface{}) bool ... | nit: Should have a `nil` check? | // Iterate over the watchlist to go through the query string
// and the corresponding client connections to that query string
w.WatchList.Range(func(key, value interface{}) bool {
queryString := key.(string)
clients := value.(*sync.Map)
query, err := ParseQuery(queryString)
if err != nil {
log.Error(fmt.... | @@ -121,35 +125,55 @@ func (w *QueryWatcher) watchKeys(ctx context.Context, watchChan <-chan dstore.Wa
}
// processWatchEvent processes a single watch event.
-func (w *QueryWatcher) processWatchEvent(event dstore.WatchEvent) {
- w.WatchList.Range(func(key, value interface{}) bool {
- query := key.(DSQLQuery)
- cl... | internal/querywatcher/query_watcher.go | 26 | Go | 0.286 | question | 31 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | lucifercr07 | pratikpandey21 |
w.QueryCacheMu.Lock()
w.QueryCache.Delete(queryFingerprint)
w.FingerPrintCache.Delete(queryFingerprint)
w.QueryCacheMu.Unlock()
log.Info(fmt.Sprintf("no longer watching query: %s", query))
}
}
}
// clientCount returns the number of clients watching a query.
func (w *QWatchManager) clientCount(client... | We're calling `generateQueryFingerprint` for `addWatcher`, `removeWatcher` and `runquery` in which `runQuery` might be the case where the calls are very frequent.
May be in another PR we can think of a way to cache these fingerprints with `query.toString()` depending on it's impact. Would that be required? | package querywatcher
import (
"context"
"fmt"
"sync"
"syscall"
"github.com/charmbracelet/log"
"github.com/cockroachdb/swiss"
"github.com/dicedb/dice/internal/clientio"
"github.com/dicedb/dice/internal/regex"
dstore "github.com/dicedb/dice/internal/store"
)
type (
cacheStore *swiss.Map[string, *dstore.Obj]
... | @@ -240,15 +289,23 @@ func (w *QueryWatcher) clientCount(clients *sync.Map) int {
}
// runQuery executes a query on its respective cache.
-func (w *QueryWatcher) runQuery(query *DSQLQuery) (*[]dstore.DSQLQueryResultRow, error) {
+func (w *QWatchManager) runQuery(query *DSQLQuery) (*[]dstore.DSQLQueryResultRow, erro... | internal/querywatcher/query_watcher.go | 26 | Go | 0.643 | performance | 308 | 42 | 272 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | lucifercr07 | pratikpandey21 |
return err
}
// eventLoop listens for events and handles client requests. It also runs a cron job to delete expired keys
func (s *AsyncServer) eventLoop(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
events, err := s.multiplexer.Poll(s.multiplexerPollTimeout)
... | @pratikpandey21 Is there any reason to remove this? Not relevant now? | // eventLoop listens for events and handles client requests. It also runs a cron job to delete expired keys
func (s *AsyncServer) eventLoop(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
events, err := s.multiplexer.Poll(s.multiplexerPollTimeout)
if err != nil {... | @@ -228,12 +232,8 @@ func (s *AsyncServer) eventLoop(ctx context.Context) error {
if errors.Is(err, ErrAborted) {
log.Info("Received abort command, initiating graceful shutdown")
return err
- } else if errors.Is(err, syscall.ECONNRESET) || errors.Is(err, net.ErrClosed) { | internal/server/server.go | 26 | Go | 0.286 | refactor | 70 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | AshwinKul28 | pratikpandey21 |
}
}
}
// watchKeys watches for changes in keys and notifies clients.
func (w *QueryManager) watchKeys(ctx context.Context, watchChan <-chan dstore.WatchEvent) {
for {
select {
case event := <-watchChan:
w.processWatchEvent(event)
case <-ctx.Done():
return
}
}
}
// processWatchEvent processes a sing... | Aesthetics/linter change: Go error strings should not be capitalized! | }
}
// watchKeys watches for changes in keys and notifies clients.
func (w *QueryManager) watchKeys(ctx context.Context, watchChan <-chan dstore.WatchEvent) {
for {
select {
case event := <-watchChan:
w.processWatchEvent(event)
case <-ctx.Done():
return
}
}
}
// processWatchEvent processes a single w... | @@ -121,16 +121,26 @@ func (w *QueryWatcher) watchKeys(ctx context.Context, watchChan <-chan dstore.Wa
}
// processWatchEvent processes a single watch event.
-func (w *QueryWatcher) processWatchEvent(event dstore.WatchEvent) {
+func (w *QueryManager) processWatchEvent(event dstore.WatchEvent) {
+ // Iterate over th... | internal/querywatcher/query_watcher.go | 26 | Go | 0.429 | style | 69 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | AshwinKul28 | pratikpandey21 |
} else {
w.removeWatcher(&event.Query, event.ClientFD)
}
case <-ctx.Done():
return
}
}
}
// watchKeys watches for changes in keys and notifies clients.
func (w *QueryManager) watchKeys(ctx context.Context, watchChan <-chan dstore.WatchEvent) {
for {
select {
case event := <-watchChan:
w.proce... | For my understanding, why are we changing the key of the WatchList to a string? Isn't it possible to keep it as a `DSQLQuery` object? That would save us a ParseQuery call on every execution. | w.removeWatcher(&event.Query, event.ClientFD)
}
case <-ctx.Done():
return
}
}
}
// watchKeys watches for changes in keys and notifies clients.
func (w *QueryManager) watchKeys(ctx context.Context, watchChan <-chan dstore.WatchEvent) {
for {
select {
case event := <-watchChan:
w.processWatchEvent... | @@ -121,16 +121,26 @@ func (w *QueryWatcher) watchKeys(ctx context.Context, watchChan <-chan dstore.Wa
}
// processWatchEvent processes a single watch event.
-func (w *QueryWatcher) processWatchEvent(event dstore.WatchEvent) {
+func (w *QueryManager) processWatchEvent(event dstore.WatchEvent) {
+ // Iterate over th... | internal/querywatcher/query_watcher.go | 26 | Go | 0.5 | suggestion | 190 | 51 | 51 | false | #469: Add support for common cache per fingerprint in QWATCH | 473 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
}
}
// notifyClient notifies all clients watching a query about the new result.
func (w *QueryManager) notifyClients(query *DSQLQuery, clients *sync.Map, queryResult *[]dstore.DSQLQueryResultRow) {
encodedResult := clientio.Encode(CreatePushResponse(query, queryResult), false)
// Send the result to the client
clie... | Do we need max 20 retries? We can reduce the number. Also can we add random jitter to it? Just a thought so that all the clients won't collide.
Thanks for the change. | default:
log.Warnf("Unknown operation: %s", event.Operation)
}
}
func (w *QueryManager) notifyClients(query *DSQLQuery, clients *sync.Map, queryResult *[]dstore.DSQLQueryResultRow) {
encodedResult := clientio.Encode(CreatePushResponse(query, queryResult), false)
clients.Range(func(clientKey, _ interface{}) bool... | @@ -172,20 +174,50 @@ func (w *QueryManager) updateQueryCache(queryFingerprint string, event dstore.Wa
}
}
-// notifyClient notifies all clients watching a query about the new result.
func (w *QueryManager) notifyClients(query *DSQLQuery, clients *sync.Map, queryResult *[]dstore.DSQLQueryResultRow) {
encodedRes... | internal/querywatcher/query_watcher.go | 26 | Go | 0.429 | question | 171 | 51 | 51 | false | Adds retry with exponential backoff for QWATCH writes | 514 | DiceDB/dice | 10,326 | C | AshwinKul28 | JyotinderSingh |
if obj != nil {
currKeyHll := obj.Value.(*hyperloglog.Sketch)
err := unionHll.Merge(currKeyHll)
if err != nil {
return diceerrors.NewErrWithMessage(diceerrors.InvalidHllErr)
}
}
}
return clientio.Encode(unionHll.Estimate(), false)
}
func evalPFMERGE(args []string, store *dstore.Store) []byte {
... | There should be a check here to ensure that the retrieved object has the correct encoding. |
// sort the sets by the number of elements in the set
// we will iterate over the smallest set
// and check if the element is present in all the other sets
sort.Slice(sets, func(i, j int) bool {
return len(sets[i]) < len(sets[j])
})
count := 0
resultSet := make(map[string]struct{}, len(sets[0]))
// init th... | @@ -2533,3 +2533,37 @@ func evalPFCOUNT(args []string, store *dstore.Store) []byte {
return clientio.Encode(unionHll.Estimate(), false)
}
+
+func evalPFMERGE(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("PFMERGE")
+ }
+
+ var mergedHll *hyperloglog.Sketch
+ des... | internal/eval/eval.go | 26 | Go | 0.286 | suggestion | 90 | 46 | 51 | false | #241: Implementation PFMERGE command | 518 | DiceDB/dice | 10,326 | C | JyotinderSingh | lucifercr07 |
return diceerrors.NewErrWithFormattedMessage("unknown command '%s', with args beginning with: %s", op.Cmd.Cmd, strings.Join(op.Cmd.Args, " "))
}
// The following commands could be handled at the server level, however, we can randomly let any shard handle them
// to reduce load on main server.
switch diceCmd.Name... | Thanks for tackling this issue as a part of this PR. It would be better if we make this configurable using a config variable instead of adding a static condition in this manner.
Additionally, when you set that config for the test server inside the setup method, please add an explanation as to why we're doing it. | if !ok {
return diceerrors.NewErrWithFormattedMessage("unknown command '%s', with args beginning with: %s", op.Cmd.Cmd, strings.Join(op.Cmd.Args, " "))
}
// The following commands could be handled at the server level, however, we can randomly let any shard handle them
// to reduce load on main server.
switch di... | @@ -127,5 +128,10 @@ func (shard *ShardThread) executeCommand(op *ops.StoreOp) []byte {
// cleanup handles cleanup logic when the shard stops.
func (shard *ShardThread) cleanup() {
close(shard.ReqChan)
+ if testing.Testing() {
+ // Avoiding AOF dump in case of testing env
+ return
+ } | internal/shard/shard_thread.go | 26 | Go | 0.5 | suggestion | 316 | 30 | 34 | false | #241: Implementation PFMERGE command | 518 | DiceDB/dice | 10,326 | C | JyotinderSingh | lucifercr07 |
}
func evalPFMERGE(args []string, store *dstore.Store) []byte {
if len(args) < 1 {
return diceerrors.NewErrArity("PFMERGE")
}
var mergedHll *hyperloglog.Sketch
destKey := args[0]
obj := store.Get(destKey)
// If destKey doesn't exist, create a new HLL, else fetch the existing
if obj == nil {
mergedHll = hy... | We should be doing a type assertion here as well | }
return clientio.Encode(0, false)
}
func evalPFCOUNT(args []string, store *dstore.Store) []byte {
if len(args) < 1 {
return diceerrors.NewErrArity("PFCOUNT")
}
var unionHll = hyperloglog.New()
for _, arg := range args {
obj := store.Get(arg)
if obj != nil {
currKeyHll, ok := obj.Value.(*hyperloglog.... | @@ -2603,3 +2603,41 @@ func evalPFCOUNT(args []string, store *dstore.Store) []byte {
return clientio.Encode(unionHll.Estimate(), false)
}
+
+func evalPFMERGE(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("PFMERGE")
+ }
+
+ var mergedHll *hyperloglog.Sketch
+ des... | internal/eval/eval.go | 26 | Go | 0.286 | suggestion | 48 | 40 | 51 | false | #241: Implementation PFMERGE command | 518 | DiceDB/dice | 10,326 | C | JyotinderSingh | lucifercr07 |
// Will evict EvictionRatio of keys whenever eviction runs
var (
EvictionRatio float64 = 0.40
EvictionStrategy string = "allkeys-lru"
AOFFile string = "./dice-master.aof"
)
// Network
var (
IOBufferLength int = 512
IOBufferLengthMAX int = 50 * 1024
)
var (
ShardCronFrequency = 1 * tim... | Let's call this `writeAOFOnCleanup` | // Will evict EvictionRatio of keys whenever eviction runs
var (
EvictionRatio float64 = 0.40
EvictionStrategy string = "allkeys-lru"
AOFFile string = "./dice-master.aof"
)
// Network
var (
IOBufferLength int = 512
IOBufferLengthMAX int = 50 * 1024
)
var (
ShardCronFrequency = 1 * tim... | @@ -37,3 +37,5 @@ var (
// if RequirePass is set to an empty string, no authentication is required
RequirePass string = utils.EmptyStr
)
+
+var TestEnvEnabled = false | config/config.go | 26 | Go | 0.214 | suggestion | 35 | 27 | 27 | false | Adding TestEnvEnabled config and avoiding AOF dump for test env | 523 | DiceDB/dice | 10,326 | C | JyotinderSingh | lucifercr07 |
return clientio.RespNIL
}
// If the object exists, check if it is a set object.
if err := dstore.AssertType(obj.TypeEncoding, dstore.ObjTypeSet); err == nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
// return the RESP encoded value
return clientio.Encode(obj.Value, false)
}
... | nit: Consider aligning the comment with the code for better readability. | obj := store.GetDel(key)
// if key does not exist, return RESP encoded nil
if obj == nil {
return clientio.RespNIL
}
// If the object exists, check if it is a set object.
if err := object.AssertType(obj.TypeEncoding, object.ObjTypeSet); err == nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.Wr... | @@ -323,6 +323,30 @@ func evalGETDEL(args []string, store *dstore.Store) []byte {
return clientio.Encode(obj.Value, false)
}
+// evaLJSONFORGET removes the field specified by the given JSONPath from the JSON document stored under the provided key.
+// calls the evalJSONDEL() with the arguments passed
+// Returns ... | internal/eval/eval.go | 26 | Go | 0.286 | suggestion | 72 | 51 | 51 | false | #494: Implementation `JSON.FORGET` command | 524 | DiceDB/dice | 10,326 | C | kushal0511-not | Nijin-P-S |
// if key does not exist, return RESP encoded nil
if obj == nil {
return clientio.RespNIL
}
// If the object exists, check if it is a set object.
if err := object.AssertType(obj.TypeEncoding, object.ObjTypeSet); err == nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
// return ... | Can we just change L341 to L349 to return `evalJSONDEL(args, store)`? | // if key does not exist, return RESP encoded nil
if obj == nil {
return clientio.RespNIL
}
// If the object exists, check if it is a set object.
if err := object.AssertType(obj.TypeEncoding, object.ObjTypeSet); err == nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
// return ... | @@ -327,6 +327,30 @@ func evalGETDEL(args []string, store *dstore.Store) []byte {
return clientio.Encode(obj.Value, false)
}
+// evaLJSONFORGET removes the field specified by the given JSONPath from the JSON document stored under the provided key.
+// calls the evalJSONDEL() with the arguments passed
+// Returns ... | internal/eval/eval.go | 26 | Go | 0.429 | question | 69 | 51 | 51 | false | #494: Implementation `JSON.FORGET` command | 524 | DiceDB/dice | 10,326 | C | lucifercr07 | Nijin-P-S |
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/charmbracelet/log"
"github.com/dicedb/dice/config"
"github.com/dicedb/dice/internal/clientio"
"github.com/dicedb/dice/internal/ops"
"github.com/dicedb/dice/internal/querywatcher"
"github.com/dicedb/dice/internal/server/utils"
"github.com/dicedb/dic... | Is this comment outdated? Aren't we already creating and sharing a common shard manager across both servers? | "encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/charmbracelet/log"
"github.com/dicedb/dice/config"
"github.com/dicedb/dice/internal/clientio"
"github.com/dicedb/dice/internal/ops"
"github.com/dicedb/dice/internal/querywatcher"
"github.com/dicedb/dice/internal/server/utils"
"github.com/dicedb/dic... | @@ -0,0 +1,127 @@
+package server
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/charmbracelet/log"
+ "github.com/dicedb/dice/config"
+ "github.com/dicedb/dice/internal/clientio"
+ "github.com/dicedb/dice/internal/ops"
+ "github.com/dicedb/dice/internal/queryw... | internal/server/httpServer.go | 26 | Go | 0.357 | question | 108 | 51 | 51 | false | Add Support for HTTP | 527 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
serverErrCh := make(chan error, 2)
var serverWg sync.WaitGroup
serverWg.Add(1)
go func() {
defer serverWg.Done()
// Run the server
err := asyncServer.Run(ctx)
// Handling different server errors
if err != nil {
if errors.Is(err, context.Canceled) {
log.Info("Server was canceled")
} else if err... | Should we create a cancellable context from the ctx for the `httpServer` and `asyncServer` to maintain consistency with the shard manager? Or change the shard manager to use the common ctx.
(Actually I would like to know what the preferred practice is) | serverWg.Add(1)
go func() {
defer serverWg.Done()
// Run the server
err := asyncServer.Run(ctx)
// Handling different server errors
if err != nil {
if errors.Is(err, context.Canceled) {
log.Debug("Server was canceled")
} else if errors.Is(err, server.ErrAborted) {
log.Debug("Server received a... | @@ -51,23 +62,73 @@ func main() {
cancel()
}()
- // Run the server
- err := asyncServer.Run(ctx)
+ shardManagerCtx, cancelShardManager := context.WithCancel(ctx)
+ defer cancelShardManager()
+
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ shardManager.Run(shardManagerCtx)
+ }()
+
+ serverErrCh := make(chan err... | main.go | 26 | Go | 0.643 | question | 255 | 51 | 51 | false | Add Support for HTTP | 527 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
prefix := strings.TrimPrefix(r.URL.Path, "/")
if prefix == "" {
return nil, errors.New("invalid command")
}
prefix = strings.ToUpper(prefix)
var args []string
// Step 1: Handle JSON body if present
if r.Body != nil {
body, err := io.ReadAll(r... | Let's use a fixed size array here instead of a slice. Also we should prefer using constants here (in case they get reused elsewhere) |
const (
Key = "key"
Field = "field"
Path = "path"
Value = "value"
)
func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
command := strings.TrimPrefix(r.URL.Path, "/")
if command == "" {
return nil, errors.New("invalid command")
}
command = strings.ToUpper(command)
var args []string
// Ste... | @@ -0,0 +1,72 @@
+package utils
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/dicedb/dice/internal/cmd"
+)
+
+func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
+ prefix := strings.TrimPrefix(r.URL.Path, "/")
+ if prefix == "" {
+ return nil, errors.New("... | internal/server/utils/redisCmdAdapter.go | 26 | Go | 0.429 | suggestion | 132 | 51 | 51 | false | Add Support for HTTP | 527 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
package utils
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/dicedb/dice/internal/cmd"
)
func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
prefix := strings.TrimPrefix(r.URL.Path, "/")
if prefix == "" {
return nil, errors.New("invalid command")
}
prefix = st... | nit: just for better clarity.
```suggestion
command := strings.TrimPrefix(r.URL.Path, "/")
``` | package utils
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/dicedb/dice/internal/cmd"
)
const (
Key = "key"
Field = "field"
Path = "path"
Value = "value"
)
func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
command := strings.TrimPrefix(r.URL.Path, "/")
i... | @@ -0,0 +1,72 @@
+package utils
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/dicedb/dice/internal/cmd"
+)
+
+func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
+ prefix := strings.TrimPrefix(r.URL.Path, "/") | internal/server/utils/redisCmdAdapter.go | 15 | Go | 0.643 | suggestion | 98 | 40 | 40 | false | Add Support for HTTP | 527 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
package utils
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/dicedb/dice/internal/cmd"
)
func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
prefix := strings.TrimPrefix(r.URL.Path, "/")
if prefix == "" {
return nil, errors.New("invalid command")
}
prefix = st... | Maybe this can be made clearer in this fashion:
```suggestion
// Process remaining keys in the JSON body
for key, val := range jsonBody {
switch v := val.(type) {
case string:
// Handle unary operations like 'nx' where value is "true"
... | delete(jsonBody, key)
}
}
// Process remaining keys in the JSON body
for key, val := range jsonBody {
switch v := val.(type) {
case string:
// Handle unary operations like 'nx' where value is "true"
if v == "true" {
args = append(args, key)
} else {
args = append(ar... | @@ -0,0 +1,72 @@
+package utils
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/dicedb/dice/internal/cmd"
+)
+
+func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
+ prefix := strings.TrimPrefix(r.URL.Path, "/")
+ if prefix == "" {
+ return nil, errors.New("... | internal/server/utils/redisCmdAdapter.go | 26 | Go | 0.929 | suggestion | 1,033 | 73 | 36 | false | Add Support for HTTP | 527 | DiceDB/dice | 10,326 | C | JyotinderSingh | pratikpandey21 |
time.Sleep(2 * time.Second)
// restart server
runTestServer(ctx, &wg)
// wait for the server to start up
time.Sleep(2 * time.Second)
// Check if the server is running
conn, err = net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", config.Port))
if err != nil {
t.Fatalf("Server should be running after restart: %v",... | We can export the runTestServer and fireCommand methods from the package in which they are defined to avoid code duplication. |
wg.Wait()
// restart server
ctx2, cancel2 := context.WithCancel(context.Background())
t.Cleanup(cancel2)
// start test server.
// use different waitgroups and contexts to avoid race conditions.;
var wg2 sync.WaitGroup
tests.RunTestServer(ctx2, &wg2, testServerOptions)
// wait for the server to start up
ti... | @@ -0,0 +1,190 @@
+package server_test
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/charmbracelet/log"
+ "github.com/dicedb/dice/config"
+ "github.com/dicedb/dice/internal/clientio"
+ "github.com/dicedb/dice/internal/server"
+ "github.com/dicedb/dice/testutils"... | internal/server/server_test.go | 26 | Go | 0.429 | suggestion | 125 | 51 | 31 | false | #437: feat: add test for abort command | 531 | DiceDB/dice | 10,326 | C | JyotinderSingh | tdadadavid |
package server_test
import (
"context"
"fmt"
"github.com/dicedb/dice/tests"
"net"
"sync"
"testing"
"time"
"github.com/dicedb/dice/config"
)
var options = tests.TestServerOptions{
Port: 8740,
}
func TestAbortCommand(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
t... | Let's call this testServerOptions instead. We should avoid overly generic names so that the namespace doesn't get polluted. | package server_test
import (
"context"
"fmt"
"github.com/dicedb/dice/tests"
"net"
"sync"
"testing"
"time"
"github.com/dicedb/dice/config"
)
var testServerOptions = tests.TestServerOptions{
Port: 8740,
}
func TestAbortCommand(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer ca... | @@ -0,0 +1,121 @@
+package server_test
+
+import (
+ "context"
+ "fmt"
+ "github.com/dicedb/dice/tests"
+ "net"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/dicedb/dice/config"
+)
+
+var options = tests.TestServerOptions{ | internal/server/server_test.go | 15 | Go | 0.429 | suggestion | 123 | 40 | 40 | false | #437: feat: add test for abort command | 531 | DiceDB/dice | 10,326 | C | JyotinderSingh | tdadadavid |
// If the approximated cardinality estimated by the HyperLogLog changed after executing the command,
// returns 1, otherwise 0 is returned.
func evalPFADD(args []string, store *dstore.Store) []byte {
if len(args) < 1 {
return diceerrors.NewErrArity("PFADD")
}
key := args[0]
obj := store.Get(key)
// If key does... | We shall change the error as below to maintain parity with Redis.
`WrongTypeHllErr = "-WRONGTYPE Key is not a valid HyperLogLog string value."`
```
if !ok {
return diceerrors.NewErrWithMessage(diceerrors.WrongTypeErr)
}
```
Output from Redis:
```
127.0.0.1:6379> pfadd hll a b c
(integer) 1
127.0.0.1... | // If the approximated cardinality estimated by the HyperLogLog changed after executing the command,
// returns 1, otherwise 0 is returned.
func evalPFADD(args []string, store *dstore.Store) []byte {
if len(args) < 1 {
return diceerrors.NewErrArity("PFADD")
}
key := args[0]
obj := store.Get(key)
// If key does... | @@ -2570,7 +2570,10 @@ func evalPFADD(args []string, store *dstore.Store) []byte {
return clientio.Encode(1, false)
}
- existingHll := obj.Value.(*hyperloglog.Sketch)
+ existingHll, ok := obj.Value.(*hyperloglog.Sketch)
+ if !ok {
+ return diceerrors.NewErrWithMessage("*WRONGTYPE*") | internal/eval/eval.go | 26 | Go | 1 | bug | 460 | 51 | 51 | false | Fixed hyperloglog type assertion check. | 541 | DiceDB/dice | 10,326 | C | lucifercr07 | AshwinKul28 |
obj := store.Get(key)
if obj == nil {
return diceerrors.NewErrWithMessage("could not perform this operation on a key that doesn't exist")
}
errWithMessage := dstore.AssertTypeAndEncoding(obj.TypeEncoding, dstore.ObjTypeJSON, dstore.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
jsonDa... | thanks for your add this command. I have a few comments.
if the len(results) == 0. in redis. it should return a empty array
`
127.0.0.1:6379> JSON.SET item:1 $ '{"name":"Noise-cancelling Bluetooth headphones","description":"Wireless Bluetooth headphones with noise-cancelling technology","connection":{"wireless... | return diceerrors.NewErrWithMessage("could not serialize result")
}
return clientio.Encode(string(resultBytes), false)
}
// evalJSONSET stores a JSON value at the specified key
// args must contain at least the key, path (unused in this implementation), and JSON string
// Returns encoded error response if incorrec... | @@ -675,6 +675,105 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// evalJSONARRAPPEND appends the value(s) provided in the args to the given array path
+// in the JSON object saved at key in arguments.
+// Args must contain atleast a key, path and value.
+// If the key ... | internal/eval/eval.go | 26 | Go | 0.786 | suggestion | 489 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | jujiale | srivastava-yash |
results := expr.Get(jsonData)
if(len(results) == 0){
return clientio.RespNIL
}
pathArrData, ok := results[0].([]interface{})
if(!ok) {
return clientio.RespNIL
}
for _, arg := range args[2:] {
var value interface{}
var conversionErr error
// Determine type of element ... | you could use utils.GetJSONFieldType to judge the element type | case NX, Nx:
if i != len(args)-1 {
return diceerrors.NewErrWithMessage(diceerrors.SyntaxErr)
}
obj := store.Get(key)
if obj != nil {
return clientio.RespNIL
}
case XX, Xx:
if i != len(args)-1 {
return diceerrors.NewErrWithMessage(diceerrors.SyntaxErr)
}
obj := store.Get(key)
i... | @@ -675,6 +675,105 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// evalJSONARRAPPEND appends the value(s) provided in the args to the given array path
+// in the JSON object saved at key in arguments.
+// Args must contain atleast a key, path and value.
+// If the key ... | internal/eval/eval.go | 26 | Go | 0.429 | suggestion | 62 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | jujiale | srivastava-yash |
// Determine type of element in the existing array (if any) to match type
if len(pathArrData) > 0 {
switch pathArrData[0].(type) {
case string:
value = arg
case float64:
value, conversionErr = strconv.ParseFloat(arg, 64)
case int64:
var intVal int64
intVal, conversionErr = strc... | in json. the elemet have concrete types. so if the type isn't recognized, we could return err | if obj == nil {
return clientio.RespNIL
}
default:
return diceerrors.NewErrWithMessage(diceerrors.SyntaxErr)
}
}
// Parse the JSON string
var jsonValue interface{}
if err := sonic.UnmarshalString(jsonStr, &jsonValue); err != nil {
return diceerrors.NewErrWithFormattedMessage("invalid JSON: %v",... | @@ -675,6 +675,105 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// evalJSONARRAPPEND appends the value(s) provided in the args to the given array path
+// in the JSON object saved at key in arguments.
+// Args must contain atleast a key, path and value.
+// If the key ... | internal/eval/eval.go | 26 | Go | 0.429 | suggestion | 93 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | jujiale | srivastava-yash |
if len(args) < 3 {
return diceerrors.NewErrArity("JSON.ARRAPPEND")
}
var key string = args[0]
var path string = args[1]
obj := store.Get(key)
if obj == nil {
return diceerrors.NewErrWithMessage("could not perform this operation on a key that doesn't exist")
}
errWithMe... | The error message should be something like `ERR Path '<path>' does not exist or not an array` | if len(results) == 1 {
resultBytes, err = sonic.Marshal(results[0])
} else {
resultBytes, err = sonic.Marshal(results)
}
if err != nil {
return diceerrors.NewErrWithMessage("could not serialize result")
}
return clientio.Encode(string(resultBytes), false)
}
// evalJSONSET stores a JSON value at the specifi... | @@ -675,6 +675,162 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// evalJSONARRAPPEND appends the value(s) provided in the args to the given array path
+// in the JSON object saved at key in arguments.
+// Args must contain atleast a key, path and value.
+// If the key ... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 93 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | JyotinderSingh | srivastava-yash |
// Determine type of element in the existing array (if any) to match type
if len(pathArrData) > 0 {
switch utils.GetJSONFieldType(pathArrData[0]) {
case utils.StringType:
value = arg
case utils.NumberType:
v... | Redis does not throw an error in case of incompatible types existing in a json array. | }
default:
return diceerrors.NewErrWithMessage(diceerrors.SyntaxErr)
}
}
// Parse the JSON string
var jsonValue interface{}
if err := sonic.UnmarshalString(jsonStr, &jsonValue); err != nil {
return diceerrors.NewErrWithFormattedMessage("invalid JSON: %v", err.Error())
}
// Retrieve existing object ... | @@ -675,6 +675,162 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// evalJSONARRAPPEND appends the value(s) provided in the args to the given array path
+// in the JSON object saved at key in arguments.
+// Args must contain atleast a key, path and value.
+// If the key ... | internal/eval/eval.go | 26 | Go | 0.357 | suggestion | 85 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | JyotinderSingh | srivastava-yash |
pathArrData = append(pathArrData, value)
}
obj.Value = pathArrData
resultsArray = append(resultsArray, int64(len(pathArrData)))
} else {
expr.MustModify(jsonData, func(data any) (interface{}, bool) {
pathArrData, ok := data.([]interface{})
if(!ok) ... | I feel this implementation can be simplified a lot. I tried coding it on my machine and I think you can also do something similar here. I tested it and it works fine for the most part. It also allows you to have arrays of mixed data types (while maintaining type information)
Note that this is just a rough implementa... | if err != nil {
return diceerrors.NewErrWithMessage("invalid JSONPath")
}
err = expr.Set(rootData, jsonValue)
if err != nil {
return diceerrors.NewErrWithMessage("failed to set value")
}
} else {
// If path is root, replace the entire JSON
rootData = jsonValue
}
// Create a new object with the ... | @@ -675,6 +675,162 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// evalJSONARRAPPEND appends the value(s) provided in the args to the given array path
+// in the JSON object saved at key in arguments.
+// Args must contain atleast a key, path and value.
+// If the key ... | internal/eval/eval.go | 26 | Go | 0.929 | bug | 2,396 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | JyotinderSingh | srivastava-yash |
},
"key exists but expired": {
setup: func() {
key := "EXISTING_EXPIRED_KEY"
value := "mock_value"
obj := &dstore.Obj{
Value: value,
LastAccessedAt: uint32(time.Now().Unix()),
}
store.Put(key, obj)
store.SetExpiry(obj, int64(-2*time.Millisecond))
},
input: []str... | Add a test case testing the case where the root level object is an array. The implementation which I have provided works for it.
```sh
0.0.0.0:7379> JSON.SET arr $ '[1,2,3,"blue"]'
OK
0.0.0.0:7379> JSON.ARRAPPEND arr $ '["black"]'
1) (integer) 5
0.0.0.0:7379> JSON.GET arr $
"[1,2,3,\"blue\",[\"black\"]]"
0.0.0.... | "insufficient args": {
setup: func() {},
input: []string{},
output: []byte("-ERR wrong number of arguments for 'json.set' command\r\n"),
},
"invalid json path": {
setup: func() {},
input: []string{"doc", "$", "{\"a\":}"},
output: nil,
validator: func(output []byte) {
assert.Assert(t, ... | @@ -698,6 +699,96 @@ func testEvalJSONSET(t *testing.T, store *dstore.Store) {
runEvalTests(t, tests, evalJSONSET, store)
}
+func testEvalJSONARRAPPEND(t *testing.T, store *dstore.Store) { | internal/eval/eval_test.go | 26 | Go | 0.786 | suggestion | 436 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | JyotinderSingh | srivastava-yash |
conversionErr = sonic.Unmarshal([]byte(arg), &jsonObject)
if conversionErr == nil {
value = jsonObject
}
default:
return diceerrors.NewErrWithMessage("failed to convert existing value in array to a va... | Do not use MustModify. It can result in a panic and crash the server. | rootData = make(map[string]interface{})
} else {
rootData = jsonValue
}
} else {
// If the key exists, check if it's a JSON object
err := object.AssertType(obj.TypeEncoding, object.ObjTypeJSON)
if err != nil {
return clientio.Encode(err, false)
}
err = object.AssertEncoding(obj.TypeEncoding, obj... | @@ -675,6 +675,162 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// evalJSONARRAPPEND appends the value(s) provided in the args to the given array path
+// in the JSON object saved at key in arguments.
+// Args must contain atleast a key, path and value.
+// If the key ... | internal/eval/eval.go | 26 | Go | 0.286 | bug | 69 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | JyotinderSingh | srivastava-yash |
// If the object at given path is not an array, it returns response.RespNIL.
// Returns the new length of the array at path.
func evalJSONARRAPPEND(args []string, store *dstore.Store) []byte {
if len(args) < 3 {
return diceerrors.NewErrArity("JSON.ARRAPPEND")
}
key := args[0]
path := args[1]
values := args[2:]
... | the `<path>` here should be replaced by the path sent by the user. | // If the object at given path is not an array, it returns response.RespNIL.
// Returns the new length of the array at path.
func evalJSONARRAPPEND(args []string, store *dstore.Store) []byte {
if len(args) < 3 {
return diceerrors.NewErrArity("JSON.ARRAPPEND")
}
key := args[0]
path := args[1]
values := args[2:]
... | @@ -783,6 +783,87 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// evalJSONARRAPPEND appends the value(s) provided in the args to the given array path
+// in the JSON object saved at key in arguments.
+// Args must contain atleast a key, path and value.
+// If the key d... | internal/eval/eval.go | 26 | Go | 0.429 | suggestion | 66 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | JyotinderSingh | srivastava-yash |
values := args[2:]
obj := store.Get(key)
if obj == nil {
return diceerrors.NewErrWithMessage("ERR key does not exist")
}
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
jsonData := obj.Value
... | ```suggestion
return diceerrors.NewErrWithMessage(err)
``` | values := args[2:]
obj := store.Get(key)
if obj == nil {
return diceerrors.NewErrWithMessage("ERR key does not exist")
}
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
jsonData := obj.Value
... | @@ -783,6 +783,87 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// evalJSONARRAPPEND appends the value(s) provided in the args to the given array path
+// in the JSON object saved at key in arguments.
+// Args must contain atleast a key, path and value.
+// If the key d... | internal/eval/eval.go | 26 | Go | 0.714 | suggestion | 63 | 51 | 51 | false | #485: JSON.ARRAPPEND Command | 543 | DiceDB/dice | 10,326 | C | JyotinderSingh | srivastava-yash |
}
runEvalTests(t, tests, evalEXPIREAT, store)
}
func testEvalJSONARRLEN(t *testing.T, store *dstore.Store) {
tests := map[string]evalTestCase{
"nil value": {
setup: func() {},
input: nil,
output: []byte("-ERR wrong number of arguments for 'json.arrlen' command\r\n"),
},
"key does not exist": {
... | nit: unnecessary new line, same for other occurrences below this. | input: []string{"NONEXISTENT_KEY"},
output: clientio.RespMinusTwo,
},
"key exists without expiry": {
setup: func() {
key := "EXISTING_KEY"
value := "mock_value"
obj := &object.Obj{
Value: value,
LastAccessedAt: uint32(time.Now().Unix()),
}
store.Put(key, obj)
},
... | @@ -382,6 +326,7 @@ func testEvalJSONARRLEN(t *testing.T, store *dstore.Store) {
_ = sonic.Unmarshal([]byte(value), &rootData)
obj := store.NewObj(rootData, -1, object.ObjTypeJSON, object.ObjEncodingJSON)
store.Put(key, obj)
+ | internal/eval/eval_test.go | 26 | Go | 0.214 | nitpick | 65 | 51 | 51 | false | #445: PFCOUNT benchmark and caching implementation analysis | 544 | DiceDB/dice | 10,326 | C | JyotinderSingh | Dev79844 |
output: clientio.Encode(int64(1), false),
},
}
runEvalTests(t, tests, evalHSET, store)
}
func BenchmarkEvalPFCOUNT(b *testing.B) {
store := *dstore.NewStore(nil)
// Helper function to create and insert HLL objects
createAndInsertHLL := func(key string, items []string) {
hll := hyperloglog.... | We don't need to benchmark for very small values | input: nil,
output: []byte(":0\r\n"),
},
"one key exists in db": {
setup: func() {
evalSET([]string{"key", "val"}, store)
},
input: nil,
output: []byte(":1\r\n"),
},
"two keys exist in db": {
setup: func() {
evalSET([]string{"key1", "val1"}, store)
evalSET([]string{"key2", "va... | @@ -1507,6 +1421,70 @@ func testEvalHSET(t *testing.T, store *dstore.Store) {
runEvalTests(t, tests, evalHSET, store)
}
+func BenchmarkEvalPFCOUNT(b *testing.B) {
+ store := *dstore.NewStore(nil)
+
+ // Helper function to create and insert HLL objects
+ createAndInsertHLL := func(key string, items []strin... | internal/eval/eval_test.go | 26 | Go | 0.071 | suggestion | 48 | 51 | 51 | false | #445: PFCOUNT benchmark and caching implementation analysis | 544 | DiceDB/dice | 10,326 | C | JyotinderSingh | Dev79844 |
for _, item := range items {
hll.Insert([]byte(item))
}
obj := &object.Obj{
Value: hll,
LastAccessedAt: uint32(time.Now().Unix()),
}
store.Put(key, obj)
}
// Create small HLLs (2 items each)
createAndInsertHLL("SMALL1", []... | It would be better to benchmark for 10^4, 10^6, 10^9 values. | evalSET([]string{"key2", "val2"}, store)
},
input: nil,
output: []byte(":2\r\n"),
},
}
runEvalTests(t, tests, evalDBSIZE, store)
}
func testEvalGETSET(t *testing.T, store *dstore.Store) {
tests := map[string]evalTestCase{
"GETSET with 1 arg": {
input: []string{"HELLO"},
output: []byte("-ER... | @@ -1507,6 +1421,70 @@ func testEvalHSET(t *testing.T, store *dstore.Store) {
runEvalTests(t, tests, evalHSET, store)
}
+func BenchmarkEvalPFCOUNT(b *testing.B) {
+ store := *dstore.NewStore(nil)
+
+ // Helper function to create and insert HLL objects
+ createAndInsertHLL := func(key string, items []strin... | internal/eval/eval_test.go | 26 | Go | 0.286 | suggestion | 60 | 51 | 51 | false | #445: PFCOUNT benchmark and caching implementation analysis | 544 | DiceDB/dice | 10,326 | C | JyotinderSingh | Dev79844 |
package eval
import (
"bytes"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/dicedb/dice/internal/object"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/charmbracelet/log"
"github.com/dicedb/dice/config"
... | thanks for your pr. I have a tiny comment. in redis. if the rootpath is not provided, the return msg should like below:
`
127.0.0.1:6379> JSON.SET doc $ '{"a":"foo", "nested": {"a": "hello"}, "nested2": {"a": 31}}'
OK
127.0.0.1:6379> JSON.STRLEN doc $
1) (nil)
127.0.0.1:6379> JSON.STRLEN doc... |
path := args[1]
obj := store.Get(key)
if obj == nil {
return clientio.RespNIL
}
// Check if the object is of JSON type
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
jsonData := obj.Value
... | @@ -2603,3 +2603,65 @@ func evalPFCOUNT(args []string, store *dstore.Store) []byte {
return clientio.Encode(unionHll.Estimate(), false)
}
+
+func evalJSONSTRLEN(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("JSON.STRLEN")
+ }
+
+ key := args[0]
+ path := default... | internal/eval/eval.go | 26 | Go | 0.786 | bug | 476 | 2,668 | 49 | false | #502 Added support for `JSON.STRLEN` | 545 | DiceDB/dice | 10,326 | C | jujiale | apoorvyadav1111 |
package eval
import (
"bytes"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/dicedb/dice/internal/object"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/charmbracelet/log"
"github.com/dicedb/dice/config"
... | a tiny question. in this logic. **if path == defaultRootPath** . should the jsonData not be a string? because we have made judge in **AssertTypeAndEncoding** |
path := args[1]
obj := store.Get(key)
if obj == nil {
return clientio.RespNIL
}
// Check if the object is of JSON type
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
jsonData := obj.Value
... | @@ -2672,3 +2672,75 @@ func evalPFMERGE(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+
+func evalJSONSTRLEN(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("JSON.STRLEN")
+ }
+
+ key := args[0]
+
+ if len(args) < 2 {
+ // no recursive
+ ... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 159 | 2,675 | 49 | false | #502 Added support for `JSON.STRLEN` | 545 | DiceDB/dice | 10,326 | C | jujiale | apoorvyadav1111 |
}
if err != nil {
return diceerrors.NewErrWithMessage("could not serialize result")
}
return clientio.Encode(string(resultBytes), false)
}
// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
// args must contain at least the key and path (where the boolean is located).
// If the key d... | In redis. if the key's is not exist. should return an error. like following:
`
127.0.0.1:6379> JSON.SET user $ '{"age":13,"high":1.60,"pet":null,"language":["python","golang"],"flag":false,"partner":{"name":"tom","language":["rust"]}}'
OK
127.0.0.1:6379> JSON.TOGGLE user111 $.aaa
(error)... | // Create a new object with the updated JSON data
newObj := store.NewObj(jsonData, -1, object.ObjTypeJSON, object.ObjEncodingJSON)
store.Put(key, newObj)
return clientio.Encode(len(results), false)
}
// evalJSONCLEAR Clear container values (arrays/objects) and set numeric values to 0,
// Already cleared values are... | @@ -646,6 +642,77 @@ func evalJSONGET(args []string, store *dstore.Store) []byte {
return clientio.Encode(string(resultBytes), false)
}
+// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
+// args must contain at least the key and path (where the boolean is located).
+// If the key doe... | internal/eval/eval.go | 26 | Go | 0.786 | suggestion | 392 | 51 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | jujiale | TheRanomial |
for _, result := range results {
switch v := result.(type) {
case bool:
newValue := !v
err := expr.Set(jsonData, newValue)
if err != nil {
return diceerrors.NewErrWithMessage("failed to set toggled value")
}
// Update the ... | if the value is not bool, should return array that contains nil, also, because results may including many elements, you should return an array. just as the following:
`
127.0.0.1:6379> JSON.SET user $ '{"age":13,"high":1.60,"flag":false,"pet":null,"language":["python","golang"],"flag":false,"partner":{"name":... | // If path is root and len(args) == 1, return it instantly
newObj := store.NewObj(struct{}{}, -1, object.ObjTypeJSON, object.ObjEncodingJSON)
store.Put(key, newObj)
countClear++
return clientio.Encode(countClear, false)
}
}
expr, err := jp.ParseString(path)
if err != nil {
return diceerrors.NewEr... | @@ -646,6 +642,77 @@ func evalJSONGET(args []string, store *dstore.Store) []byte {
return clientio.Encode(string(resultBytes), false)
}
+// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
+// args must contain at least the key and path (where the boolean is located).
+// If the key doe... | internal/eval/eval.go | 26 | Go | 0.786 | suggestion | 582 | 51 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | jujiale | TheRanomial |
return diceerrors.NewErrWithMessage("invalid JSONPath")
}
// Execute the JSONPath query
results := expr.Get(jsonData)
if len(results) == 0 {
return clientio.Encode([]interface{}{}, false) // Return empty array if no matches
}
toggleResults := make([]interface{}, len(results))
... | Hi, the changes look good. I have one question about a case where the previous object had an expired time set using expiry command. | }
expr, err := jp.ParseString(path)
if err != nil {
return diceerrors.NewErrWithMessage("invalid JSONPath")
}
_, err = expr.Modify(jsonData, func(element any) (altered any, changed bool) {
switch utils.GetJSONFieldType(element) {
case utils.IntegerType, utils.NumberType:
if element != utils.NumberZeroVa... | @@ -660,6 +656,79 @@ func evalJSONGET(args []string, store *dstore.Store) []byte {
return clientio.Encode(string(resultBytes), false)
}
+// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
+// args must contain at least the key and path (where the boolean is located).
+// If the key doe... | internal/eval/eval.go | 26 | Go | 0.429 | suggestion | 131 | 51 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | TheRanomial |
}
if err != nil {
return diceerrors.NewErrWithMessage("could not serialize result")
}
return clientio.Encode(string(resultBytes), false)
}
// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
// args must contain at least the key and path (where the boolean is located).
// If the key d... | in order to keep code style. please use diceerrors.NewErrWithMessage to return err | if len(args) < 1 {
return diceerrors.NewErrArity("JSON.CLEAR")
}
key := args[0]
// Default path is root if not specified
path := defaultRootPath
if len(args) > 1 {
path = args[1]
}
// Retrieve the object from the database
obj := store.Get(key)
if obj == nil {
return diceerrors.NewErrWithMessage("could... | @@ -660,6 +656,79 @@ func evalJSONGET(args []string, store *dstore.Store) []byte {
return clientio.Encode(string(resultBytes), false)
}
+// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
+// args must contain at least the key and path (where the boolean is located).
+// If the key doe... | internal/eval/eval.go | 26 | Go | 0.429 | style | 82 | 51 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | jujiale | TheRanomial |
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
jsonData := obj.Value
// Parse the JSONPath expression
expr, err := jp.ParseString(path)
if err != nil {
return di... | Hey, I am implementing JSON.ARRAPPEND where I also have to modify json for multiple results like this. I had also done this similarly using expr.Set() in the loop, it works fine when there is only 1 value in results array but for example in your case lets say the json is `{"isSimple":true,"nested":{"isSimple":false}}` ... | var countClear uint64 = 0
if len(args) == 1 || path == defaultRootPath {
if jsonData != struct{}{} {
// If path is root and len(args) == 1, return it instantly
newObj := store.NewObj(struct{}{}, -1, object.ObjTypeJSON, object.ObjEncodingJSON)
store.Put(key, newObj)
countClear++
return clientio.Encode... | @@ -661,6 +657,79 @@ func evalJSONGET(args []string, store *dstore.Store) []byte {
return clientio.Encode(string(resultBytes), false)
}
+// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
+// args must contain at least the key and path (where the boolean is located).
+// If the key doe... | internal/eval/eval.go | 26 | Go | 0.643 | suggestion | 630 | 51 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | srivastava-yash | TheRanomial |
package commands
import (
"testing"
"github.com/dicedb/dice/testutils"
"gotest.tools/v3/assert"
)
func TestEvalJSONTOGGLE(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
simpleJSON :=`{"name":true,"age":false}`
testCases := []struct {
name string
commands []strin... | Also add a test case where the json structure is similar to : `{field: true, nested: {field: false, nested: {field: true}}}` and the user calls `JSON.TOGGLE key $..field`
It will be good to validate the final JSON structure too using `JSON.GET` call. Same for the integration tests.
```sh
0.0.0.0:6379> JSON.SET doc $... | package commands
import (
"encoding/json"
"testing"
"github.com/dicedb/dice/testutils"
"gotest.tools/v3/assert"
)
func compareJSON(t *testing.T, expected, actual string) {
var expectedMap map[string]interface{}
var actualMap map[string]interface{}
err1 := json.Unmarshal([]byte(expected), &expectedMap)
err2... | @@ -0,0 +1,57 @@
+package commands
+
+import (
+ "testing"
+
+ "github.com/dicedb/dice/testutils"
+ "gotest.tools/v3/assert"
+)
+
+func TestEvalJSONTOGGLE(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ simpleJSON :=`{"name":true,"age":false}` | integration_tests/commands/toggle_test.go | 14 | Go | 0.857 | suggestion | 698 | 39 | 39 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | JyotinderSingh | TheRanomial |
return diceerrors.NewErrWithFormattedMessage("-ERR could not perform this operation on a key that doesn't exist")
}
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
jsonDa... | nit: You can improve readability by making the smaller if-blocks.
```suggestion
boolValue, ok := value.(bool)
if !ok {
toggleResults = append(toggleResults, nil)
return value, false
}
newValue := !boolValue
toggleResults = append(toggleResults, boo... | return []interface{}{}, true
}
case utils.ObjectType:
if element != struct{}{} {
countClear++
return struct{}{}, true
}
default:
return element, false
}
return
})
if err != nil {
return diceerrors.NewErrWithMessage(err.Error())
}
// Create a new object with the updated JSON data
n... | @@ -693,6 +689,88 @@ func evalJSONGET(args []string, store *dstore.Store) []byte {
return clientio.Encode(string(resultBytes), false)
}
+// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
+// args must contain at least the key and path (where the boolean is located).
+// If the key doe... | internal/eval/eval.go | 26 | Go | 0.786 | suggestion | 398 | 51 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | JyotinderSingh | TheRanomial |
toggleResults = append(toggleResults, boolToInt(newValue))
modified = true
return newValue, true
}
toggleResults = append(toggleResults, nil)
return value, false
})
if err != nil {
return diceerrors.NewErrWithMessage("failed to toggle values")... | Do we need to create and put a new object into the store or can we simply replace the Value field in the existing `obj`? |
// evalJSONTYPE retrieves a JSON value type stored at the specified key
// args must contain at least the key; (path unused in this implementation)
// Returns response.RespNIL if key is expired or it does not exist
// Returns encoded error response if incorrect number of arguments
// The RESP value of the key's value... | @@ -693,6 +689,88 @@ func evalJSONGET(args []string, store *dstore.Store) []byte {
return clientio.Encode(string(resultBytes), false)
}
+// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
+// args must contain at least the key and path (where the boolean is located).
+// If the key doe... | internal/eval/eval.go | 26 | Go | 0.571 | question | 120 | 51 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | JyotinderSingh | TheRanomial |
if modified {
newObj := &object.Obj{
Value: jsonData,
TypeEncoding: object.ObjTypeJSON,
}
exp, ok := dstore.GetExpiry(obj, store)
var exDurationMs int64 = -1
if ok {
exDurationMs = int64(exp - uint64(utils.GetCurrentTime().UnixMilli(... | ```suggestion
func boolToInt(b bool) int {
return int(b)
}
``` | // Default path is root if not specified
path := defaultRootPath
if len(args) > 1 {
path = args[1]
}
// Retrieve the object from the database
obj := store.Get(key)
if obj == nil {
return clientio.RespNIL
}
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncod... | @@ -693,6 +689,88 @@ func evalJSONGET(args []string, store *dstore.Store) []byte {
return clientio.Encode(string(resultBytes), false)
}
+// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
+// args must contain at least the key and path (where the boolean is located).
+// If the key doe... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 72 | 51 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | JyotinderSingh | TheRanomial |
exDurationMs = int64(exp - uint64(utils.GetCurrentTime().UnixMilli()))
}
if exDurationMs > 0 {
store.SetExpiry(newObj, exDurationMs)
}
store.Put(key, newObj)
}
toggleResults = reverseResults(toggleResults)
return clientio.Encode(toggleResults, false)
... | We can probably make this generic and name it better.
```suggestion
// ReverseSlice takes a slice of any type and returns a new slice with the elements reversed.
func ReverseSlice[T any](slice []T) []T {
reversed := make([]T, len(slice))
for i, v := range slice {
reversed[len(slice)-1-i] = v
... | return clientio.RespNIL
}
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
jsonData := obj.Value
if path == defaultRootPath {
_, err := sonic.Marshal(jsonData)
if err != nil {
return diceer... | @@ -693,6 +689,88 @@ func evalJSONGET(args []string, store *dstore.Store) []byte {
return clientio.Encode(string(resultBytes), false)
}
+// evalJSONTOGGLE toggles a boolean value stored at the specified key and path.
+// args must contain at least the key and path (where the boolean is located).
+// If the key doe... | internal/eval/eval.go | 26 | Go | 1 | suggestion | 350 | 51 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | JyotinderSingh | TheRanomial |
},
{
name: "deeply nested JSON structure with multiple matching fields",
commands: []string{
`JSON.SET user $ `+ complexJson,
"JSON.GET user",
"JSON.TOGGLE user $..field",
"JSON.GET user",
},
expected: []interface{}{"OK",
"{\"f... | You are directly comparing the string representations of the json objects here, the field ordering for json elements is not deterministic - which means the test is flaky om the CI (you can see the failure in the checks).
Unmarshal the expected and actual values into a map and do a deep equal on those. | },
{
name: "JSON.TOGGLE with non-existing key",
commands: []string{"JSON.TOGGLE user $.flag"},
expected: []interface{}{"ERR could not perform this operation on a key that doesn't exist"},
},
{
name: "JSON.TOGGLE with invalid path",
commands: []string{`JSON.SET testkey $ ` + simpleJSON, "J... | @@ -0,0 +1,71 @@
+package commands
+
+import (
+ "testing"
+
+ "github.com/dicedb/dice/testutils"
+ "gotest.tools/v3/assert"
+)
+
+func TestEvalJSONTOGGLE(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ simpleJSON :=`{"name":true,"age":false}`
+ complexJson :=`{"field":true,"nested":{"fiel... | integration_tests/commands/toggle_test.go | 26 | Go | 0.429 | bug | 302 | 31 | 51 | false | #503: Added support for JSON.TOGGLE | 546 | DiceDB/dice | 10,326 | C | JyotinderSingh | TheRanomial |
runEvalTests(t, tests, evalHSET, store)
}
func testEvalSELECT(t *testing.T, store *dstore.Store) {
tests := map[string]evalTestCase{
"nil value": {
setup: func() {},
input: nil,
output: []byte("-ERR wrong number of arguments for 'select' command\r\n"),
},
"database is specified": {
setup: func(... | We can remove this benchmark, it's not needed for this command. | }
runEvalTests(t, tests, evalHSET, store)
}
func testEvalHLEN(t *testing.T, store *dstore.Store) {
tests := map[string]evalTestCase{
"wrong number of args": {
input: []string{},
output: []byte("-ERR wrong number of arguments for 'hlen' command\r\n"),
},
"key does not exist": {
input: []string{"non... | @@ -1442,3 +1410,26 @@ func testEvalHSET(t *testing.T, store *dstore.Store) {
runEvalTests(t, tests, evalHSET, store)
}
+
+func testEvalSELECT(t *testing.T, store *dstore.Store) {
+ tests := map[string]evalTestCase{
+ "nil value": {
+ setup: func() {},
+ input: nil,
+ output: []byte("-ERR wrong number of ... | internal/eval/eval_test.go | 26 | Go | 0.286 | refactor | 63 | 27 | 51 | false | #569: cmd: add SELECT cmd | 574 | DiceDB/dice | 10,326 | C | JyotinderSingh | codeasashu |
// Execute the JSONPath query
results := expr.Get(jsonData)
if len(results) == 0 {
return clientio.Encode([]interface{}{}, false)
}
strLenResults := make([]interface{}, 0, len(results))
for _, result := range results {
switch utils.GetJSONFieldType(result) {
case utils.StringType:
strLenResults = append(... | You can directly return `clientio.RespOK` without first assigning it to a temporary variable. | // Execute the JSONPath query
results := expr.Get(jsonData)
if len(results) == 0 {
return clientio.Encode([]interface{}{}, false)
}
strLenResults := make([]interface{}, 0, len(results))
for _, result := range results {
switch utils.GetJSONFieldType(result) {
case utils.StringType:
strLenResults = append(... | @@ -2745,3 +2748,14 @@ func evalJSONSTRLEN(args []string, store *dstore.Store) []byte {
}
return clientio.Encode(strLenResults, false)
}
+
+func evalSELECT(args []string, store *dstore.Store) []byte {
+ var b []byte
+
+ if len(args) != 1 {
+ return diceerrors.NewErrArity("SELECT")
+ }
+
+ b = clientio.RespOK
+ re... | internal/eval/eval.go | 26 | Go | 0.357 | suggestion | 93 | 28 | 46 | false | #569: cmd: add SELECT cmd | 574 | DiceDB/dice | 10,326 | C | JyotinderSingh | codeasashu |
// check if the object is set type if yes then return error
if object.AssertType(obj.TypeEncoding, object.ObjTypeSet) == nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
var exDurationMs int64 = -1
var state exDurationState = Uninitialized
var persist bool = false
for i := 1; i <... | HI @Gaurav-Kumar81 please make it > maxDuration instead of >=. Because `9223372036854775` value is still allowed. | exp, ok := dstore.GetExpiry(sourceObj, store)
var exDurationMs int64 = -1
if ok {
exDurationMs = int64(exp - uint64(utils.GetCurrentTime().UnixMilli()))
}
store.Put(destinationKey, copyObj)
if exDurationMs > 0 {
store.SetExpiry(copyObj, exDurationMs)
}
return clientio.RespOne
}
// GETEX key [EX seconds |... | @@ -1872,7 +1872,7 @@ func evalGETEX(args []string, store *dstore.Store) []byte {
if err != nil {
return diceerrors.NewErrWithMessage(diceerrors.IntOrOutOfRangeErr)
}
- if exDuration <= 0 {
+ if exDuration <= 0 || exDuration >= maxExDuration { | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 114 | 51 | 51 | false | GETEXwith EX with big integer reports an error | 576 | DiceDB/dice | 10,326 | C | AshwinKul28 | Gaurav-Kumar81 |
if obj == nil {
return clientio.RespNIL
}
// If the object exists, check if it is a set object.
if err := object.AssertType(obj.TypeEncoding, object.ObjTypeSet); err == nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
// return the RESP encoded value
return clientio.Encode(obj.... | Please define `HELP` and `MEMORY` as constants in the constants file and use them here. | if obj == nil {
return clientio.RespNIL
}
// If the object exists, check if it is a Set object.
if err := object.AssertType(obj.TypeEncoding, object.ObjTypeSet); err == nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
// If the object exists, check if it is a JSON object.
if er... | @@ -328,6 +330,153 @@ func evalGETDEL(args []string, store *dstore.Store) []byte {
return clientio.Encode(obj.Value, false)
}
+// evalJSONDEBUG reports value's memmory usage in bytes
+// Returns arity error if subcommand is missing
+// Supports only two subcommand as of now - HELP and MEMORY
+func evalJSONDebug(ar... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 87 | 51 | 51 | false | Added support for JSON.DEBUG | 579 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
return evalJSONDebugMemory(args[1:], store)
default:
return diceerrors.NewErrWithFormattedMessage("unknown subcommand - try `JSON.DEBUG HELP`")
}
}
// evalJSONDebugHelp implements HELP subcommand for evalJSONDebug
// It returns help text
// It ignore any other args
func evalJSONDebugHelp() []byte {
memoryText :... | ```suggestion
return diceerrors.NewErrArity("json.debug")
``` |
case object.ObjEncodingEmbStr, object.ObjEncodingRaw:
// Value is stored as a string, use type assertion
if val, ok := objVal.Value.(string); ok {
return clientio.Encode(val, false)
}
return diceerrors.NewErrWithMessage("expected string but got another type")
case object.ObjEncodingByteArray:
// Value ... | @@ -328,6 +330,153 @@ func evalGETDEL(args []string, store *dstore.Store) []byte {
return clientio.Encode(obj.Value, false)
}
+// evalJSONDEBUG reports value's memmory usage in bytes
+// Returns arity error if subcommand is missing
+// Supports only two subcommand as of now - HELP and MEMORY
+func evalJSONDebug(ar... | internal/eval/eval.go | 26 | Go | 0.714 | bug | 65 | 51 | 51 | false | Added support for JSON.DEBUG | 579 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
package utils
func IsArray(data any) bool {
_, ok := data.([]any)
return ok
}
| ```suggestion
func IsArray(data any) bool {
kind := reflect.TypeOf(data).Kind()
return kind == reflect.Array || kind == reflect.Slice
}
```
The function only checks if data is of type `[]any`, which means it will return false for slices of any other type (e.g., `[]int`, `[]string`).
You can use reflect... | package utils
import "reflect"
func IsArray(data any) bool {
kind := reflect.TypeOf(data).Kind()
return kind == reflect.Array || kind == reflect.Slice
}
| @@ -0,0 +1,6 @@
+package utils
+
+func IsArray(data any) bool {
+ _, ok := data.([]any)
+ return ok
+} | internal/server/utils/array.go | 6 | Go | 1 | bug | 509 | 7 | 9 | false | Added support for JSON.DEBUG | 579 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
}
// add memory used by storage object
size += int(unsafe.Sizeof(obj)) + calculateMemory(obj.LastAccessedAt) + calculateMemory(obj.TypeEncoding)
return clientio.Encode(size, false)
}
// handle nested paths
var results []any = []any{}
if path != defaultRootPath {
// check if path is valid
expr, err :... | You are casting types twice, once inside the `IsArray` method and once here. This adds to the latency.
You can replace the call to `IsArray` with the following:
```go
arr, ok := obj.Value.([]any)
if !ok {
// return err
}
// use arr
``` | // It returns value's memory usage in bytes
func evalJSONDebugMemory(args []string, store *dstore.Store) []byte {
if len(args) < 1 {
return diceerrors.NewErrArity("json.debug")
}
key := args[0]
// default path is root if not specified
path := defaultRootPath
if len(args) > 1 {
path = args[1] // any more args... | @@ -328,6 +330,153 @@ func evalGETDEL(args []string, store *dstore.Store) []byte {
return clientio.Encode(obj.Value, false)
}
+// evalJSONDEBUG reports value's memmory usage in bytes
+// Returns arity error if subcommand is missing
+// Supports only two subcommand as of now - HELP and MEMORY
+func evalJSONDebug(ar... | internal/eval/eval.go | 26 | Go | 1 | performance | 247 | 51 | 51 | false | Added support for JSON.DEBUG | 579 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
expr, err := jp.ParseString(path)
if err != nil {
return diceerrors.NewErrWithMessage("invalid JSON path")
}
results = expr.Get(obj.Value)
// handle error cases
if len(results) == 0 {
// handle out of bound index path for array json type
isArray := utils.IsArray(obj.Value)
if isArray {
arr... | Can you help me understand what's happening here? Maybe add a few comments here too. | obj := store.Get(key)
if obj == nil {
return clientio.RespZero
}
// check if the object is a valid JSON
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
// handle root path
if path == defaultRoo... | @@ -328,6 +330,153 @@ func evalGETDEL(args []string, store *dstore.Store) []byte {
return clientio.Encode(obj.Value, false)
}
+// evalJSONDEBUG reports value's memmory usage in bytes
+// Returns arity error if subcommand is missing
+// Supports only two subcommand as of now - HELP and MEMORY
+func evalJSONDebug(ar... | internal/eval/eval.go | 26 | Go | 0.214 | suggestion | 84 | 51 | 51 | false | Added support for JSON.DEBUG | 579 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
index, err := strconv.Atoi(matches[2])
if err != nil {
return diceerrors.NewErrWithMessage("unable to extract index")
}
if index >= len(arr) {
return clientio.RespEmptyArray
}
}
}
// for rest json types, throw error
return diceerrors.NewErrWithFormattedMessage("Path '$... | nit:
```suggestion
func calculateSizeInBytes(value interface{}) int {
``` | if size == -1 {
return diceerrors.NewErrWithMessage("unknown type")
}
// add memory used by storage object
size += int(unsafe.Sizeof(obj)) + calculateSizeInBytes(obj.LastAccessedAt) + calculateSizeInBytes(obj.TypeEncoding)
return clientio.Encode(size, false)
}
// handle nested paths
var results []any... | @@ -328,6 +330,153 @@ func evalGETDEL(args []string, store *dstore.Store) []byte {
return clientio.Encode(obj.Value, false)
}
+// evalJSONDEBUG reports value's memmory usage in bytes
+// Returns arity error if subcommand is missing
+// Supports only two subcommand as of now - HELP and MEMORY
+func evalJSONDebug(ar... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 76 | 51 | 51 | false | Added support for JSON.DEBUG | 579 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
return diceerrors.NewErrArity("LLEN")
}
obj := store.Get(args[0])
if obj == nil {
return clientio.Encode(0, false)
}
// if object is a set type, return error
if object.AssertType(obj.TypeEncoding, object.ObjTypeSet) == nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
if err... | Can't we simply use
```go
object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeByteList, object.ObjEncodingDeque)
``` | panic(fmt.Sprintf("unknown error: %v", err))
}
return clientio.Encode(x, false)
}
func evalLLEN(args []string, store *dstore.Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrArity("LLEN")
}
obj := store.Get(args[0])
if obj == nil {
return clientio.Encode(0, false)
}
if err := object.AssertT... | @@ -2219,6 +2219,33 @@ func evalLPOP(args []string, store *dstore.Store) []byte {
return clientio.Encode(x, false)
}
+func evalLLEN(args []string, store *dstore.Store) []byte {
+ if len(args) != 1 {
+ return diceerrors.NewErrArity("LLEN")
+ }
+
+ obj := store.Get(args[0])
+ if obj == nil {
+ return clientio.Enco... | internal/eval/eval.go | 26 | Go | 0.929 | suggestion | 129 | 51 | 51 | false | #572: Added support for LLEN command | 580 | DiceDB/dice | 10,326 | C | JyotinderSingh | jainbhavya53 |
deq := obj.Value.(*Deque)
x, err := deq.LPop()
if err != nil {
if err == ErrDequeEmpty {
return clientio.RespNIL
}
panic(fmt.Sprintf("unknown error: %v", err))
}
return clientio.Encode(x, false)
}
func evalLLEN(args []string, store *dstore.Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrA... | I don't think this is required.
```suggestion
``` | deq := obj.Value.(*Deque)
x, err := deq.LPop()
if err != nil {
if err == ErrDequeEmpty {
return clientio.RespNIL
}
panic(fmt.Sprintf("unknown error: %v", err))
}
return clientio.Encode(x, false)
}
func evalLLEN(args []string, store *dstore.Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrA... | @@ -2227,6 +2227,29 @@ func evalLPOP(args []string, store *dstore.Store) []byte {
return clientio.Encode(x, false)
}
+func evalLLEN(args []string, store *dstore.Store) []byte {
+ if len(args) != 1 {
+ return diceerrors.NewErrArity("LLEN")
+ }
+
+ obj := store.Get(args[0])
+ if obj == nil {
+ return clientio.Enco... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 51 | 51 | 51 | false | #572: Added support for LLEN command | 580 | DiceDB/dice | 10,326 | C | JyotinderSingh | jainbhavya53 |
if err == ErrDequeEmpty {
return clientio.RespNIL
}
panic(fmt.Sprintf("unknown error: %v", err))
}
return clientio.Encode(x, false)
}
func evalLLEN(args []string, store *dstore.Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrArity("LLEN")
}
obj := store.Get(args[0])
if obj == nil {
ret... | Return the error directly, it is already encoded. Include a test case validating the error message too.
```suggestion
return err | if err == ErrDequeEmpty {
return clientio.RespNIL
}
panic(fmt.Sprintf("unknown error: %v", err))
}
return clientio.Encode(x, false)
}
func evalLLEN(args []string, store *dstore.Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrArity("LLEN")
}
obj := store.Get(args[0])
if obj == nil {
ret... | @@ -2227,6 +2227,29 @@ func evalLPOP(args []string, store *dstore.Store) []byte {
return clientio.Encode(x, false)
}
+func evalLLEN(args []string, store *dstore.Store) []byte {
+ if len(args) != 1 {
+ return diceerrors.NewErrArity("LLEN")
+ }
+
+ obj := store.Get(args[0])
+ if obj == nil {
+ return clientio.Enco... | internal/eval/eval.go | 26 | Go | 0.857 | suggestion | 132 | 51 | 51 | false | #572: Added support for LLEN command | 580 | DiceDB/dice | 10,326 | C | JyotinderSingh | jainbhavya53 |
"github.com/dicedb/dice/internal/shard"
dstore "github.com/dicedb/dice/internal/store"
"github.com/dicedb/dice/internal/server"
"log/slog"
"github.com/dicedb/dice/config"
"github.com/rs/zerolog"
slogzerolog "github.com/samber/slog-zerolog/v2"
)
func setupFlags() {
flag.StringVar(&config.Host, "host", "0.0.... | not entirely happy with this being here, what would be the right place for it? | "github.com/dicedb/dice/internal/logger"
"github.com/dicedb/dice/internal/shard"
dstore "github.com/dicedb/dice/internal/store"
"github.com/dicedb/dice/internal/server"
"log/slog"
"github.com/dicedb/dice/config"
)
func init() {
flag.StringVar(&config.Host, "host", "0.0.0.0", "host for the dice server")
flag... | @@ -30,7 +34,36 @@ func setupFlags() {
flag.Parse()
}
+func getLogLevel() slog.Leveler { | main.go | 26 | Go | 0.214 | question | 78 | 51 | 51 | false | Setup slog with zerolog | 584 | DiceDB/dice | 10,326 | C | KaviiSuri | KaviiSuri |
package eval
import (
"bytes"
"errors"
"fmt"
"log/slog"
"math"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/dicedb/dice/internal/object"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/dicedb/dice/config"
"github.com/dicedb/d... | eval functions arne't recievers, so they don't have any structs to store loggers in. I can imagine multiple approaches here.
1. use the global logger using slog.Info as we do right now
2. use the logger by passing logger in as a argument to each eval function
3. pass in a `context.Context` that has a logger in it.... | // Bulk string reply: the old value stored at the key.
// Nil reply: if the key does not exist.
func evalGETSET(args []string, store *dstore.Store) []byte {
if len(args) != 2 {
return diceerrors.NewErrArity("GETSET")
}
key, value := args[0], args[1]
getResp := evalGET([]string{key}, store)
// Check if it's an e... | @@ -2258,7 +2258,7 @@ func evalGETSET(args []string, store *dstore.Store) []byte {
}
func evalFLUSHDB(args []string, store *dstore.Store) []byte {
- log.Info(args)
+ slog.Info("FLUSHDB called", slog.Any("args", args)) | internal/eval/eval.go | 26 | Go | 0.643 | suggestion | 413 | 2,785 | 51 | false | Setup slog with zerolog | 584 | DiceDB/dice | 10,326 | C | KaviiSuri | KaviiSuri |
)
type Config struct {
Server struct {
Addr string `mapstructure:"addr"`
Port int `mapstructure:"port"`
KeepAlive int32 `mapstructure:"keepalive"`
Timeout int32 `mapstructure:"timeout"`
MaxConn in... | I think rather than using `PrettyPrintLogs` we should use env based log ( i.e dev/prod ) allow pretty logs in dev | CustomConfigFilePath = utils.EmptyStr
ConfigFileLocation = utils.EmptyStr
InitConfigCmd = false
)
type Config struct {
Server struct {
Addr string `mapstructure:"addr"`
Port int `mapstructure:"port"`
KeepAlive int32 `mapstructure:"k... | @@ -53,6 +53,8 @@ type Config struct {
AOFFile string `mapstructure:"aoffile"`
PersistenceEnabled bool `mapstructure:"persistenceenabled"`
WriteAOFOnCleanup bool `mapstructure:"writeaofoncleanup"`
+ LogLevel string `mapstructure:"loglevel"`... | config/config.go | 26 | Go | 0.571 | suggestion | 113 | 51 | 51 | false | Setup slog with zerolog | 584 | DiceDB/dice | 10,326 | C | vinitparekh17 | KaviiSuri |
LogLevel string `mapstructure:"loglevel"`
PrettyPrintLogs bool `mapstructure:"prettyprintlogs"`
}{
Addr: DefaultHost,
Port: DefaultPort,
KeepAlive: int32(300),
Timeout: int32(300),
MaxConn: ... | Should default level be `warn (zerolog.WarnLevel, 2)`?
| EvictionRatio float64 `mapstructure:"evictionratio"`
KeysLimit int `mapstructure:"keyslimit"`
AOFFile string `mapstructure:"aoffile"`
PersistenceEnabled bool `mapstructure:"persistenceenabled"`
WriteAOFOnCleanup bool `mapst... | @@ -98,6 +102,8 @@ var defaultConfig = Config{
AOFFile: "./dice-master.aof",
PersistenceEnabled: true,
WriteAOFOnCleanup: false,
+ LogLevel: "info", | config/config.go | 26 | Go | 0.429 | question | 56 | 51 | 51 | false | Setup slog with zerolog | 584 | DiceDB/dice | 10,326 | C | lucifercr07 | KaviiSuri |
func FireCommand(conn net.Conn, cmd string) interface{} {
var err error
args := testutils.ParseCommand(cmd)
_, err = conn.Write(clientio.Encode(args, false))
if err != nil {
slog.Error(
"error while firing command",
slog.Any("error", err),
slog.String("command", cmd),
)
os.Exit(1)
}
rp := clienti... | Shall we write our own function wrapper like `func LogErrorFatal(l *slog.Logger, ..)` and use it instead of calling `os.Exit(1)`?
May be we can do this as part of package implementaion. |
func FireCommand(conn net.Conn, cmd string) interface{} {
var err error
args := testutils.ParseCommand(cmd)
_, err = conn.Write(clientio.Encode(args, false))
if err != nil {
slog.Error(
"error while firing command",
slog.Any("error", err),
slog.String("command", cmd),
)
os.Exit(1)
}
rp := clienti... | @@ -76,7 +83,12 @@ func FireCommand(conn net.Conn, cmd string) interface{} {
if err == io.EOF {
return nil
}
- log.Fatalf("error %s while firing command: %s", err, cmd)
+ slog.Error(
+ "error while firing command",
+ slog.Any("error", err),
+ slog.String("command", cmd),
+ )
+ os.Exit(1) | integration_tests/commands/setup.go | 26 | Go | 0.714 | suggestion | 186 | 51 | 51 | false | Setup slog with zerolog | 584 | DiceDB/dice | 10,326 | C | lucifercr07 | KaviiSuri |
// ZerologHandler is a custom handler that adapts slog to zerolog
type ZerologHandler struct {
logger zerolog.Logger
}
// newZerologHandler creates a new ZerologHandler
func newZerologHandler(logger zerolog.Logger) *ZerologHandler {
return &ZerologHandler{logger: logger}
}
// Handle implements the slog.Handler int... | `default` and `slog.KindAny` is doing exact same thing which results in redundant code.
we can simplify it by removing `slog.KindAny` case and rely on `default`. |
// ZerologHandler is a custom handler that adapts slog to zerolog
type ZerologHandler struct {
logger *zerolog.Logger
}
// newZerologHandler creates a new ZerologHandler
func newZerologHandler(logger *zerolog.Logger) *ZerologHandler {
return &ZerologHandler{
logger: logger,
}
}
// Handle implements the slog.Han... | @@ -0,0 +1,81 @@
+package logger
+
+import (
+ "context"
+ "log/slog"
+
+ "github.com/rs/zerolog"
+)
+
+// ZerologHandler is a custom handler that adapts slog to zerolog
+type ZerologHandler struct {
+ logger zerolog.Logger
+}
+
+// newZerologHandler creates a new ZerologHandler
+func newZerologHandler(logger zerolog.L... | internal/logger/zerolog.go | 26 | Go | 0.571 | refactor | 164 | 51 | 51 | false | Setup slog with zerolog | 584 | DiceDB/dice | 10,326 | C | vinitparekh17 | KaviiSuri |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.