Cloak/internal/multiplex/qos.go

55 lines
1.6 KiB
Go
Raw Normal View History

2018-11-07 21:16:13 +00:00
package multiplex
import (
"sync/atomic"
"github.com/juju/ratelimit"
)
// Valve needs to be universal, across all sessions that belong to a user
// gabe please don't sue
type Valve struct {
// traffic directions from the server's perspective are refered
// exclusively as rx and tx.
// rx is from client to server, tx is from server to client
// DO NOT use terms up or down as this is used in usermanager
// for bandwidth limiting
rxtb atomic.Value // *ratelimit.Bucket
txtb atomic.Value // *ratelimit.Bucket
2018-11-22 21:55:23 +00:00
rxCredit *int64
txCredit *int64
2018-11-07 21:16:13 +00:00
}
2018-11-22 21:55:23 +00:00
func MakeValve(rxRate, txRate int64, rxCredit, txCredit *int64) *Valve {
2018-11-07 21:16:13 +00:00
v := &Valve{
rxCredit: rxCredit,
txCredit: txCredit,
}
v.SetRxRate(rxRate)
v.SetTxRate(txRate)
return v
}
2018-12-03 20:33:14 +00:00
func (v *Valve) SetRxRate(rate int64) { v.rxtb.Store(ratelimit.NewBucketWithRate(float64(rate), rate)) }
2018-11-22 21:55:23 +00:00
2018-12-03 20:33:14 +00:00
func (v *Valve) SetTxRate(rate int64) { v.txtb.Store(ratelimit.NewBucketWithRate(float64(rate), rate)) }
2018-11-07 21:16:13 +00:00
2018-12-03 20:33:14 +00:00
func (v *Valve) rxWait(n int) { v.rxtb.Load().(*ratelimit.Bucket).Wait(int64(n)) }
2018-11-07 21:16:13 +00:00
2018-12-03 20:33:14 +00:00
func (v *Valve) txWait(n int) { v.txtb.Load().(*ratelimit.Bucket).Wait(int64(n)) }
2018-11-07 21:16:13 +00:00
2018-12-03 20:33:14 +00:00
func (v *Valve) SetRxCredit(n int64) { atomic.StoreInt64(v.rxCredit, n) }
2018-11-07 21:16:13 +00:00
2018-12-03 20:33:14 +00:00
func (v *Valve) SetTxCredit(n int64) { atomic.StoreInt64(v.txCredit, n) }
2018-11-22 21:55:23 +00:00
2018-12-03 20:33:14 +00:00
func (v *Valve) GetRxCredit() int64 { return atomic.LoadInt64(v.rxCredit) }
2018-11-22 21:55:23 +00:00
2018-12-03 20:33:14 +00:00
func (v *Valve) GetTxCredit() int64 { return atomic.LoadInt64(v.txCredit) }
2018-11-07 21:16:13 +00:00
// n can be negative
2018-12-03 20:33:14 +00:00
func (v *Valve) AddRxCredit(n int64) int64 { return atomic.AddInt64(v.rxCredit, n) }
2018-11-07 21:16:13 +00:00
// n can be negative
2018-12-03 20:33:14 +00:00
func (v *Valve) AddTxCredit(n int64) int64 { return atomic.AddInt64(v.txCredit, n) }