feat(dns): Implement optimistic caching

This commit is contained in:
Meo597
2025-10-19 02:24:04 +08:00
parent b69a376aa1
commit 79787a0176
14 changed files with 352 additions and 194 deletions
+19 -14
View File
@@ -3,6 +3,9 @@ package dns
import (
"context"
go_errors "errors"
"sync"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
@@ -10,25 +13,27 @@ import (
"github.com/xtls/xray-core/common/task"
dns_feature "github.com/xtls/xray-core/features/dns"
"golang.org/x/net/dns/dnsmessage"
"sync"
"time"
)
type CacheController struct {
sync.RWMutex
ips map[string]*record
pub *pubsub.Service
cacheCleanup *task.Periodic
name string
disableCache bool
ips map[string]*record
pub *pubsub.Service
cacheCleanup *task.Periodic
name string
disableCache bool
serveStale bool
serveExpiredTTL int32
}
func NewCacheController(name string, disableCache bool) *CacheController {
func NewCacheController(name string, disableCache bool, serveStale bool, serveExpiredTTL uint32) *CacheController {
c := &CacheController{
name: name,
disableCache: disableCache,
ips: make(map[string]*record),
pub: pubsub.NewService(),
name: name,
disableCache: disableCache,
serveStale: serveStale,
serveExpiredTTL: -int32(serveExpiredTTL),
ips: make(map[string]*record),
pub: pubsub.NewService(),
}
c.cacheCleanup = &task.Periodic{
@@ -113,7 +118,7 @@ func (c *CacheController) updateIP(req *dnsRequest, ipRec *IPRecord) {
common.Must(c.cacheCleanup.Start())
}
func (c *CacheController) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, uint32, error) {
func (c *CacheController) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, int32, error) {
c.RLock()
record, found := c.ips[domain]
c.RUnlock()
@@ -124,7 +129,7 @@ func (c *CacheController) findIPsForDomain(domain string, option dns_feature.IPO
var errs []error
var allIPs []net.IP
var rTTL uint32 = dns_feature.DefaultTTL
var rTTL int32 = dns_feature.DefaultTTL
mergeReq := option.IPv4Enable && option.IPv6Enable