1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 02:26:49 -05:00
v2fly/transport/internet/ws/connection_cache.go

115 lines
2.0 KiB
Go
Raw Normal View History

2016-08-13 09:44:36 -04:00
package ws
import (
"net"
"sync"
"time"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common/log"
"v2ray.com/core/common/signal"
2016-08-13 09:44:36 -04:00
)
type AwaitingConnection struct {
conn *wsconn
expire time.Time
}
2016-11-27 15:39:09 -05:00
func (v *AwaitingConnection) Expired() bool {
return v.expire.Before(time.Now())
2016-08-13 09:44:36 -04:00
}
type ConnectionCache struct {
sync.Mutex
cache map[string][]*AwaitingConnection
cleanupOnce signal.Once
}
func NewConnectionCache() *ConnectionCache {
return &ConnectionCache{
cache: make(map[string][]*AwaitingConnection),
}
}
2016-11-27 15:39:09 -05:00
func (v *ConnectionCache) Cleanup() {
defer v.cleanupOnce.Reset()
2016-08-13 09:44:36 -04:00
2016-11-27 15:39:09 -05:00
for len(v.cache) > 0 {
2016-08-15 09:21:09 -04:00
time.Sleep(time.Second * 7)
2016-11-27 15:39:09 -05:00
v.Lock()
for key, value := range v.cache {
2016-08-13 09:44:36 -04:00
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]
2016-11-27 15:39:09 -05:00
v.cache[key] = value
2016-08-13 09:44:36 -04:00
}
}
2016-11-27 15:39:09 -05:00
v.Unlock()
2016-08-13 09:44:36 -04:00
}
}
2016-11-27 15:39:09 -05:00
func (v *ConnectionCache) Recycle(dest string, conn *wsconn) {
v.Lock()
defer v.Unlock()
2016-08-13 09:44:36 -04:00
aconn := &AwaitingConnection{
conn: conn,
2016-08-15 08:14:45 -04:00
expire: time.Now().Add(time.Second * 7),
2016-08-13 09:44:36 -04:00
}
var list []*AwaitingConnection
2016-11-27 15:39:09 -05:00
if val, found := v.cache[dest]; found {
2016-11-27 11:01:44 -05:00
val = append(val, aconn)
list = val
2016-08-13 09:44:36 -04:00
} else {
list = []*AwaitingConnection{aconn}
}
2016-11-27 15:39:09 -05:00
v.cache[dest] = list
2016-08-13 09:44:36 -04:00
2016-11-27 15:39:09 -05:00
go v.cleanupOnce.Do(v.Cleanup)
2016-08-13 09:44:36 -04:00
}
func FindFirstValid(list []*AwaitingConnection) int {
for idx, conn := range list {
if !conn.Expired() && !conn.conn.connClosing {
return idx
}
go conn.conn.Close()
}
return -1
}
2016-11-27 15:39:09 -05:00
func (v *ConnectionCache) Get(dest string) net.Conn {
v.Lock()
defer v.Unlock()
2016-08-13 09:44:36 -04:00
2016-11-27 15:39:09 -05:00
list, found := v.cache[dest]
2016-08-13 09:44:36 -04:00
if !found {
return nil
}
firstValid := FindFirstValid(list)
if firstValid == -1 {
2016-11-27 15:39:09 -05:00
delete(v.cache, dest)
2016-08-13 09:44:36 -04:00
return nil
}
res := list[firstValid].conn
list = list[firstValid+1:]
2016-11-27 15:39:09 -05:00
v.cache[dest] = list
2016-08-14 23:07:29 -04:00
log.Debug("WS:Conn Cache used.")
2016-08-13 09:44:36 -04:00
return res
}