You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/transport/internet/ws/connection_cache.go

115 lines
2.0 KiB

package ws
import (
"net"
"sync"
"time"
"v2ray.com/core/common/log"
"v2ray.com/core/common/signal"
)
type AwaitingConnection struct {
conn *wsconn
expire time.Time
}
8 years ago
func (v *AwaitingConnection) Expired() bool {
return v.expire.Before(time.Now())
}
type ConnectionCache struct {
sync.Mutex
cache map[string][]*AwaitingConnection
cleanupOnce signal.Once
}
func NewConnectionCache() *ConnectionCache {
return &ConnectionCache{
cache: make(map[string][]*AwaitingConnection),
}
}
8 years ago
func (v *ConnectionCache) Cleanup() {
defer v.cleanupOnce.Reset()
8 years ago
for len(v.cache) > 0 {
8 years ago
time.Sleep(time.Second * 7)
8 years ago
v.Lock()
for key, value := range v.cache {
size := len(value)
changed := false
for i := 0; i < size; {
if value[i].Expired() {
value[i].conn.Close()
value[i] = value[size-1]
size--
changed = true
} else {
i++
}
}
if changed {
for i := size; i < len(value); i++ {
value[i] = nil
}
value = value[:size]
8 years ago
v.cache[key] = value
}
}
8 years ago
v.Unlock()
}
}
8 years ago
func (v *ConnectionCache) Recycle(dest string, conn *wsconn) {
v.Lock()
defer v.Unlock()
aconn := &AwaitingConnection{
conn: conn,
8 years ago
expire: time.Now().Add(time.Second * 7),
}
var list []*AwaitingConnection
8 years ago
if val, found := v.cache[dest]; found {
val = append(val, aconn)
list = val
} else {
list = []*AwaitingConnection{aconn}
}
8 years ago
v.cache[dest] = list
8 years ago
go v.cleanupOnce.Do(v.Cleanup)
}
func FindFirstValid(list []*AwaitingConnection) int {
for idx, conn := range list {
if !conn.Expired() && !conn.conn.connClosing {
return idx
}
go conn.conn.Close()
}
return -1
}
8 years ago
func (v *ConnectionCache) Get(dest string) net.Conn {
v.Lock()
defer v.Unlock()
8 years ago
list, found := v.cache[dest]
if !found {
return nil
}
firstValid := FindFirstValid(list)
if firstValid == -1 {
8 years ago
delete(v.cache, dest)
return nil
}
res := list[firstValid].conn
list = list[firstValid+1:]
8 years ago
v.cache[dest] = list
log.Debug("WS:Conn Cache used.")
return res
}