package access import ( "container/list" "sync" ) // Served is a host-local set of (asset, buyer) pairs already served. // // It is a scheduling hint, never an entitlement decision. It is never // published, and an error in it can only mis-prioritise a repeat downloader. // It exists because a first acquisition is worth more to the network than a // repeat fetch. type Served struct { mu sync.Mutex capacity int order *list.List index map[string]*list.Element } type servedKey struct{ asset, buyer string } // NewServed creates a bounded recently-served cache. func NewServed(capacity int) *Served { if capacity <= 0 { capacity = 100_000 } return &Served{ capacity: capacity, order: list.New(), index: make(map[string]*list.Element, capacity), } } func skey(asset, buyer string) string { return asset + "|" + buyer } // Has reports whether the pair was served recently. It moves the pair to the // front of the eviction order. func (s *Served) Has(asset, buyer string) bool { if s == nil || asset == "" || buyer == "" { return false } k := skey(asset, buyer) s.mu.Lock() defer s.mu.Unlock() if e, ok := s.index[k]; ok { s.order.MoveToFront(e) return true } return false } // Mark records a serve. func (s *Served) Mark(asset, buyer string) { if s == nil || asset == "" || buyer == "" { return } k := skey(asset, buyer) s.mu.Lock() defer s.mu.Unlock() if e, ok := s.index[k]; ok { s.order.MoveToFront(e) return } e := s.order.PushFront(servedKey{asset: asset, buyer: buyer}) s.index[k] = e for s.order.Len() > s.capacity { back := s.order.Back() if back == nil { break } s.order.Remove(back) kv := back.Value.(servedKey) delete(s.index, skey(kv.asset, kv.buyer)) } } // Len returns the number of tracked pairs. func (s *Served) Len() int { if s == nil { return 0 } s.mu.Lock() defer s.mu.Unlock() return s.order.Len() } // FirstAcquisition reports whether serving this pair would be a first // acquisition, which is the case the priority optimisation favours. func (s *Served) FirstAcquisition(asset, buyer string) bool { return !s.Has(asset, buyer) }