/
dummy.go
99 lines (80 loc) · 2 KB
/
dummy.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package benchclient
import (
"context"
"fmt"
"math/rand"
"strings"
"time"
infinistore "github.com/ds2-lab/infinistore/client"
"github.com/zhangjyr/hashmap"
)
const (
DummyStore = "ds"
DummyCache = "dc"
DummyCacheMissRatio = 50 // Miss ratio of cache, 10 means 10%
)
var (
sizemap *hashmap.HashMap
)
func ResetDummySizeRegistry() {
sizemap = hashmap.New(10000)
}
type Dummy struct {
*defaultClient
ctx context.Context
bandwidth int64
}
// NewDummy returns a new dummy client.
// bandwidth defined the bandwidth of the dummy client in B/s, 0 for unlimited.
func NewDummy(bandwidth int64, t string) *Dummy {
//client := newSession(addr)
client := &Dummy{
defaultClient: newDefaultClient(fmt.Sprintf("Dummy%s: ", strings.ToUpper(t))),
ctx: context.Background(),
bandwidth: bandwidth,
}
client.setter = client.set
client.getter = client.get
client.abbr = t
return client
}
func (d *Dummy) set(key string, val []byte) (err error) {
sizemap.Set(key, len(val))
if d.bandwidth == 0 {
return nil
}
time.Sleep(d.sizeToDuration(len(val)))
return nil
}
func (d *Dummy) get(key string) (infinistore.ReadAllCloser, error) {
size, ok := sizemap.Get(key)
if !ok {
return nil, infinistore.ErrNotFound
}
if d.abbr == DummyCache && rand.Intn(100) < DummyCacheMissRatio {
return nil, infinistore.ErrNotFound
}
if d.bandwidth == 0 {
return &DummyReadAllCloser{size: size.(int)}, nil
}
time.Sleep(d.sizeToDuration(size.(int)))
return &DummyReadAllCloser{size: size.(int)}, nil
}
func (d *Dummy) sizeToDuration(size int) time.Duration {
return time.Duration(float64(size) / float64(d.bandwidth) * float64(time.Second))
}
type DummyReadAllCloser struct {
size int
}
func (r *DummyReadAllCloser) Len() int {
return r.size
}
func (r *DummyReadAllCloser) Read(p []byte) (n int, err error) {
return n, ErrNotSupported
}
func (r *DummyReadAllCloser) ReadAll() ([]byte, error) {
return nil, ErrNotSupported
}
func (r *DummyReadAllCloser) Close() error {
return nil
}