File size: 9,191 Bytes
ea775bd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | package node
import (
"math"
"strings"
"sync"
"time"
"github.com/zeebo/xxh3"
)
// DomainLatencyStats holds the TD-EWMA latency statistics for a single domain.
type DomainLatencyStats struct {
Ewma time.Duration
LastUpdated time.Time
}
const latencyReadTouchMinInterval = 100 * time.Millisecond
type latencySlot struct {
key uint64
domain string
stats DomainLatencyStats
lastAccessNs int64
occupied bool
}
type latencyEntry struct {
domain string
stats DomainLatencyStats
}
// LatencyTable is a bounded, thread-safe per-domain latency table.
// It keeps authority domains in a resident partition and regular domains in a
// bounded partition evicted by least-recently-accessed timestamp.
// Domain lookup inside the table uses a 64-bit xxh3 hash key for compactness.
// This intentionally accepts extremely low-probability hash collisions.
type LatencyTable struct {
mu sync.Mutex
authorities []latencySlot
regular []latencySlot
}
// NewLatencyTable creates a new LatencyTable whose regular partition
// is bounded to maxEntries.
func NewLatencyTable(maxEntries int) *LatencyTable {
if maxEntries <= 0 {
panic("node: latency table max entries must be positive")
}
return &LatencyTable{
regular: make([]latencySlot, maxEntries),
}
}
// Update records a latency observation for the given domain using TD-EWMA.
// wasEmpty is true if the table had no entries before this update.
//
// TD-EWMA formula:
//
// weight = exp(-Δt / decayWindow)
// newEwma = oldEwma * weight + latency * (1 - weight)
//
// For the first observation of a domain, Ewma is set to the raw latency.
func (t *LatencyTable) Update(domain string, latency, decayWindow time.Duration) (wasEmpty bool) {
wasEmpty, _, _ = t.UpdateClassified(domain, latency, decayWindow, false)
return wasEmpty
}
// UpdateClassified records a latency observation and writes into either
// authority-resident partition or regular partition.
// It returns evicted=true with evictedDomain when a regular-domain eviction
// happens due to bounded capacity.
func (t *LatencyTable) UpdateClassified(
domain string,
latency, decayWindow time.Duration,
isAuthority bool,
) (wasEmpty bool, evictedDomain string, evicted bool) {
key := domainKey(domain)
now := time.Now()
nowNs := now.UnixNano()
t.mu.Lock()
defer t.mu.Unlock()
wasEmpty = t.totalSizeLocked() == 0
old, found := t.popDomainLocked(key)
stats := tdEWMAUpdate(old, found, latency, decayWindow, now)
if isAuthority {
t.upsertAuthorityLocked(key, domain, stats, nowNs)
return wasEmpty, "", false
}
evictedDomain, evicted = t.upsertRegularLocked(key, domain, stats, nowNs)
return wasEmpty, evictedDomain, evicted
}
// GetDomainStats returns the latency stats for a domain, if present.
// Read touches are write-throttled: last-access timestamp is updated only when
// the last update is older than latencyReadTouchMinInterval.
func (t *LatencyTable) GetDomainStats(domain string) (DomainLatencyStats, bool) {
key := domainKey(domain)
nowNs := time.Now().UnixNano()
t.mu.Lock()
defer t.mu.Unlock()
for i := range t.authorities {
if !t.authorities[i].occupied || t.authorities[i].key != key {
continue
}
stats := t.authorities[i].stats
if nowNs-t.authorities[i].lastAccessNs >= latencyReadTouchMinInterval.Nanoseconds() {
t.authorities[i].lastAccessNs = nowNs
}
return stats, true
}
for i := range t.regular {
if !t.regular[i].occupied || t.regular[i].key != key {
continue
}
stats := t.regular[i].stats
if nowNs-t.regular[i].lastAccessNs >= latencyReadTouchMinInterval.Nanoseconds() {
t.regular[i].lastAccessNs = nowNs
}
return stats, true
}
return DomainLatencyStats{}, false
}
// LoadEntry stores a bootstrap-recovered entry directly (no TD-EWMA).
func (t *LatencyTable) LoadEntry(domain string, stats DomainLatencyStats) {
_, _ = t.LoadEntryClassified(domain, stats, false)
}
// LoadEntryClassified stores a bootstrap-recovered entry directly (no TD-EWMA)
// into either authority or regular partition.
func (t *LatencyTable) LoadEntryClassified(
domain string,
stats DomainLatencyStats,
isAuthority bool,
) (evictedDomain string, evicted bool) {
key := domainKey(domain)
accessNs := stats.LastUpdated.UnixNano()
if accessNs <= 0 {
accessNs = time.Now().UnixNano()
}
t.mu.Lock()
defer t.mu.Unlock()
t.popDomainLocked(key)
if isAuthority {
t.upsertAuthorityLocked(key, domain, stats, accessNs)
return "", false
}
return t.upsertRegularLocked(key, domain, stats, accessNs)
}
// Size returns the number of domains with latency data.
func (t *LatencyTable) Size() int {
t.mu.Lock()
defer t.mu.Unlock()
return t.totalSizeLocked()
}
// Range iterates all domain entries. Returning false stops iteration.
func (t *LatencyTable) Range(fn func(domain string, stats DomainLatencyStats) bool) {
t.mu.Lock()
snapshot := make([]latencyEntry, 0, t.totalSizeLocked())
for i := range t.authorities {
if !t.authorities[i].occupied {
continue
}
snapshot = append(snapshot, latencyEntry{
domain: t.authorities[i].domain,
stats: t.authorities[i].stats,
})
}
for i := range t.regular {
if !t.regular[i].occupied {
continue
}
snapshot = append(snapshot, latencyEntry{
domain: t.regular[i].domain,
stats: t.regular[i].stats,
})
}
t.mu.Unlock()
for _, e := range snapshot {
if !fn(e.domain, e.stats) {
return
}
}
}
// Close is kept for lifecycle symmetry. LatencyTable currently has no
// background resources and Close is a no-op.
func (t *LatencyTable) Close() {}
func (t *LatencyTable) totalSizeLocked() int {
count := 0
for i := range t.authorities {
if t.authorities[i].occupied {
count++
}
}
for i := range t.regular {
if t.regular[i].occupied {
count++
}
}
return count
}
func (t *LatencyTable) popDomainLocked(key uint64) (DomainLatencyStats, bool) {
for i := range t.authorities {
if t.authorities[i].occupied && t.authorities[i].key == key {
stats := t.authorities[i].stats
t.authorities = deleteLatencySlot(t.authorities, i)
return stats, true
}
}
for i := range t.regular {
if t.regular[i].occupied && t.regular[i].key == key {
stats := t.regular[i].stats
t.regular[i] = latencySlot{}
return stats, true
}
}
return DomainLatencyStats{}, false
}
func (t *LatencyTable) upsertAuthorityLocked(
key uint64,
domain string,
stats DomainLatencyStats,
accessNs int64,
) {
t.authorities = append(t.authorities, latencySlot{
key: key,
domain: domain,
stats: stats,
lastAccessNs: accessNs,
occupied: true,
})
}
func (t *LatencyTable) upsertRegularLocked(
key uint64,
domain string,
stats DomainLatencyStats,
accessNs int64,
) (evictedDomain string, evicted bool) {
emptyIdx := -1
oldestIdx := -1
oldestAccessNs := int64(0)
for i := range t.regular {
slot := t.regular[i]
if !slot.occupied {
if emptyIdx < 0 {
emptyIdx = i
}
continue
}
if oldestIdx < 0 || slot.lastAccessNs < oldestAccessNs {
oldestIdx = i
oldestAccessNs = slot.lastAccessNs
}
}
targetIdx := emptyIdx
if targetIdx < 0 {
targetIdx = oldestIdx
if targetIdx >= 0 {
evictedDomain = t.regular[targetIdx].domain
evicted = true
}
}
if targetIdx < 0 {
return "", false
}
t.regular[targetIdx] = latencySlot{
key: key,
domain: domain,
stats: stats,
lastAccessNs: accessNs,
occupied: true,
}
return evictedDomain, evicted
}
// domainKey builds a compact 64-bit key for domain matching in LatencyTable.
// Collision handling is intentionally omitted as a memory/perf trade-off.
func domainKey(domain string) uint64 {
return xxh3.HashString(domain)
}
func deleteLatencySlot(slots []latencySlot, idx int) []latencySlot {
if idx < 0 || idx >= len(slots) {
return slots
}
copy(slots[idx:], slots[idx+1:])
slots[len(slots)-1] = latencySlot{}
return slots[:len(slots)-1]
}
func tdEWMAUpdate(
old DomainLatencyStats,
found bool,
latency, decayWindow time.Duration,
now time.Time,
) DomainLatencyStats {
if !found {
return DomainLatencyStats{
Ewma: latency,
LastUpdated: now,
}
}
dt := now.Sub(old.LastUpdated).Seconds()
decay := decayWindow.Seconds()
if decay <= 0 {
decay = 1 // prevent division by zero
}
weight := math.Exp(-dt / decay)
newEwma := time.Duration(float64(old.Ewma)*weight + float64(latency)*(1-weight))
return DomainLatencyStats{
Ewma: newEwma,
LastUpdated: now,
}
}
// AverageEWMAForDomainsMs returns the average EWMA latency in milliseconds
// across domains that exist in the node's latency table.
func AverageEWMAForDomainsMs(entry *NodeEntry, domains []string) (float64, bool) {
if entry == nil || entry.LatencyTable == nil || entry.LatencyTable.Size() == 0 || len(domains) == 0 {
return 0, false
}
var sumMs float64
var count int
for _, domain := range domains {
domain = strings.TrimSpace(domain)
if domain == "" {
continue
}
stats, ok := entry.LatencyTable.GetDomainStats(domain)
if !ok {
continue
}
sumMs += float64(stats.Ewma.Milliseconds())
count++
}
if count == 0 {
return 0, false
}
return sumMs / float64(count), true
}
|