forked from joomcode/redispipe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
76 lines (67 loc) · 2.11 KB
/
request.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package redis
import "fmt"
// Req - convenient wrapper to create Request.
func Req(cmd string, args ...interface{}) Request {
return Request{cmd, args}
}
// Request represents request to be passed to redis.
type Request struct {
// Cmd is a redis command to be sent.
// It could contain single space, then it will be split, and last part will be serialized as an argument.
Cmd string
Args []interface{}
}
func (r Request) String() string {
args := r.Args
if len(args) > 5 {
args = args[:5]
}
argss := make([]string, 0, 1+len(args))
for _, arg := range args {
argStr := fmt.Sprintf("%v", arg)
if len(argStr) > 32 {
argStr = argStr[:32] + "..."
}
argss = append(argss, argStr)
}
if len(r.Args) > 5 {
argss = append(argss, "...")
}
return fmt.Sprintf("Req(%q, %q)", r.Cmd, argss)
}
// Key returns first field of request that should be used as a key for redis cluster.
func (r Request) Key() (string, bool) {
if r.Cmd == "RANDOMKEY" {
return "RANDOMKEY", false
}
var n int
switch r.Cmd {
case "EVAL", "EVALSHA":
n = 2
case "BITOP":
n = 1
default:
n = 0
}
if len(r.Args) <= n {
return "", false
}
return ArgToString(r.Args[n])
}
// Future is interface accepted by Sender to signal request completion.
type Future interface {
// Resolve is called by sender to pass result (or error) for particular request.
// Single future could be used for accepting multiple results.
// n argument is used then to distinguish request this result is for.
Resolve(res interface{}, n uint64)
// Cancelled method could inform sender that request is abandoned.
// It is called usually before sending request, and if Cancelled returns non-nil error,
// then Sender calls Resolve with ErrRequestCancelled error wrapped around returned error.
Cancelled() error
}
// FuncFuture simple wrapper that makes Future from function.
type FuncFuture func(res interface{}, n uint64)
// Cancelled implements Future.Cancelled (always false)
func (f FuncFuture) Cancelled() error { return nil }
// Resolve implements Future.Resolve (by calling wrapped function).
func (f FuncFuture) Resolve(res interface{}, n uint64) { f(res, n) }