2019-09-19 04:34:19 +01:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package rpc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/zeebo/errs"
|
|
|
|
"gopkg.in/spacemonkeygo/monkit.v2"
|
|
|
|
|
2019-11-14 19:46:15 +00:00
|
|
|
"storj.io/storj/private/memory"
|
2019-09-19 04:34:19 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
//go:generate go run gen.go ../pb drpc compat_drpc.go
|
|
|
|
//go:generate go run gen.go ../pb grpc compat_grpc.go
|
|
|
|
|
|
|
|
var mon = monkit.Package()
|
|
|
|
|
|
|
|
// Error wraps all of the errors returned by this package.
|
|
|
|
var Error = errs.Class("rpccompat")
|
|
|
|
|
|
|
|
// timedConn wraps a net.Conn so that all reads and writes get the specified timeout and
|
|
|
|
// return bytes no faster than the rate. If the timeout or rate are zero, they are
|
|
|
|
// ignored.
|
|
|
|
type timedConn struct {
|
|
|
|
net.Conn
|
2019-10-23 00:57:24 +01:00
|
|
|
rate memory.Size
|
2019-09-19 04:34:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// now returns time.Now if there's a nonzero rate.
|
|
|
|
func (t *timedConn) now() (now time.Time) {
|
|
|
|
if t.rate > 0 {
|
|
|
|
now = time.Now()
|
|
|
|
}
|
|
|
|
return now
|
|
|
|
}
|
|
|
|
|
|
|
|
// delay ensures that we sleep to keep the rate if it is nonzero. n is the number of
|
|
|
|
// bytes in the read or write operation we need to delay.
|
|
|
|
func (t *timedConn) delay(start time.Time, n int) {
|
|
|
|
if t.rate > 0 {
|
|
|
|
expected := time.Duration(n * int(time.Second) / t.rate.Int())
|
|
|
|
if actual := time.Since(start); expected > actual {
|
|
|
|
time.Sleep(expected - actual)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-23 00:57:24 +01:00
|
|
|
// Read wraps the connection read and adds sleeping to ensure the rate.
|
2019-09-19 04:34:19 +01:00
|
|
|
func (t *timedConn) Read(p []byte) (int, error) {
|
|
|
|
start := t.now()
|
|
|
|
n, err := t.Conn.Read(p)
|
|
|
|
t.delay(start, n)
|
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
|
2019-10-23 00:57:24 +01:00
|
|
|
// Write wraps the connection write and adds sleeping to ensure the rate.
|
2019-09-19 04:34:19 +01:00
|
|
|
func (t *timedConn) Write(p []byte) (int, error) {
|
|
|
|
start := t.now()
|
|
|
|
n, err := t.Conn.Write(p)
|
|
|
|
t.delay(start, n)
|
|
|
|
return n, err
|
|
|
|
}
|