1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-18 02:16:10 -05:00
v2fly/app/router/routing_table.go

71 lines
1.1 KiB
Go
Raw Normal View History

2016-10-12 10:11:13 -04:00
package router
2016-05-30 18:21:29 -04:00
import (
"sync"
"time"
)
type RoutingEntry struct {
tag string
err error
expire time.Time
}
2016-11-27 15:39:09 -05:00
func (v *RoutingEntry) Extend() {
v.expire = time.Now().Add(time.Hour)
2016-05-30 18:21:29 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *RoutingEntry) Expired() bool {
return v.expire.Before(time.Now())
2016-05-30 18:21:29 -04:00
}
type RoutingTable struct {
sync.RWMutex
table map[string]*RoutingEntry
}
func NewRoutingTable() *RoutingTable {
return &RoutingTable{
table: make(map[string]*RoutingEntry),
}
}
2016-11-27 15:39:09 -05:00
func (v *RoutingTable) Cleanup() {
v.Lock()
defer v.Unlock()
2016-05-30 18:21:29 -04:00
2016-11-27 15:39:09 -05:00
for key, value := range v.table {
2016-05-30 18:21:29 -04:00
if value.Expired() {
2016-11-27 15:39:09 -05:00
delete(v.table, key)
2016-05-30 18:21:29 -04:00
}
}
}
2016-11-27 15:39:09 -05:00
func (v *RoutingTable) Set(destination string, tag string, err error) {
v.Lock()
defer v.Unlock()
2016-05-30 18:21:29 -04:00
entry := &RoutingEntry{
tag: tag,
err: err,
}
entry.Extend()
2016-11-27 15:39:09 -05:00
v.table[destination] = entry
2016-05-30 18:21:29 -04:00
2016-11-27 15:39:09 -05:00
if len(v.table) > 1000 {
go v.Cleanup()
2016-05-30 18:21:29 -04:00
}
}
2016-11-27 15:39:09 -05:00
func (v *RoutingTable) Get(destination string) (bool, string, error) {
v.RLock()
defer v.RUnlock()
2016-05-30 18:21:29 -04:00
2016-11-27 15:39:09 -05:00
entry, found := v.table[destination]
2016-05-30 18:21:29 -04:00
if !found {
return false, "", nil
}
entry.Extend()
return true, entry.tag, entry.err
}