| 1 |
// Copyright 2024-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package thw |
| 15 |
|
| 16 |
import ( |
| 17 |
"encoding/binary" |
| 18 |
"errors" |
| 19 |
"io" |
| 20 |
"math" |
| 21 |
"time" |
| 22 |
) |
| 23 |
|
| 24 |
// Error for when we can not locate a task for removal or updates. |
| 25 |
var ErrTaskNotFound = errors.New("thw: task not found") |
| 26 |
|
| 27 |
// Error for when we try to decode a binary-encoded THW with an unknown version number. |
| 28 |
var ErrInvalidVersion = errors.New("thw: encoded version not known") |
| 29 |
|
| 30 |
const ( |
| 31 |
tickDuration = int64(time.Second) // Tick duration in nanoseconds. |
| 32 |
wheelBits = 12 // 2^12 = 4096 slots. |
| 33 |
wheelSize = 1 << wheelBits // Number of slots in the wheel. |
| 34 |
wheelMask = wheelSize - 1 // Mask for calculating position. |
| 35 |
headerLen = 17 // 1 byte magic + 2x uint64s |
| 36 |
) |
| 37 |
|
| 38 |
// slot represents a single slot in the wheel. |
| 39 |
type slot struct { |
| 40 |
entries map[uint64]int64 // Map of sequence to expires. |
| 41 |
lowest int64 // Lowest expiration time in this slot. |
| 42 |
} |
| 43 |
|
| 44 |
// HashWheel represents the timing wheel. |
| 45 |
type HashWheel struct { |
| 46 |
wheel []*slot // Array of slots. |
| 47 |
lowest int64 // Track the lowest expiration time across all slots. |
| 48 |
count uint64 // How many entries are present? |
| 49 |
} |
| 50 |
|
| 51 |
// HashWheelEntry represents a single entry in the wheel. |
| 52 |
type HashWheelEntry struct { |
| 53 |
Seq uint64 |
| 54 |
Expires int64 |
| 55 |
} |
| 56 |
|
| 57 |
// NewHashWheel initializes a new HashWheel. |
| 58 |
func NewHashWheel() *HashWheel { |
| 59 |
return &HashWheel{ |
| 60 |
wheel: make([]*slot, wheelSize), |
| 61 |
lowest: math.MaxInt64, |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
// getPosition calculates the slot position for a given expiration time. |
| 66 |
func (hw *HashWheel) getPosition(expires int64) int64 { |
| 67 |
return (expires / tickDuration) & wheelMask |
| 68 |
} |
| 69 |
|
| 70 |
// newSlot creates a new slot. |
| 71 |
func newSlot() *slot { |
| 72 |
return &slot{ |
| 73 |
entries: make(map[uint64]int64), |
| 74 |
lowest: math.MaxInt64, |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
// Add schedules a new timer task. |
| 79 |
func (hw *HashWheel) Add(seq uint64, expires int64) error { |
| 80 |
pos := hw.getPosition(expires) |
| 81 |
// Initialize the slot lazily. |
| 82 |
if hw.wheel[pos] == nil { |
| 83 |
hw.wheel[pos] = newSlot() |
| 84 |
} |
| 85 |
if _, ok := hw.wheel[pos].entries[seq]; !ok { |
| 86 |
hw.count++ |
| 87 |
} |
| 88 |
hw.wheel[pos].entries[seq] = expires |
| 89 |
|
| 90 |
// Update slot's lowest expiration if this is earlier. |
| 91 |
if expires < hw.wheel[pos].lowest { |
| 92 |
hw.wheel[pos].lowest = expires |
| 93 |
// Update global lowest if this is now the earliest. |
| 94 |
if expires < hw.lowest { |
| 95 |
hw.lowest = expires |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
return nil |
| 100 |
} |
| 101 |
|
| 102 |
// Remove removes a timer task. |
| 103 |
func (hw *HashWheel) Remove(seq uint64, expires int64) error { |
| 104 |
pos := hw.getPosition(expires) |
| 105 |
s := hw.wheel[pos] |
| 106 |
if s == nil { |
| 107 |
return ErrTaskNotFound |
| 108 |
} |
| 109 |
if _, exists := s.entries[seq]; !exists { |
| 110 |
return ErrTaskNotFound |
| 111 |
} |
| 112 |
delete(s.entries, seq) |
| 113 |
hw.count-- |
| 114 |
|
| 115 |
// If the slot is empty, we can set it to nil to free memory. |
| 116 |
if len(s.entries) == 0 { |
| 117 |
hw.wheel[pos] = nil |
| 118 |
} |
| 119 |
return nil |
| 120 |
} |
| 121 |
|
| 122 |
// Update updates the expiration time of an existing timer task. |
| 123 |
func (hw *HashWheel) Update(seq uint64, oldExpires int64, newExpires int64) error { |
| 124 |
// Remove from old position. |
| 125 |
if err := hw.Remove(seq, oldExpires); err != nil { |
| 126 |
return err |
| 127 |
} |
| 128 |
// Add to new position. |
| 129 |
return hw.Add(seq, newExpires) |
| 130 |
} |
| 131 |
|
| 132 |
// ExpireTasks processes all expired tasks using a callback, but only expires a task if the callback returns true. |
| 133 |
func (hw *HashWheel) ExpireTasks(callback func(seq uint64, expires int64) bool) { |
| 134 |
now := time.Now().UnixNano() |
| 135 |
hw.expireTasks(now, callback) |
| 136 |
} |
| 137 |
|
| 138 |
func (hw *HashWheel) expireTasks(ts int64, callback func(seq uint64, expires int64) bool) { |
| 139 |
// Quick return if nothing is expired. |
| 140 |
if hw.lowest > ts { |
| 141 |
return |
| 142 |
} |
| 143 |
|
| 144 |
globalLowest := int64(math.MaxInt64) |
| 145 |
for pos, s := range hw.wheel { |
| 146 |
// Skip s if nothing to expire. |
| 147 |
if s == nil || s.lowest > ts { |
| 148 |
if s != nil && s.lowest < globalLowest { |
| 149 |
globalLowest = s.lowest |
| 150 |
} |
| 151 |
continue |
| 152 |
} |
| 153 |
|
| 154 |
// Track new lowest while processing expirations |
| 155 |
slotLowest := int64(math.MaxInt64) |
| 156 |
for seq, expires := range s.entries { |
| 157 |
if expires <= ts && callback(seq, expires) { |
| 158 |
// Only remove if not done so already by the callback. |
| 159 |
if _, ok := s.entries[seq]; ok { |
| 160 |
delete(s.entries, seq) |
| 161 |
hw.count-- |
| 162 |
} |
| 163 |
continue |
| 164 |
} |
| 165 |
if expires < slotLowest { |
| 166 |
slotLowest = expires |
| 167 |
} |
| 168 |
} |
| 169 |
|
| 170 |
// Nil out if we are empty. |
| 171 |
if len(s.entries) == 0 { |
| 172 |
hw.wheel[pos] = nil |
| 173 |
} else { |
| 174 |
s.lowest = slotLowest |
| 175 |
if slotLowest < globalLowest { |
| 176 |
globalLowest = slotLowest |
| 177 |
} |
| 178 |
} |
| 179 |
} |
| 180 |
hw.lowest = globalLowest |
| 181 |
} |
| 182 |
|
| 183 |
// GetNextExpiration returns the earliest expiration time before the given time. |
| 184 |
// Returns math.MaxInt64 if no expirations exist before the specified time. |
| 185 |
func (hw *HashWheel) GetNextExpiration(before int64) int64 { |
| 186 |
if hw.lowest < before { |
| 187 |
return hw.lowest |
| 188 |
} |
| 189 |
return math.MaxInt64 |
| 190 |
} |
| 191 |
|
| 192 |
// Count returns the amount of tasks in the THW. |
| 193 |
func (hw *HashWheel) Count() uint64 { |
| 194 |
return hw.count |
| 195 |
} |
| 196 |
|
| 197 |
// Encode writes out the contents of the THW into a binary snapshot |
| 198 |
// and returns it. The high seq number is included in the snapshot and will |
| 199 |
// be returned on decode. |
| 200 |
func (hw *HashWheel) Encode(highSeq uint64) []byte { |
| 201 |
b := make([]byte, 0, headerLen+(hw.count*(2*binary.MaxVarintLen64))) |
| 202 |
b = append(b, 1) // Magic version |
| 203 |
b = binary.LittleEndian.AppendUint64(b, hw.count) // Entry count |
| 204 |
b = binary.LittleEndian.AppendUint64(b, highSeq) // Stamp |
| 205 |
for _, slot := range hw.wheel { |
| 206 |
if slot == nil || slot.entries == nil { |
| 207 |
continue |
| 208 |
} |
| 209 |
for v, ts := range slot.entries { |
| 210 |
b = binary.AppendVarint(b, ts) |
| 211 |
b = binary.AppendUvarint(b, v) |
| 212 |
} |
| 213 |
} |
| 214 |
return b |
| 215 |
} |
| 216 |
|
| 217 |
// Decode snapshots a binary-encoded THW and replaces the contents of this |
| 218 |
// THW with them. Returns the high seq number from the snapshot. |
| 219 |
func (hw *HashWheel) Decode(b []byte) (uint64, error) { |
| 220 |
if len(b) < headerLen { |
| 221 |
return 0, io.ErrShortBuffer |
| 222 |
} |
| 223 |
if b[0] != 1 { |
| 224 |
return 0, ErrInvalidVersion |
| 225 |
} |
| 226 |
hw.wheel = make([]*slot, wheelSize) |
| 227 |
hw.lowest = math.MaxInt64 |
| 228 |
count := binary.LittleEndian.Uint64(b[1:]) |
| 229 |
stamp := binary.LittleEndian.Uint64(b[9:]) |
| 230 |
b = b[headerLen:] |
| 231 |
for i := uint64(0); i < count; i++ { |
| 232 |
ts, tn := binary.Varint(b) |
| 233 |
if tn <= 0 { |
| 234 |
return 0, io.ErrUnexpectedEOF |
| 235 |
} |
| 236 |
v, vn := binary.Uvarint(b[tn:]) |
| 237 |
if vn <= 0 { |
| 238 |
return 0, io.ErrUnexpectedEOF |
| 239 |
} |
| 240 |
hw.Add(v, ts) |
| 241 |
b = b[tn+vn:] |
| 242 |
} |
| 243 |
return stamp, nil |
| 244 |
} |