From 58221adccb1c27b921fa399414d598cad5fd9a9a Mon Sep 17 00:00:00 2001 From: tidwall Date: Thu, 8 Jul 2021 06:46:08 -0700 Subject: [PATCH] Code cleanup - Removed unused functions and variables - Wrapped client formatted errors - Updated deprecated packages - Changed suggested code patterns --- go.mod | 2 +- go.sum | 5 +- internal/clip/clip.go | 11 +-- internal/clip/clip_test.go | 4 +- internal/collection/collection.go | 2 - internal/collection/collection_test.go | 11 ++- internal/endpoint/amqp.go | 2 +- internal/endpoint/disque.go | 2 +- internal/endpoint/grpc.go | 2 +- internal/endpoint/kafka.go | 2 +- internal/endpoint/local.go | 6 -- internal/endpoint/mqtt.go | 2 +- internal/endpoint/nats.go | 2 +- internal/endpoint/redis.go | 2 +- internal/endpoint/sqs.go | 7 +- internal/expire/expire.go | 1 - internal/log/log.go | 4 +- internal/server/aof.go | 12 +-- internal/server/aofmigrate.go | 2 +- internal/server/aofshrink.go | 11 +-- internal/server/client.go | 51 +++---------- internal/server/config.go | 66 +--------------- internal/server/crud.go | 30 ++++---- internal/server/dev.go | 3 +- internal/server/follow.go | 2 +- internal/server/hooks.go | 10 ++- internal/server/json.go | 6 +- internal/server/keys.go | 2 +- internal/server/monitor.go | 30 ++++---- internal/server/output.go | 2 +- internal/server/pubsub.go | 10 +-- internal/server/scan.go | 4 +- internal/server/scripts.go | 10 +-- internal/server/search.go | 8 +- internal/server/server.go | 33 ++++---- internal/server/stats.go | 31 +------- internal/server/test.go | 3 +- internal/server/token.go | 43 ----------- .../x/crypto/ssh/terminal/terminal.go | 76 ------------------- vendor/modules.txt | 8 ++ 40 files changed, 134 insertions(+), 386 deletions(-) delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/terminal.go diff --git a/go.mod b/go.mod index b9500a9f..f8f410fa 100644 --- a/go.mod +++ b/go.mod @@ -28,8 +28,8 @@ require ( github.com/tidwall/rtree v1.2.7 github.com/tidwall/sjson v1.1.6 github.com/yuin/gopher-lua v0.0.0-20200816102855-ee81675732da - golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad golang.org/x/net v0.0.0-20210119194325-5f4716e94777 + golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 google.golang.org/api v0.20.0 google.golang.org/grpc v1.35.0 layeh.com/gopher-json v0.0.0-20201124131017-552bb3c4c3bf diff --git a/go.sum b/go.sum index f28148d1..251a2557 100644 --- a/go.sum +++ b/go.sum @@ -235,9 +235,8 @@ golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a h1:vclmkQCjlDX5OydZ9wv8rBCcS0QyQY66Mpf/7BZbInM= golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY= -golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -315,7 +314,6 @@ golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -328,7 +326,6 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= diff --git a/internal/clip/clip.go b/internal/clip/clip.go index 88797266..97b9bfd5 100644 --- a/internal/clip/clip.go +++ b/internal/clip/clip.go @@ -79,9 +79,9 @@ func clipRing(ring []geometry.Point, bbox geometry.Rect) ( // Entering resRing = append(resRing, intersect(bbox, edge, prev, p)) resRing = append(resRing, p) - } else { - // Staying outside - } + } /* else { + // Stay outside + } */ prev, prevInside = p, inside } if len(resRing) > 0 && resRing[0] != resRing[len(resRing)-1] { @@ -137,8 +137,9 @@ func intersect(bbox geometry.Rect, code uint8, start, end geometry.Point) ( X: bbox.Min.X, Y: start.Y + (end.Y-start.Y)*(bbox.Min.X-start.X)/(end.X-start.X), } - } else { // should not call intersect with the zero code - } + } /* else { + // should not call intersect with the zero code + } */ return } diff --git a/internal/clip/clip_test.go b/internal/clip/clip_test.go index dee60edc..3e4ecf1d 100644 --- a/internal/clip/clip_test.go +++ b/internal/clip/clip_test.go @@ -47,7 +47,7 @@ func TestClipPolygonSimple(t *testing.T) { {X: 2, Y: 2}, } holes := [][]geometry.Point{ - []geometry.Point{ + { {X: 1.9, Y: 1.9}, {X: 1.2, Y: 1.9}, {X: 1.45, Y: 1.65}, @@ -79,7 +79,7 @@ func TestClipPolygon2(t *testing.T) { {X: 2, Y: 2}, } holes := [][]geometry.Point{ - []geometry.Point{ + { {X: 1.9, Y: 1.9}, {X: 1.2, Y: 1.9}, {X: 1.45, Y: 1.65}, diff --git a/internal/collection/collection.go b/internal/collection/collection.go index f5b55683..d8c84633 100644 --- a/internal/collection/collection.go +++ b/internal/collection/collection.go @@ -58,8 +58,6 @@ type Collection struct { nobjects int // non-geometry count } -var counter uint64 - // New creates an empty collection func New() *Collection { col := &Collection{ diff --git a/internal/collection/collection_test.go b/internal/collection/collection_test.go index edf6fd81..7471f071 100644 --- a/internal/collection/collection_test.go +++ b/internal/collection/collection_test.go @@ -44,8 +44,7 @@ func TestCollectionNewCollection(t *testing.T) { c := New() for i := 0; i < numItems; i++ { id := strconv.FormatInt(int64(i), 10) - var obj geojson.Object - obj = PO(rand.Float64()*360-180, rand.Float64()*180-90) + obj := PO(rand.Float64()*360-180, rand.Float64()*180-90) objs[id] = obj c.Set(id, obj, nil, nil) } @@ -168,23 +167,23 @@ func TestCollectionSet(t *testing.T) { expect(t, len(c.FieldMap()) == 0) - v, flds, updated, ok = c.SetField("3", "hello", 123) + _, flds, updated, ok = c.SetField("3", "hello", 123) expect(t, ok) expect(t, reflect.DeepEqual(flds, []float64{123})) expect(t, updated) expect(t, c.FieldMap()["hello"] == 0) - v, flds, updated, ok = c.SetField("3", "hello", 1234) + _, flds, updated, ok = c.SetField("3", "hello", 1234) expect(t, ok) expect(t, reflect.DeepEqual(flds, []float64{1234})) expect(t, updated) - v, flds, updated, ok = c.SetField("3", "hello", 1234) + _, flds, updated, ok = c.SetField("3", "hello", 1234) expect(t, ok) expect(t, reflect.DeepEqual(flds, []float64{1234})) expect(t, !updated) - v, flds, updateCount, ok = c.SetFields("3", + _, flds, updateCount, ok = c.SetFields("3", []string{"planet", "world"}, []float64{55, 66}) expect(t, ok) expect(t, reflect.DeepEqual(flds, []float64{1234, 55, 66})) diff --git a/internal/endpoint/amqp.go b/internal/endpoint/amqp.go index f8cf4444..546dee78 100644 --- a/internal/endpoint/amqp.go +++ b/internal/endpoint/amqp.go @@ -26,7 +26,7 @@ func (conn *AMQPConn) Expired() bool { conn.mu.Lock() defer conn.mu.Unlock() if !conn.ex { - if time.Now().Sub(conn.t) > amqpExpiresAfter { + if time.Since(conn.t) > amqpExpiresAfter { conn.ex = true conn.close() } diff --git a/internal/endpoint/disque.go b/internal/endpoint/disque.go index 73e08496..35300ec6 100644 --- a/internal/endpoint/disque.go +++ b/internal/endpoint/disque.go @@ -32,7 +32,7 @@ func (conn *DisqueConn) Expired() bool { conn.mu.Lock() defer conn.mu.Unlock() if !conn.ex { - if time.Now().Sub(conn.t) > disqueExpiresAfter { + if time.Since(conn.t) > disqueExpiresAfter { if conn.conn != nil { conn.close() } diff --git a/internal/endpoint/grpc.go b/internal/endpoint/grpc.go index 2a1a9a3b..12de3d7e 100644 --- a/internal/endpoint/grpc.go +++ b/internal/endpoint/grpc.go @@ -35,7 +35,7 @@ func (conn *GRPCConn) Expired() bool { conn.mu.Lock() defer conn.mu.Unlock() if !conn.ex { - if time.Now().Sub(conn.t) > grpcExpiresAfter { + if time.Since(conn.t) > grpcExpiresAfter { if conn.conn != nil { conn.close() } diff --git a/internal/endpoint/kafka.go b/internal/endpoint/kafka.go index 51581184..3c2ed4d9 100644 --- a/internal/endpoint/kafka.go +++ b/internal/endpoint/kafka.go @@ -32,7 +32,7 @@ func (conn *KafkaConn) Expired() bool { conn.mu.Lock() defer conn.mu.Unlock() if !conn.ex { - if time.Now().Sub(conn.t) > kafkaExpiresAfter { + if time.Since(conn.t) > kafkaExpiresAfter { if conn.conn != nil { conn.close() } diff --git a/internal/endpoint/local.go b/internal/endpoint/local.go index 3a807183..1038fd79 100644 --- a/internal/endpoint/local.go +++ b/internal/endpoint/local.go @@ -1,11 +1,5 @@ package endpoint -import ( - "time" -) - -const localExpiresAfter = time.Second * 30 - // LocalPublisher is used to publish local notifcations type LocalPublisher interface { Publish(channel string, message ...string) int diff --git a/internal/endpoint/mqtt.go b/internal/endpoint/mqtt.go index f0f178a4..b755e40c 100644 --- a/internal/endpoint/mqtt.go +++ b/internal/endpoint/mqtt.go @@ -32,7 +32,7 @@ func (conn *MQTTConn) Expired() bool { conn.mu.Lock() defer conn.mu.Unlock() if !conn.ex { - if time.Now().Sub(conn.t) > mqttExpiresAfter { + if time.Since(conn.t) > mqttExpiresAfter { conn.close() conn.ex = true } diff --git a/internal/endpoint/nats.go b/internal/endpoint/nats.go index 92e49b18..6030ec40 100644 --- a/internal/endpoint/nats.go +++ b/internal/endpoint/nats.go @@ -31,7 +31,7 @@ func (conn *NATSConn) Expired() bool { conn.mu.Lock() defer conn.mu.Unlock() if !conn.ex { - if time.Now().Sub(conn.t) > natsExpiresAfter { + if time.Since(conn.t) > natsExpiresAfter { if conn.conn != nil { conn.close() } diff --git a/internal/endpoint/redis.go b/internal/endpoint/redis.go index 29542864..8064d166 100644 --- a/internal/endpoint/redis.go +++ b/internal/endpoint/redis.go @@ -31,7 +31,7 @@ func (conn *RedisConn) Expired() bool { conn.mu.Lock() defer conn.mu.Unlock() if !conn.ex { - if time.Now().Sub(conn.t) > redisExpiresAfter { + if time.Since(conn.t) > redisExpiresAfter { if conn.conn != nil { conn.close() } diff --git a/internal/endpoint/sqs.go b/internal/endpoint/sqs.go index dd6dd6cf..8a1098b7 100644 --- a/internal/endpoint/sqs.go +++ b/internal/endpoint/sqs.go @@ -1,7 +1,6 @@ package endpoint import ( - "errors" "fmt" "strings" "sync" @@ -11,12 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sqs" - "github.com/streadway/amqp" "github.com/tidwall/tile38/internal/log" ) -var errCreateQueue = errors.New("Error while creating queue") - const sqsExpiresAfter = time.Second * 30 // SQSConn is an endpoint connection @@ -25,7 +21,6 @@ type SQSConn struct { ep Endpoint session *session.Session svc *sqs.SQS - channel *amqp.Channel ex bool t time.Time } @@ -43,7 +38,7 @@ func (conn *SQSConn) Expired() bool { conn.mu.Lock() defer conn.mu.Unlock() if !conn.ex { - if time.Now().Sub(conn.t) > sqsExpiresAfter { + if time.Since(conn.t) > sqsExpiresAfter { conn.ex = true conn.close() } diff --git a/internal/expire/expire.go b/internal/expire/expire.go index 4c040036..a501f28a 100644 --- a/internal/expire/expire.go +++ b/internal/expire/expire.go @@ -62,7 +62,6 @@ type qnode struct { type queue struct { nodes []qnode len int - size int } func (q *queue) push(unix int64, item Item) { diff --git a/internal/log/log.go b/internal/log/log.go index eaebf044..8afb3df0 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -7,7 +7,7 @@ import ( "sync" "time" - "golang.org/x/crypto/ssh/terminal" + "golang.org/x/term" ) var mu sync.Mutex @@ -24,7 +24,7 @@ var Level = 1 // SetOutput sets the output of the logger func SetOutput(w io.Writer) { f, ok := w.(*os.File) - tty = ok && terminal.IsTerminal(int(f.Fd())) + tty = ok && term.IsTerminal(int(f.Fd())) wr = w } diff --git a/internal/server/aof.go b/internal/server/aof.go index 40119ed1..c8ed7b6c 100644 --- a/internal/server/aof.go +++ b/internal/server/aof.go @@ -29,8 +29,6 @@ func (err errAOFHook) Error() string { return fmt.Sprintf("hook: %v", err.err) } -var errInvalidAOF = errors.New("invalid aof file") - func (s *Server) loadAOF() (err error) { fi, err := s.aof.Stat() if err != nil { @@ -39,7 +37,7 @@ func (s *Server) loadAOF() (err error) { start := time.Now() var count int defer func() { - d := time.Now().Sub(start) + d := time.Since(start) ps := float64(count) / (float64(d) / float64(time.Second)) suf := []string{"bytes/s", "KB/s", "MB/s", "GB/s", "TB/s"} bps := float64(fi.Size()) / (float64(d) / float64(time.Second)) @@ -95,7 +93,7 @@ func (s *Server) loadAOF() (err error) { continue } if zeros > 0 { - return errors.New("Zeros found in AOF file (issue #230)") + return clientErrorf("Zeros found in AOF file (issue #230)") } } complete, args, _, data, err = redcon.ReadNextCommand(data, args[:0]) @@ -211,9 +209,7 @@ func (s *Server) writeAOF(args []string, d *commandDetails) error { if len(s.lives) > 0 { if d.parent { // queue children - for _, d := range d.children { - s.lstack = append(s.lstack, d) - } + s.lstack = append(s.lstack, d.children...) } else { // queue parent s.lstack = append(s.lstack, d) @@ -444,7 +440,7 @@ func (s *Server) cmdAOFMD5(msg *Message) (res resp.Value, err error) { switch msg.OutputType { case JSON: res = resp.StringValue( - fmt.Sprintf(`{"ok":true,"md5":"%s","elapsed":"%s"}`, sum, time.Now().Sub(start))) + fmt.Sprintf(`{"ok":true,"md5":"%s","elapsed":"%s"}`, sum, time.Since(start))) case RESP: res = resp.SimpleStringValue(sum) } diff --git a/internal/server/aofmigrate.go b/internal/server/aofmigrate.go index afdb0819..e5947077 100644 --- a/internal/server/aofmigrate.go +++ b/internal/server/aofmigrate.go @@ -154,6 +154,6 @@ func (s *Server) migrateAOF() error { } oldf.Close() newf.Close() - log.Debugf("%d items: %.0f/sec", count, float64(count)/(float64(time.Now().Sub(start))/float64(time.Second))) + log.Debugf("%d items: %.0f/sec", count, float64(count)/(float64(time.Since(start))/float64(time.Second))) return os.Rename(path.Join(s.dir, "migrate.aof"), path.Join(s.dir, "appendonly.aof")) } diff --git a/internal/server/aofshrink.go b/internal/server/aofshrink.go index 67c8318b..be01af89 100644 --- a/internal/server/aofshrink.go +++ b/internal/server/aofshrink.go @@ -38,8 +38,7 @@ func (server *Server) aofshrink() { server.shrinking = false server.shrinklog = nil server.mu.Unlock() - log.Infof("aof shrink ended %v", time.Now().Sub(start)) - return + log.Infof("aof shrink ended %v", time.Since(start)) }() err := func() error { @@ -199,20 +198,16 @@ func (server *Server) aofshrink() { } else { values = append(values, "sethook", name, strings.Join(hook.Endpoints, ",")) - values = append(values) } for _, meta := range hook.Metas { values = append(values, "meta", meta.Name, meta.Value) } if !hook.expires.IsZero() { - ex := float64(hook.expires.Sub(time.Now())) / - float64(time.Second) + ex := float64(time.Until(hook.expires)) / float64(time.Second) values = append(values, "ex", strconv.FormatFloat(ex, 'f', 1, 64)) } - for _, value := range hook.Message.Args { - values = append(values, value) - } + values = append(values, hook.Message.Args...) // append the values to the aof buffer aofbuf = append(aofbuf, '*') aofbuf = append(aofbuf, strconv.FormatInt(int64(len(values)), 10)...) diff --git a/internal/server/client.go b/internal/server/client.go index a41cfbee..6af0a108 100644 --- a/internal/server/client.go +++ b/internal/server/client.go @@ -60,8 +60,9 @@ func (s *Server) cmdClient(msg *Message, client *Client) (resp.Value, error) { } switch strings.ToLower(msg.Args[1]) { default: - return NOMessage, errors.New("Syntax error, try CLIENT " + - "(LIST | KILL | GETNAME | SETNAME)") + return NOMessage, clientErrorf( + "Syntax error, try CLIENT (LIST | KILL | GETNAME | SETNAME)", + ) case "list": if len(msg.Args) != 2 { return NOMessage, errInvalidNumberOfArguments @@ -114,7 +115,7 @@ func (s *Server) cmdClient(msg *Message, client *Client) (resp.Value, error) { if err != nil { return NOMessage, err } - return resp.StringValue(`{"ok":true,"list":` + string(data) + `,"elapsed":"` + time.Now().Sub(start).String() + "\"}"), nil + return resp.StringValue(`{"ok":true,"list":` + string(data) + `,"elapsed":"` + time.Since(start).String() + "\"}"), nil case RESP: return resp.BytesValue(buf), nil } @@ -131,7 +132,7 @@ func (s *Server) cmdClient(msg *Message, client *Client) (resp.Value, error) { client.mu.Unlock() return resp.StringValue(`{"ok":true,"name":` + jsonString(name) + - `,"elapsed":"` + time.Now().Sub(start).String() + "\"}"), nil + `,"elapsed":"` + time.Since(start).String() + "\"}"), nil case RESP: return resp.StringValue(name), nil } @@ -142,8 +143,9 @@ func (s *Server) cmdClient(msg *Message, client *Client) (resp.Value, error) { name := msg.Args[2] for i := 0; i < len(name); i++ { if name[i] < '!' || name[i] > '~' { - errstr := "Client names cannot contain spaces, newlines or special characters." - return NOMessage, errors.New(errstr) + return NOMessage, clientErrorf( + "Client names cannot contain spaces, newlines or special characters.", + ) } } client.mu.Lock() @@ -151,7 +153,7 @@ func (s *Server) cmdClient(msg *Message, client *Client) (resp.Value, error) { client.mu.Unlock() switch msg.OutputType { case JSON: - return resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}"), nil + return resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}"), nil case RESP: return resp.SimpleStringValue("OK"), nil } @@ -172,7 +174,7 @@ func (s *Server) cmdClient(msg *Message, client *Client) (resp.Value, error) { } switch strings.ToLower(arg) { default: - return NOMessage, errors.New("No such client") + return NOMessage, clientErrorf("No such client") case "addr": i++ if i == len(msg.Args) { @@ -202,13 +204,13 @@ func (s *Server) cmdClient(msg *Message, client *Client) (resp.Value, error) { } s.connsmu.RUnlock() if cclose == nil { - return NOMessage, errors.New("No such client") + return NOMessage, clientErrorf("No such client") } var res resp.Value switch msg.OutputType { case JSON: - res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: res = resp.SimpleStringValue("OK") } @@ -229,32 +231,3 @@ func (s *Server) cmdClient(msg *Message, client *Client) (resp.Value, error) { } return NOMessage, errors.New("invalid output type") } - -/* -func (c *Controller) cmdClientList(msg *Message) (string, error) { - - var ok bool - var key string - if vs, key, ok = tokenval(vs); !ok || key == "" { - return "", errInvalidNumberOfArguments - } - - col := c.getCol(key) - if col == nil { - if msg.OutputType == RESP { - return "+none\r\n", nil - } - return "", errKeyNotFound - } - - typ := "hash" - - switch msg.OutputType { - case JSON: - return `{"ok":true,"type":` + string(typ) + `,"elapsed":"` + time.Now().Sub(start).String() + "\"}", nil - case RESP: - return "+" + typ + "\r\n", nil - } - return "", nil -} -*/ diff --git a/internal/server/config.go b/internal/server/config.go index b1fc0817..7b55fc6d 100644 --- a/internal/server/config.go +++ b/internal/server/config.go @@ -2,7 +2,6 @@ package server import ( "encoding/json" - "fmt" "io/ioutil" "os" "strconv" @@ -241,7 +240,7 @@ func (config *Config) setProperty(name, value string, fromLoad bool) error { var invalid bool switch name { default: - return fmt.Errorf("Unsupported CONFIG parameter: %s", name) + return clientErrorf("Unsupported CONFIG parameter: %s", name) case RequirePass: config._requirePass = value case LeaderAuth: @@ -259,7 +258,7 @@ func (config *Config) setProperty(name, value string, fromLoad bool) error { case MaxMemory: sz, ok := parseMemSize(value) if !ok { - return fmt.Errorf("Invalid argument '%s' for CONFIG SET '%s'", value, name) + return clientErrorf("Invalid argument '%s' for CONFIG SET '%s'", value, name) } config._maxMemory = sz case ProtectedMode: @@ -289,7 +288,7 @@ func (config *Config) setProperty(name, value string, fromLoad bool) error { } if invalid { - return fmt.Errorf("Invalid argument '%s' for CONFIG SET '%s'", value, name) + return clientErrorf("Invalid argument '%s' for CONFIG SET '%s'", value, name) } return nil } @@ -345,7 +344,7 @@ func (s *Server) cmdConfigGet(msg *Message) (res resp.Value, err error) { if err != nil { return NOMessage, err } - res = resp.StringValue(`{"ok":true,"properties":` + string(data) + `,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"properties":` + string(data) + `,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: vals := respValuesSimpleMap(m) res = resp.ArrayValue(vals) @@ -398,18 +397,6 @@ func (config *Config) followPort() int { config.mu.RUnlock() return int(v) } -func (config *Config) followID() string { - config.mu.RLock() - v := config._followID - config.mu.RUnlock() - return v -} -func (config *Config) followPos() int64 { - config.mu.RLock() - v := config._followPos - config.mu.RUnlock() - return v -} func (config *Config) serverID() string { config.mu.RLock() v := config._serverID @@ -468,53 +455,8 @@ func (config *Config) setFollowPort(v int) { config._followPort = int64(v) config.mu.Unlock() } -func (config *Config) setFollowID(v string) { - config.mu.Lock() - config._followID = v - config.mu.Unlock() -} -func (config *Config) setFollowPos(v int64) { - config.mu.Lock() - config._followPos = v - config.mu.Unlock() -} -func (config *Config) setServerID(v string) { - config.mu.Lock() - config._serverID = v - config.mu.Unlock() -} func (config *Config) setReadOnly(v bool) { config.mu.Lock() config._readOnly = v config.mu.Unlock() } -func (config *Config) setRequirePass(v string) { - config.mu.Lock() - config._requirePass = v - config.mu.Unlock() -} -func (config *Config) setLeaderAuth(v string) { - config.mu.Lock() - config._leaderAuth = v - config.mu.Unlock() -} -func (config *Config) setProtectedMode(v string) { - config.mu.Lock() - config._protectedMode = v - config.mu.Unlock() -} -func (config *Config) setMaxMemory(v int) { - config.mu.Lock() - config._maxMemory = int64(v) - config.mu.Unlock() -} -func (config *Config) setAutoGC(v uint64) { - config.mu.Lock() - config._autoGC = v - config.mu.Unlock() -} -func (config *Config) setKeepAlive(v int64) { - config.mu.Lock() - config._keepAlive = v - config.mu.Unlock() -} diff --git a/internal/server/crud.go b/internal/server/crud.go index e7b076d5..16fa38a0 100644 --- a/internal/server/crud.go +++ b/internal/server/crud.go @@ -87,7 +87,7 @@ func (server *Server) cmdBounds(msg *Message) (resp.Value, error) { } switch msg.OutputType { case JSON: - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), nil case RESP: return vals[0], nil @@ -101,7 +101,7 @@ func (server *Server) cmdType(msg *Message) (resp.Value, error) { var ok bool var key string - if vs, key, ok = tokenval(vs); !ok || key == "" { + if _, key, ok = tokenval(vs); !ok || key == "" { return NOMessage, errInvalidNumberOfArguments } @@ -117,7 +117,7 @@ func (server *Server) cmdType(msg *Message) (resp.Value, error) { switch msg.OutputType { case JSON: - return resp.StringValue(`{"ok":true,"type":` + string(typ) + `,"elapsed":"` + time.Now().Sub(start).String() + "\"}"), nil + return resp.StringValue(`{"ok":true,"type":` + string(typ) + `,"elapsed":"` + time.Since(start).String() + "\"}"), nil case RESP: return resp.SimpleStringValue(typ), nil } @@ -269,7 +269,7 @@ func (server *Server) cmdGet(msg *Message) (resp.Value, error) { } switch msg.OutputType { case JSON: - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), nil case RESP: var oval resp.Value @@ -316,7 +316,7 @@ func (server *Server) cmdDel(msg *Message) (res resp.Value, d commandDetails, er d.timestamp = time.Now() switch msg.OutputType { case JSON: - res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: if d.updated { res = resp.IntegerValue(1) @@ -396,7 +396,7 @@ func (server *Server) cmdPdel(msg *Message) (res resp.Value, d commandDetails, e d.parent = true switch msg.OutputType { case JSON: - res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: total := len(d.children) - expired if total < 0 { @@ -432,7 +432,7 @@ func (server *Server) cmdDrop(msg *Message) (res resp.Value, d commandDetails, e server.clearKeyExpires(d.key) switch msg.OutputType { case JSON: - res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: if d.updated { res = resp.IntegerValue(1) @@ -489,7 +489,7 @@ func (server *Server) cmdRename(msg *Message, nx bool) (res resp.Value, d comman d.timestamp = time.Now() switch msg.OutputType { case JSON: - res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: if !nx { res = resp.SimpleStringValue("OK") @@ -520,7 +520,7 @@ func (server *Server) cmdFlushDB(msg *Message) (res resp.Value, d commandDetails d.timestamp = time.Now() switch msg.OutputType { case JSON: - res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: res = resp.SimpleStringValue("OK") } @@ -798,7 +798,7 @@ func (server *Server) cmdSet(msg *Message, resetExpires bool) (res resp.Value, d switch msg.OutputType { default: case JSON: - res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: res = resp.SimpleStringValue("OK") } @@ -899,7 +899,7 @@ func (server *Server) cmdFset(msg *Message) (res resp.Value, d commandDetails, e switch msg.OutputType { case JSON: - res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: res = resp.IntegerValue(updateCount) } @@ -946,7 +946,7 @@ func (server *Server) cmdExpire(msg *Message) (res resp.Value, d commandDetails, switch msg.OutputType { case JSON: if ok { - res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") } else { return resp.SimpleStringValue(""), d, errIDNotFound } @@ -998,7 +998,7 @@ func (server *Server) cmdPersist(msg *Message) (res resp.Value, d commandDetails d.timestamp = time.Now() switch msg.OutputType { case JSON: - res = resp.SimpleStringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.SimpleStringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: if cleared { res = resp.IntegerValue(1) @@ -1040,7 +1040,7 @@ func (server *Server) cmdTTL(msg *Message) (res resp.Value, err error) { if time.Now().After(at) { ok2 = false } else { - v = float64(at.Sub(time.Now())) / float64(time.Second) + v = float64(time.Until(at)) / float64(time.Second) if v < 0 { v = 0 } @@ -1058,7 +1058,7 @@ func (server *Server) cmdTTL(msg *Message) (res resp.Value, err error) { ttl = "-1" } res = resp.SimpleStringValue( - `{"ok":true,"ttl":` + ttl + `,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + `{"ok":true,"ttl":` + ttl + `,"elapsed":"` + time.Since(start).String() + "\"}") } else { return resp.SimpleStringValue(""), errIDNotFound } diff --git a/internal/server/dev.go b/internal/server/dev.go index 641df9dc..8b73d0cb 100644 --- a/internal/server/dev.go +++ b/internal/server/dev.go @@ -78,8 +78,7 @@ func (s *Server) cmdMassInsert(msg *Message) (res resp.Value, err error) { docmd := func(args []string) error { s.mu.Lock() defer s.mu.Unlock() - var nmsg Message - nmsg = *msg + nmsg := *msg nmsg._command = "" nmsg.Args = args _, d, err := s.command(&nmsg, nil) diff --git a/internal/server/follow.go b/internal/server/follow.go index 0ac1df12..7d9f0b16 100644 --- a/internal/server/follow.go +++ b/internal/server/follow.go @@ -107,7 +107,7 @@ func (s *Server) cmdReplConf(msg *Message, client *Client) (res resp.Value, err if vs, cmd, ok = tokenval(vs); !ok || cmd == "" { return NOMessage, errInvalidNumberOfArguments } - if vs, val, ok = tokenval(vs); !ok || val == "" { + if _, val, ok = tokenval(vs); !ok || val == "" { return NOMessage, errInvalidNumberOfArguments } diff --git a/internal/server/hooks.go b/internal/server/hooks.go index 9153e3b2..bfbbbf8f 100644 --- a/internal/server/hooks.go +++ b/internal/server/hooks.go @@ -109,7 +109,9 @@ func (s *Server) cmdSetHook(msg *Message, chanCmd bool) ( break } args, err := s.cmdSearchArgs(true, cmdlc, vs, types) - defer args.Close() + if args.usingLua() { + defer args.Close() + } if err != nil { return NOMessage, d, err } @@ -252,7 +254,7 @@ func (s *Server) cmdDelHook(msg *Message, chanCmd bool) ( delete(s.hooks, hook.Name) delete(s.hooksOut, hook.Name) // remove hook from spatial index - if hook != nil && hook.Fence != nil && hook.Fence.obj != nil { + if hook.Fence != nil && hook.Fence.obj != nil { rect := hook.Fence.obj.Rect() s.hookTree.Delete( [2]float64{rect.Min.X, rect.Min.Y}, @@ -310,7 +312,7 @@ func (s *Server) cmdPDelHook(msg *Message, channel bool) ( delete(s.hooks, hook.Name) delete(s.hooksOut, hook.Name) // remove hook from spatial index - if hook != nil && hook.Fence != nil && hook.Fence.obj != nil { + if hook.Fence != nil && hook.Fence.obj != nil { rect := hook.Fence.obj.Rect() s.hookTree.Delete( [2]float64{rect.Min.X, rect.Min.Y}, @@ -439,7 +441,7 @@ func (s *Server) cmdHooks(msg *Message, channel bool) ( buf.WriteString(`}}`) } buf.WriteString(`],"elapsed":"` + - time.Now().Sub(start).String() + "\"}") + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), nil case RESP: var vals []resp.Value diff --git a/internal/server/json.go b/internal/server/json.go index be1d4c8c..7ccc9526 100644 --- a/internal/server/json.go +++ b/internal/server/json.go @@ -222,7 +222,7 @@ func (s *Server) cmdJget(msg *Message) (resp.Value, error) { if res.Exists() { buf.WriteString(`,"value":` + jsonString(val)) } - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), nil case RESP: if !res.Exists() { @@ -311,7 +311,7 @@ func (s *Server) cmdJset(msg *Message) (res resp.Value, d commandDetails, err er case JSON: var buf bytes.Buffer buf.WriteString(`{"ok":true`) - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), d, nil case RESP: return resp.SimpleStringValue("OK"), d, nil @@ -377,7 +377,7 @@ func (s *Server) cmdJdel(msg *Message) (res resp.Value, d commandDetails, err er case JSON: var buf bytes.Buffer buf.WriteString(`{"ok":true`) - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), d, nil case RESP: return resp.IntegerValue(1), d, nil diff --git a/internal/server/keys.go b/internal/server/keys.go index 5b3bb99c..bcdb4721 100644 --- a/internal/server/keys.go +++ b/internal/server/keys.go @@ -88,7 +88,7 @@ func (s *Server) cmdKeys(msg *Message) (res resp.Value, err error) { s.cols.Ascend(nil, iterator) } if msg.OutputType == JSON { - wr.WriteString(`],"elapsed":"` + time.Now().Sub(start).String() + "\"}") + wr.WriteString(`],"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(wr.String()), nil } return resp.ArrayValue(vals), nil diff --git a/internal/server/monitor.go b/internal/server/monitor.go index ba24e8a5..8281d182 100644 --- a/internal/server/monitor.go +++ b/internal/server/monitor.go @@ -39,24 +39,22 @@ func (s *Server) liveMonitor(conn net.Conn, rd *PipelineReader, msg *Message) er s.monconnsMu.Lock() conn.Write([]byte("+OK\r\n")) s.monconnsMu.Unlock() - for { - msgs, err := rd.ReadMessages() - if err != nil { - if err == io.EOF { - return nil - } - return err + msgs, err := rd.ReadMessages() + if err != nil { + if err == io.EOF { + return nil } - for _, msg := range msgs { - if len(msg.Args) == 1 && strings.ToLower(msg.Args[0]) == "quit" { - s.monconnsMu.Lock() - conn.Write([]byte("+OK\r\n")) - s.monconnsMu.Unlock() - return nil - } - } - return nil + return err } + for _, msg := range msgs { + if len(msg.Args) == 1 && strings.ToLower(msg.Args[0]) == "quit" { + s.monconnsMu.Lock() + conn.Write([]byte("+OK\r\n")) + s.monconnsMu.Unlock() + return nil + } + } + return nil } // send messages to live MONITOR clients diff --git a/internal/server/output.go b/internal/server/output.go index 8d9535a1..65824ada 100644 --- a/internal/server/output.go +++ b/internal/server/output.go @@ -34,7 +34,7 @@ func (s *Server) cmdOutput(msg *Message) (res resp.Value, err error) { default: return NOMessage, nil case JSON: - return resp.StringValue(`{"ok":true,"output":"json","elapsed":` + time.Now().Sub(start).String() + `}`), nil + return resp.StringValue(`{"ok":true,"output":"json","elapsed":` + time.Since(start).String() + `}`), nil case RESP: return resp.StringValue("resp"), nil } diff --git a/internal/server/pubsub.go b/internal/server/pubsub.go index d2dec448..0a22831f 100644 --- a/internal/server/pubsub.go +++ b/internal/server/pubsub.go @@ -166,7 +166,7 @@ func (s *Server) cmdPublish(msg *Message) (resp.Value, error) { case JSON: res = resp.StringValue(`{"ok":true` + `,"published":` + strconv.FormatInt(int64(n), 10) + - `,"elapsed":"` + time.Now().Sub(start).String() + `"}`) + `,"elapsed":"` + time.Since(start).String() + `"}`) case RESP: res = resp.IntegerValue(n) } @@ -200,7 +200,7 @@ func (s *Server) liveSubscription( switch outputType { case JSON: write([]byte(`{"ok":true` + - `,"elapsed":"` + time.Now().Sub(start).String() + `"}`)) + `,"elapsed":"` + time.Since(start).String() + `"}`)) case RESP: write([]byte("+OK\r\n")) } @@ -209,7 +209,7 @@ func (s *Server) liveSubscription( switch outputType { case JSON: write([]byte(`{"ok":false,"err":"invalid number of arguments"` + - `,"elapsed":"` + time.Now().Sub(start).String() + `"}`)) + `,"elapsed":"` + time.Since(start).String() + `"}`)) case RESP: write([]byte("-ERR wrong number of arguments " + "for '" + command + "' command\r\n")) @@ -221,7 +221,7 @@ func (s *Server) liveSubscription( write([]byte(`{"ok":false` + `,"err":"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / ` + `PING / QUIT allowed in this context"` + - `,"elapsed":"` + time.Now().Sub(start).String() + `"}`)) + `,"elapsed":"` + time.Since(start).String() + `"}`)) case RESP: write([]byte("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / " + "PING / QUIT allowed in this context\r\n")) @@ -234,7 +234,7 @@ func (s *Server) liveSubscription( `,"command":` + jsonString(command) + `,"channel":` + jsonString(channel) + `,"num":` + strconv.FormatInt(int64(num), 10) + - `,"elapsed":"` + time.Now().Sub(start).String() + `"}`)) + `,"elapsed":"` + time.Since(start).String() + `"}`)) case RESP: b := redcon.AppendArray(nil, 3) b = redcon.AppendBulkString(b, command) diff --git a/internal/server/scan.go b/internal/server/scan.go index 5ae78cd4..ad595a12 100644 --- a/internal/server/scan.go +++ b/internal/server/scan.go @@ -58,7 +58,7 @@ func (s *Server) cmdScan(msg *Message) (res resp.Value, err error) { sw.writeHead() if sw.col != nil { if sw.output == outputCount && len(sw.wheres) == 0 && - len(sw.whereins) == 0 && sw.globEverything == true { + len(sw.whereins) == 0 && sw.globEverything { count := sw.col.Count() - int(args.cursor) if count < 0 { count = 0 @@ -93,7 +93,7 @@ func (s *Server) cmdScan(msg *Message) (res resp.Value, err error) { } sw.writeFoot() if msg.OutputType == JSON { - wr.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + wr.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.BytesValue(wr.Bytes()), nil } return sw.respOut, nil diff --git a/internal/server/scripts.go b/internal/server/scripts.go index b0bccd5a..053bb40c 100644 --- a/internal/server/scripts.go +++ b/internal/server/scripts.go @@ -482,7 +482,7 @@ func (s *Server) cmdEvalUnified(scriptIsSha bool, msg *Message) (res resp.Value, var buf bytes.Buffer buf.WriteString(`{"ok":true`) buf.WriteString(`,"result":` + ConvertToJSON(ret)) - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), nil case RESP: return ConvertToRESP(ret), nil @@ -496,7 +496,7 @@ func (s *Server) cmdScriptLoad(msg *Message) (resp.Value, error) { var ok bool var script string - if vs, script, ok = tokenval(vs); !ok || script == "" { + if _, script, ok = tokenval(vs); !ok || script == "" { return NOMessage, errInvalidNumberOfArguments } @@ -519,7 +519,7 @@ func (s *Server) cmdScriptLoad(msg *Message) (resp.Value, error) { var buf bytes.Buffer buf.WriteString(`{"ok":true`) buf.WriteString(`,"result":"` + shaSum + `"`) - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), nil case RESP: return resp.StringValue(shaSum), nil @@ -557,7 +557,7 @@ func (s *Server) cmdScriptExists(msg *Message) (resp.Value, error) { resArray = append(resArray, fmt.Sprintf("%d", ires)) } buf.WriteString(`,"result":[` + strings.Join(resArray, ",") + `]`) - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), nil case RESP: var resArray []resp.Value @@ -577,7 +577,7 @@ func (s *Server) cmdScriptFlush(msg *Message) (resp.Value, error) { case JSON: var buf bytes.Buffer buf.WriteString(`{"ok":true`) - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), nil case RESP: return resp.StringValue("OK"), nil diff --git a/internal/server/search.go b/internal/server/search.go index 207b2f8a..f5126cd3 100644 --- a/internal/server/search.go +++ b/internal/server/search.go @@ -393,7 +393,7 @@ func (server *Server) cmdNearby(msg *Message) (res resp.Value, err error) { } sw.writeFoot() if msg.OutputType == JSON { - wr.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + wr.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.BytesValue(wr.Bytes()), nil } return sw.respOut, nil @@ -521,7 +521,7 @@ func (server *Server) cmdWithinOrIntersects(cmd string, msg *Message) (res resp. } sw.writeFoot() if msg.OutputType == JSON { - wr.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + wr.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.BytesValue(wr.Bytes()), nil } return sw.respOut, nil @@ -573,7 +573,7 @@ func (server *Server) cmdSearch(msg *Message) (res resp.Value, err error) { } sw.writeHead() if sw.col != nil { - if sw.output == outputCount && len(sw.wheres) == 0 && sw.globEverything == true { + if sw.output == outputCount && len(sw.wheres) == 0 && sw.globEverything { count := sw.col.Count() - int(s.cursor) if count < 0 { count = 0 @@ -612,7 +612,7 @@ func (server *Server) cmdSearch(msg *Message) (res resp.Value, err error) { } sw.writeFoot() if msg.OutputType == JSON { - wr.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + wr.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.BytesValue(wr.Bytes()), nil } return sw.respOut, nil diff --git a/internal/server/server.go b/internal/server/server.go index e6b28a22..651c950e 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -261,7 +261,7 @@ func Serve(host string, port int, dir string, http bool) error { if err := server.migrateAOF(); err != nil { return err } - if core.AppendOnly == true { + if core.AppendOnly { f, err := os.OpenFile(core.AppendFileName, os.O_CREATE|os.O_RDWR, 0600) if err != nil { return err @@ -567,7 +567,7 @@ func (server *Server) watchAutoGC() { if autoGC == 0 { continue } - if time.Now().Sub(s) < time.Second*time.Duration(autoGC) { + if time.Since(s) < time.Second*time.Duration(autoGC) { continue } var mem1, mem2 runtime.MemStats @@ -767,9 +767,9 @@ func (server *Server) handleInputCommand(client *Client, msg *Message) error { switch msg.OutputType { case JSON: if len(msg.Args) > 1 { - return writeOutput(`{"ok":true,"` + msg.Command() + `":` + jsonString(msg.Args[1]) + `,"elapsed":"` + time.Now().Sub(start).String() + `"}`) + return writeOutput(`{"ok":true,"` + msg.Command() + `":` + jsonString(msg.Args[1]) + `,"elapsed":"` + time.Since(start).String() + `"}`) } - return writeOutput(`{"ok":true,"` + msg.Command() + `":"pong","elapsed":"` + time.Now().Sub(start).String() + `"}`) + return writeOutput(`{"ok":true,"` + msg.Command() + `":"pong","elapsed":"` + time.Since(start).String() + `"}`) case RESP: if len(msg.Args) > 1 { data := redcon.AppendBulkString(nil, msg.Args[1]) @@ -784,7 +784,7 @@ func (server *Server) handleInputCommand(client *Client, msg *Message) error { writeErr := func(errMsg string) error { switch msg.OutputType { case JSON: - return writeOutput(`{"ok":false,"err":` + jsonString(errMsg) + `,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + return writeOutput(`{"ok":false,"err":` + jsonString(errMsg) + `,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: if errMsg == errInvalidNumberOfArguments.Error() { return writeOutput("-ERR wrong number of arguments for '" + msg.Command() + "' command\r\n") @@ -1148,19 +1148,6 @@ password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside. `), "\n", " ", -1) + "\r\n") -// SetKeepAlive sets the connection keepalive -func setKeepAlive(conn net.Conn, period time.Duration) error { - if tcp, ok := conn.(*net.TCPConn); ok { - if err := tcp.SetKeepAlive(true); err != nil { - return err - } - return tcp.SetKeepAlivePeriod(period) - } - return nil -} - -var errCloseHTTP = errors.New("close http") - // WriteWebSocketMessage write a websocket message to an io.Writer. func WriteWebSocketMessage(w io.Writer, data []byte) error { var msg []byte @@ -1189,7 +1176,7 @@ func WriteWebSocketMessage(w io.Writer, data []byte) error { func OKMessage(msg *Message, start time.Time) resp.Value { switch msg.OutputType { case JSON: - return resp.StringValue(`{"ok":true,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + return resp.StringValue(`{"ok":true,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: return resp.SimpleStringValue("OK") } @@ -1513,3 +1500,11 @@ func (is *InputStream) End(data []byte) { is.b = is.b[:0] } } + +// clientErrorf is the same as fmt.Errorf, but is intented for errors that are +// sent back to the client. This allows for the Go static checker to ignore +// throwing warning for certain error strings. +// https://staticcheck.io/docs/checks#ST1005 +func clientErrorf(format string, args ...interface{}) error { + return fmt.Errorf(format, args...) +} diff --git a/internal/server/stats.go b/internal/server/stats.go index 90ede9c3..0910b1b5 100644 --- a/internal/server/stats.go +++ b/internal/server/stats.go @@ -87,7 +87,7 @@ func (s *Server) cmdStats(msg *Message) (res resp.Value, err error) { if err != nil { return NOMessage, err } - res = resp.StringValue(`{"ok":true,"stats":` + string(data) + `,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"stats":` + string(data) + `,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: res = resp.ArrayValue(vals) } @@ -368,7 +368,7 @@ func (s *Server) writeInfoPersistence(w *bytes.Buffer) { if currentShrinkStart.IsZero() { fmt.Fprintf(w, "aof_current_rewrite_time_sec:0\r\n") // Duration of the on-going AOF rewrite operation if any } else { - fmt.Fprintf(w, "aof_current_rewrite_time_sec:%d\r\n", time.Now().Sub(currentShrinkStart)/time.Second) // Duration of the on-going AOF rewrite operation if any + fmt.Fprintf(w, "aof_current_rewrite_time_sec:%d\r\n", time.Since(currentShrinkStart)/time.Second) // Duration of the on-going AOF rewrite operation if any } } @@ -477,7 +477,7 @@ func (s *Server) cmdInfo(msg *Message) (res resp.Value, err error) { if err != nil { return NOMessage, err } - res = resp.StringValue(`{"ok":true,"info":` + string(data) + `,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + res = resp.StringValue(`{"ok":true,"info":` + string(data) + `,"elapsed":"` + time.Since(start).String() + "\"}") case RESP: res = resp.BytesValue(w.Bytes()) } @@ -514,28 +514,3 @@ func respValuesSimpleMap(m map[string]interface{}) []resp.Value { } return vals } - -func (s *Server) statsCollections(line string) (string, error) { - start := time.Now() - var key string - var ms = []map[string]interface{}{} - for len(line) > 0 { - line, key = token(line) - col := s.getCol(key) - if col != nil { - m := make(map[string]interface{}) - points := col.PointCount() - m["num_points"] = points - m["in_memory_size"] = col.TotalWeight() - m["num_objects"] = col.Count() - ms = append(ms, m) - } else { - ms = append(ms, nil) - } - } - data, err := json.Marshal(ms) - if err != nil { - return "", err - } - return `{"ok":true,"stats":` + string(data) + `,"elapsed":"` + time.Now().Sub(start).String() + "\"}", nil -} diff --git a/internal/server/test.go b/internal/server/test.go index b5f302ca..21c98869 100644 --- a/internal/server/test.go +++ b/internal/server/test.go @@ -269,6 +269,7 @@ func (s *Server) cmdTest(msg *Message) (res resp.Value, err error) { } if len(vs) != 0 { err = errInvalidNumberOfArguments + return } var result int @@ -296,7 +297,7 @@ func (s *Server) cmdTest(msg *Message) (res resp.Value, err error) { if clipped != nil { buf.WriteString(`,"object":` + clipped.JSON()) } - buf.WriteString(`,"elapsed":"` + time.Now().Sub(start).String() + "\"}") + buf.WriteString(`,"elapsed":"` + time.Since(start).String() + "\"}") return resp.StringValue(buf.String()), nil case RESP: if clipped != nil { diff --git a/internal/server/token.go b/internal/server/token.go index c12865c3..b010dc4c 100644 --- a/internal/server/token.go +++ b/internal/server/token.go @@ -52,35 +52,6 @@ func tokenvalbytes(vs []string) (nvs []string, token []byte, ok bool) { return } -func tokenlc(line string) (newLine, token string) { - for i := 0; i < len(line); i++ { - ch := line[i] - if ch == ' ' { - return line[i+1:], line[:i] - } - if ch >= 'A' && ch <= 'Z' { - lc := make([]byte, 0, 16) - if i > 0 { - lc = append(lc, []byte(line[:i])...) - } - lc = append(lc, ch+32) - i++ - for ; i < len(line); i++ { - ch = line[i] - if ch == ' ' { - return line[i+1:], string(lc) - } - if ch >= 'A' && ch <= 'Z' { - lc = append(lc, ch+32) - } else { - lc = append(lc, ch) - } - } - return "", string(lc) - } - } - return "", line -} func lcb(s1 []byte, s2 string) bool { if len(s1) != len(s2) { return false @@ -144,19 +115,6 @@ func (where whereT) match(value float64) bool { return true } -func zMinMaxFromWheres(wheres []whereT) (minZ, maxZ float64) { - for _, w := range wheres { - if w.field == "z" { - minZ = w.min - maxZ = w.max - return - } - } - minZ = math.Inf(-1) - maxZ = math.Inf(+1) - return -} - type whereinT struct { field string valMap map[float64]struct{} @@ -230,7 +188,6 @@ type searchScanBaseTokens struct { cursor uint64 output outputT precision uint64 - lineout string fence bool distance bool nodwell bool diff --git a/vendor/golang.org/x/crypto/ssh/terminal/terminal.go b/vendor/golang.org/x/crypto/ssh/terminal/terminal.go deleted file mode 100644 index a4d1919a..00000000 --- a/vendor/golang.org/x/crypto/ssh/terminal/terminal.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package terminal provides support functions for dealing with terminals, as -// commonly found on UNIX systems. -// -// Deprecated: this package moved to golang.org/x/term. -package terminal - -import ( - "io" - - "golang.org/x/term" -) - -// EscapeCodes contains escape sequences that can be written to the terminal in -// order to achieve different styles of text. -type EscapeCodes = term.EscapeCodes - -// Terminal contains the state for running a VT100 terminal that is capable of -// reading lines of input. -type Terminal = term.Terminal - -// NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is -// a local terminal, that terminal must first have been put into raw mode. -// prompt is a string that is written at the start of each input line (i.e. -// "> "). -func NewTerminal(c io.ReadWriter, prompt string) *Terminal { - return term.NewTerminal(c, prompt) -} - -// ErrPasteIndicator may be returned from ReadLine as the error, in addition -// to valid line data. It indicates that bracketed paste mode is enabled and -// that the returned line consists only of pasted data. Programs may wish to -// interpret pasted data more literally than typed data. -var ErrPasteIndicator = term.ErrPasteIndicator - -// State contains the state of a terminal. -type State = term.State - -// IsTerminal returns whether the given file descriptor is a terminal. -func IsTerminal(fd int) bool { - return term.IsTerminal(fd) -} - -// ReadPassword reads a line of input from a terminal without local echo. This -// is commonly used for inputting passwords and other sensitive data. The slice -// returned does not include the \n. -func ReadPassword(fd int) ([]byte, error) { - return term.ReadPassword(fd) -} - -// MakeRaw puts the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd int) (*State, error) { - return term.MakeRaw(fd) -} - -// Restore restores the terminal connected to the given file descriptor to a -// previous state. -func Restore(fd int, oldState *State) error { - return term.Restore(fd, oldState) -} - -// GetState returns the current state of a terminal which may be useful to -// restore the terminal after a signal. -func GetState(fd int) (*State, error) { - return term.GetState(fd) -} - -// GetSize returns the dimensions of the given terminal. -func GetSize(fd int) (width, height int, err error) { - return term.GetSize(fd) -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 284d1fb7..d0dbd581 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -205,6 +205,7 @@ github.com/yuin/gopher-lua github.com/yuin/gopher-lua/ast github.com/yuin/gopher-lua/parse github.com/yuin/gopher-lua/pm +<<<<<<< HEAD # go.opencensus.io v0.22.3 go.opencensus.io go.opencensus.io/internal @@ -223,10 +224,14 @@ go.opencensus.io/trace/propagation go.opencensus.io/trace/tracestate # golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad ## explicit +======= +# golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a +>>>>>>> 6b08f7fa (Code cleanup) golang.org/x/crypto/ed25519 golang.org/x/crypto/ed25519/internal/edwards25519 golang.org/x/crypto/md4 golang.org/x/crypto/pbkdf2 +<<<<<<< HEAD golang.org/x/crypto/ssh/terminal # golang.org/x/lint v0.0.0-20200302205851-738671d3881b golang.org/x/lint @@ -234,6 +239,8 @@ golang.org/x/lint/golint # golang.org/x/mod v0.2.0 golang.org/x/mod/module golang.org/x/mod/semver +======= +>>>>>>> 6b08f7fa (Code cleanup) # golang.org/x/net v0.0.0-20210119194325-5f4716e94777 ## explicit golang.org/x/net/context @@ -261,6 +268,7 @@ golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows # golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 +## explicit golang.org/x/term # golang.org/x/text v0.3.3 golang.org/x/text/secure/bidirule