From 513e5e7961ecc9fe8155811d6cbb6a6c77e0638d Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 8 Jul 2026 20:30:16 +0200 Subject: refactored EXISTS,SET,GET to support multiple shards --- handlers.go | 75 ++++++++++++++++++++++++++++++------------------------------- 1 file changed, 37 insertions(+), 38 deletions(-) (limited to 'handlers.go') diff --git a/handlers.go b/handlers.go index 305d526..aefea85 100644 --- a/handlers.go +++ b/handlers.go @@ -3,50 +3,42 @@ package main import ( "errors" "net" - "path/filepath" - "sort" - "strconv" "time" ) func handleGet(conn net.Conn, args []string) { - db.mu.Lock() - defer db.mu.Unlock() - if len(args) != 2 { err := errors.New("wrong number of arguments for 'GET'") conn.Write(serializeRESP(err)) return } + + key := args[1] - key := args[1] + result := db.Execute(key, func(s *Shard) interface{}{ + item, exists := s.data[key] + if !exists { + return nil + } - item, exists := db.data[key] - if !exists { - conn.Write(serializeRESP(nil)) - return - } + if item.ExpiresAt != nil && time.Now().After(*item.ExpiresAt) { + delete(s.data, key) + return nil + } - if item.ExpiresAt != nil && time.Now().After(*item.ExpiresAt) { - delete(db.data, key) - conn.Write(serializeRESP(nil)) - return - } + strValue, ok := item.Value.(string) + if !ok { + err := errors.New("WRONGTYPE Operation against a key holding the wrong kind of value") + return err + } + return strValue + }) - strValue, ok := item.Value.(string) - if !ok { - err := errors.New("WRONGTYPE Operation against a key holding the wrong kind of value") - conn.Write(serializeRESP(err)) - return - } - conn.Write(serializeRESP(strValue)) + conn.Write(serializeRESP(result)) } func handleExists(conn net.Conn, args []string) { - db.mu.Lock() - defer db.mu.Unlock() - if len(args) != 2 { err := errors.New("wrong number of arguments for 'EXISTS'") conn.Write(serializeRESP(err)) @@ -54,13 +46,16 @@ func handleExists(conn net.Conn, args []string) { } key := args[1] + result := db.Execute(key, func(s *Shard) interface{}{ + _, exists := s.data[key] + if exists { + return 1 + } else { + return 0 + } + }) - _, exists := db.data[key] - if exists { - conn.Write(serializeRESP(1)) - } else { - conn.Write(serializeRESP(0)) - } + conn.Write(serializeRESP(result)) } func handleSet(conn net.Conn, args []string) { @@ -74,12 +69,15 @@ func handleSet(conn net.Conn, args []string) { } key := args[1] - item := Item{Value: args[2]} + result := db.Execute(key, func(s *Shard) interface{}{ + item := Item{Value: args[2]} + s.data[key] = item + return SimpleString("OK") + }) - db.data[key] = item - conn.Write(serializeRESP(SimpleString("OK"))) + conn.Write(serializeRESP(result)) } - +/* func handleDel(conn net.Conn, args []string) { db.mu.Lock() defer db.mu.Unlock() @@ -730,4 +728,5 @@ func handleLrem(conn net.Conn, args []string){ item.Value = list db.data[key] = item conn.Write(serializeRESP(counter)) -} \ No newline at end of file +} +*/ \ No newline at end of file -- cgit v1.2.3