-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbuffered.go
126 lines (104 loc) · 2.47 KB
/
buffered.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package snowflake
import (
"context"
"fmt"
"math/rand"
"os"
"sync"
"time"
)
const (
defaultRequestSize = 512
)
// BufferedClient implements a client that internally buffers ids for performance purposes
type BufferedClient struct {
client Client
ch chan int64
ctx context.Context
cancel func()
wg *sync.WaitGroup
bufferSize int
workers int
}
func (c *BufferedClient) Id() int64 {
return <-c.ch
}
func (c *BufferedClient) spawnN(n int) {
c.wg.Add(n)
for i := 0; i < n; i++ {
go c.spawn()
}
}
func (c *BufferedClient) spawn() {
defer c.wg.Done()
requestSize := defaultRequestSize
if requestSize > c.bufferSize {
requestSize = c.bufferSize
}
for {
ctx, _ := context.WithTimeout(context.Background(), time.Second*3)
ids, err := c.client.IntN(ctx, requestSize)
if err != nil {
select {
case <-c.ctx.Done():
return
default:
}
// if there was a problem, hang out for a little bit before trying again
fmt.Fprintln(os.Stderr, err)
time.Sleep(250*time.Millisecond + time.Duration(rand.Intn(100))*time.Millisecond)
continue
}
for _, id := range ids {
select {
case c.ch <- id:
case <-c.ctx.Done():
return
}
}
}
}
func (c *BufferedClient) Close() {
c.cancel()
c.wg.Wait()
}
func NewBufferedClient(c Client, opts ...BufferedClientOption) *BufferedClient {
ctx, cancel := context.WithCancel(context.Background())
bc := &BufferedClient{
ctx: ctx,
cancel: cancel,
client: c,
wg: &sync.WaitGroup{},
bufferSize: 4096,
workers: 8,
}
for _, opt := range opts {
opt(bc)
}
bc.ch = make(chan int64, bc.bufferSize)
bc.spawnN(bc.workers)
return bc
}
// BufferedClientOption defines options to the NewBufferedClient variable
type BufferedClientOption func(client *BufferedClient)
// WithBufferSize specifies the number of ids that may be buffered locally; beware, the larger you make this, the longer
// the startup will take
func WithBufferSize(n int) BufferedClientOption {
max := 65384
return func(client *BufferedClient) {
if n < 1 || n > max {
panic(fmt.Sprintf("WithBufferSize must be between 1 and %v", max))
}
client.bufferSize = n
}
}
// WithWorkers specifies the number of concurrent goroutines that will be fetching ids
func WithWorkers(n int) BufferedClientOption {
max := 100
return func(client *BufferedClient) {
if n < 1 || n > max {
panic(fmt.Sprintf("WithBufferSize must be between 1 and %v", max))
}
client.workers = n
}
}