forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block_ops_constrained.go
48 lines (41 loc) · 1.09 KB
/
block_ops_constrained.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
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"sync"
"time"
"golang.org/x/net/context"
)
// BlockOpsConstrained implements the BlockOps interface by relaying
// requests to a delegate BlockOps, but it delays all Puts by
// simulating a bottleneck of the given bandwidth.
type BlockOpsConstrained struct {
BlockOps
bwKBps int
lock sync.Mutex
}
var _ BlockOps = (*BlockOpsConstrained)(nil)
// NewBlockOpsConstrained constructs a new BlockOpsConstrained.
func NewBlockOpsConstrained(delegate BlockOps, bwKBps int) *BlockOpsConstrained {
return &BlockOpsConstrained{
BlockOps: delegate,
bwKBps: bwKBps,
}
}
func (b *BlockOpsConstrained) delay(ctx context.Context, size int) error {
if b.bwKBps <= 0 {
return nil
}
b.lock.Lock()
defer b.lock.Unlock()
// Simulate a constrained bserver connection
delay := size * int(time.Second) / (b.bwKBps * 1024)
time.Sleep(time.Duration(delay))
select {
case <-ctx.Done():
return ctx.Err()
default:
}
return nil
}