| 1 |
package nebula |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync" |
| 5 |
"time" |
| 6 |
) |
| 7 |
|
| 8 |
// How many timer objects should be cached |
| 9 |
const timerCacheMax = 50000 |
| 10 |
|
| 11 |
// TimerWheel is a hashed timing wheel: a fixed slot array indexed by (now + delay) % wheelLen, |
| 12 |
// with each slot a singly linked list of items due in that bucket. |
| 13 |
// Adds are O(1), Purges return items in arrival-within-slot order, and an internal cache of TimeoutItems |
| 14 |
// keeps steady-state inserts allocation-free. |
| 15 |
// |
| 16 |
// The TimerWheel does not handle concurrency or lifecycle on its own. |
| 17 |
// Callers drive Advance/Purge from their own ticker loop, take their own locks (or use LockingTimerWheel), |
| 18 |
// and decide whether to keep ticking when the wheel is empty. |
| 19 |
// |
| 20 |
// Pick a TimerWheel when scheduling is high-rate and uniform: line-rate conntrack inserts, |
| 21 |
// per-tunnel traffic checks at fixed intervals. O(1) insert plus the item cache means the hot path doesn't allocate. |
| 22 |
// Items added in the same tick are dispatched together when that slot rotates current, |
| 23 |
// which amortizes the cost of waking the worker. |
| 24 |
// |
| 25 |
// Pick a Scheduler when delay precision matters or scheduling is sparse or uneven. |
| 26 |
// The wheel rounds requested timeouts up to its tick resolution and clamps anything beyond its wheel duration; |
| 27 |
// both are silent in this implementation. |
| 28 |
type TimerWheel[T any] struct { |
| 29 |
// Current tick |
| 30 |
current int |
| 31 |
|
| 32 |
// Cheat on finding the length of the wheel |
| 33 |
wheelLen int |
| 34 |
|
| 35 |
// Last time we ticked, since we are lazy ticking |
| 36 |
lastTick *time.Time |
| 37 |
|
| 38 |
// Durations of a tick and the entire wheel |
| 39 |
tickDuration time.Duration |
| 40 |
wheelDuration time.Duration |
| 41 |
|
| 42 |
// The actual wheel which is just a set of singly linked lists, head/tail pointers |
| 43 |
wheel []*TimeoutList[T] |
| 44 |
|
| 45 |
// Singly linked list of items that have timed out of the wheel |
| 46 |
expired *TimeoutList[T] |
| 47 |
|
| 48 |
// Item cache to avoid garbage collect |
| 49 |
itemCache *TimeoutItem[T] |
| 50 |
itemsCached int |
| 51 |
} |
| 52 |
|
| 53 |
type LockingTimerWheel[T any] struct { |
| 54 |
m sync.Mutex |
| 55 |
t *TimerWheel[T] |
| 56 |
} |
| 57 |
|
| 58 |
// TimeoutList Represents a tick in the wheel |
| 59 |
type TimeoutList[T any] struct { |
| 60 |
Head *TimeoutItem[T] |
| 61 |
Tail *TimeoutItem[T] |
| 62 |
} |
| 63 |
|
| 64 |
// TimeoutItem Represents an item within a tick |
| 65 |
type TimeoutItem[T any] struct { |
| 66 |
Item T |
| 67 |
Next *TimeoutItem[T] |
| 68 |
} |
| 69 |
|
| 70 |
// NewTimerWheel Builds a timer wheel and identifies the tick duration and wheel duration from the provided values |
| 71 |
// Purge must be called once per entry to actually remove anything |
| 72 |
// The TimerWheel does not handle concurrency on its own. |
| 73 |
// Locks around access to it must be used if multiple routines are manipulating it. |
| 74 |
func NewTimerWheel[T any](min, max time.Duration) *TimerWheel[T] { |
| 75 |
//TODO provide an error |
| 76 |
//if min >= max { |
| 77 |
// return nil |
| 78 |
//} |
| 79 |
|
| 80 |
// Round down and add 2 so we can have the smallest # of ticks in the wheel and still account for a full |
| 81 |
// max duration, even if our current tick is at the maximum position and the next item to be added is at maximum |
| 82 |
// timeout |
| 83 |
wLen := int((max / min) + 2) |
| 84 |
|
| 85 |
tw := TimerWheel[T]{ |
| 86 |
wheelLen: wLen, |
| 87 |
wheel: make([]*TimeoutList[T], wLen), |
| 88 |
tickDuration: min, |
| 89 |
wheelDuration: max, |
| 90 |
expired: &TimeoutList[T]{}, |
| 91 |
} |
| 92 |
|
| 93 |
for i := range tw.wheel { |
| 94 |
tw.wheel[i] = &TimeoutList[T]{} |
| 95 |
} |
| 96 |
|
| 97 |
return &tw |
| 98 |
} |
| 99 |
|
| 100 |
// NewLockingTimerWheel is version of TimerWheel that is safe for concurrent use with a small performance penalty |
| 101 |
func NewLockingTimerWheel[T any](min, max time.Duration) *LockingTimerWheel[T] { |
| 102 |
return &LockingTimerWheel[T]{ |
| 103 |
t: NewTimerWheel[T](min, max), |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
// Add will add an item to the wheel in its proper timeout. |
| 108 |
// Caller should Advance the wheel prior to ensure the proper slot is used. |
| 109 |
func (tw *TimerWheel[T]) Add(v T, timeout time.Duration) *TimeoutItem[T] { |
| 110 |
i := tw.findWheel(timeout) |
| 111 |
|
| 112 |
// Try to fetch off the cache |
| 113 |
ti := tw.itemCache |
| 114 |
if ti != nil { |
| 115 |
tw.itemCache = ti.Next |
| 116 |
tw.itemsCached-- |
| 117 |
ti.Next = nil |
| 118 |
} else { |
| 119 |
ti = &TimeoutItem[T]{} |
| 120 |
} |
| 121 |
|
| 122 |
// Relink and return |
| 123 |
ti.Item = v |
| 124 |
if tw.wheel[i].Tail == nil { |
| 125 |
tw.wheel[i].Head = ti |
| 126 |
tw.wheel[i].Tail = ti |
| 127 |
} else { |
| 128 |
tw.wheel[i].Tail.Next = ti |
| 129 |
tw.wheel[i].Tail = ti |
| 130 |
} |
| 131 |
|
| 132 |
return ti |
| 133 |
} |
| 134 |
|
| 135 |
// Purge removes and returns the first available expired item from the wheel and the 2nd argument is true. |
| 136 |
// If no item is available then an empty T is returned and the 2nd argument is false. |
| 137 |
func (tw *TimerWheel[T]) Purge() (T, bool) { |
| 138 |
if tw.expired.Head == nil { |
| 139 |
var na T |
| 140 |
return na, false |
| 141 |
} |
| 142 |
|
| 143 |
ti := tw.expired.Head |
| 144 |
tw.expired.Head = ti.Next |
| 145 |
|
| 146 |
if tw.expired.Head == nil { |
| 147 |
tw.expired.Tail = nil |
| 148 |
} |
| 149 |
|
| 150 |
// Clear out the items references |
| 151 |
ti.Next = nil |
| 152 |
|
| 153 |
// Maybe cache it for later |
| 154 |
if tw.itemsCached < timerCacheMax { |
| 155 |
ti.Next = tw.itemCache |
| 156 |
tw.itemCache = ti |
| 157 |
tw.itemsCached++ |
| 158 |
} |
| 159 |
|
| 160 |
return ti.Item, true |
| 161 |
} |
| 162 |
|
| 163 |
// findWheel find the next position in the wheel for the provided timeout given the current tick |
| 164 |
func (tw *TimerWheel[T]) findWheel(timeout time.Duration) (i int) { |
| 165 |
if timeout < tw.tickDuration { |
| 166 |
// Can't track anything below the set resolution |
| 167 |
timeout = tw.tickDuration |
| 168 |
} else if timeout > tw.wheelDuration { |
| 169 |
// We aren't handling timeouts greater than the wheels duration |
| 170 |
timeout = tw.wheelDuration |
| 171 |
} |
| 172 |
|
| 173 |
// Find the next highest, rounding up |
| 174 |
tick := int(((timeout - 1) / tw.tickDuration) + 1) |
| 175 |
|
| 176 |
// Add another tick since the current tick may almost be over then map it to the wheel from our |
| 177 |
// current position |
| 178 |
tick += tw.current + 1 |
| 179 |
if tick >= tw.wheelLen { |
| 180 |
tick -= tw.wheelLen |
| 181 |
} |
| 182 |
|
| 183 |
return tick |
| 184 |
} |
| 185 |
|
| 186 |
// Advance will move the wheel forward by the appropriate number of ticks for the provided time and all items |
| 187 |
// passed over will be moved to the expired list. Calling Purge is necessary to remove them entirely. |
| 188 |
func (tw *TimerWheel[T]) Advance(now time.Time) { |
| 189 |
if tw.lastTick == nil { |
| 190 |
tw.lastTick = &now |
| 191 |
} |
| 192 |
|
| 193 |
// We want to round down |
| 194 |
ticks := int(now.Sub(*tw.lastTick) / tw.tickDuration) |
| 195 |
adv := ticks |
| 196 |
if ticks > tw.wheelLen { |
| 197 |
ticks = tw.wheelLen |
| 198 |
} |
| 199 |
|
| 200 |
for i := 0; i < ticks; i++ { |
| 201 |
tw.current++ |
| 202 |
if tw.current >= tw.wheelLen { |
| 203 |
tw.current = 0 |
| 204 |
} |
| 205 |
|
| 206 |
if tw.wheel[tw.current].Head != nil { |
| 207 |
// We need to append the expired items as to not starve evicting the oldest ones |
| 208 |
if tw.expired.Tail == nil { |
| 209 |
tw.expired.Head = tw.wheel[tw.current].Head |
| 210 |
tw.expired.Tail = tw.wheel[tw.current].Tail |
| 211 |
} else { |
| 212 |
tw.expired.Tail.Next = tw.wheel[tw.current].Head |
| 213 |
tw.expired.Tail = tw.wheel[tw.current].Tail |
| 214 |
} |
| 215 |
|
| 216 |
tw.wheel[tw.current].Head = nil |
| 217 |
tw.wheel[tw.current].Tail = nil |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
// Advance the tick based on duration to avoid losing some accuracy |
| 222 |
newTick := tw.lastTick.Add(tw.tickDuration * time.Duration(adv)) |
| 223 |
tw.lastTick = &newTick |
| 224 |
} |
| 225 |
|
| 226 |
func (lw *LockingTimerWheel[T]) Add(v T, timeout time.Duration) *TimeoutItem[T] { |
| 227 |
lw.m.Lock() |
| 228 |
defer lw.m.Unlock() |
| 229 |
return lw.t.Add(v, timeout) |
| 230 |
} |
| 231 |
|
| 232 |
func (lw *LockingTimerWheel[T]) Purge() (T, bool) { |
| 233 |
lw.m.Lock() |
| 234 |
defer lw.m.Unlock() |
| 235 |
return lw.t.Purge() |
| 236 |
} |
| 237 |
|
| 238 |
func (lw *LockingTimerWheel[T]) Advance(now time.Time) { |
| 239 |
lw.m.Lock() |
| 240 |
defer lw.m.Unlock() |
| 241 |
lw.t.Advance(now) |
| 242 |
} |