| 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 |
"io" |
| 19 |
"math" |
| 20 |
"testing" |
| 21 |
"time" |
| 22 |
) |
| 23 |
|
| 24 |
func TestHashWheelBasics(t *testing.T) { |
| 25 |
hw := NewHashWheel() |
| 26 |
now := time.Now() |
| 27 |
|
| 28 |
// Add a sequence. |
| 29 |
seq, expires := uint64(1), now.Add(5*time.Second).UnixNano() |
| 30 |
require_NoError(t, hw.Add(seq, expires)) |
| 31 |
require_Equal(t, hw.count, 1) |
| 32 |
|
| 33 |
// Try to remove non-existent sequence. |
| 34 |
require_Error(t, hw.Remove(999, expires), ErrTaskNotFound) |
| 35 |
require_Equal(t, hw.count, 1) |
| 36 |
|
| 37 |
// Remove the sequence properly. |
| 38 |
require_NoError(t, hw.Remove(seq, expires)) |
| 39 |
require_Equal(t, hw.count, 0) |
| 40 |
|
| 41 |
// Verify it's gone. |
| 42 |
require_Error(t, hw.Remove(seq, expires), ErrTaskNotFound) |
| 43 |
require_Equal(t, hw.count, 0) |
| 44 |
} |
| 45 |
|
| 46 |
func TestHashWheelUpdate(t *testing.T) { |
| 47 |
hw := NewHashWheel() |
| 48 |
now := time.Now() |
| 49 |
oldExpires := now.Add(5 * time.Second).UnixNano() |
| 50 |
newExpires := now.Add(10 * time.Second).UnixNano() |
| 51 |
|
| 52 |
// Add initial sequence. |
| 53 |
require_NoError(t, hw.Add(1, oldExpires)) |
| 54 |
require_Equal(t, hw.count, 1) |
| 55 |
|
| 56 |
// Update expiration. |
| 57 |
require_NoError(t, hw.Update(1, oldExpires, newExpires)) |
| 58 |
require_Equal(t, hw.count, 1) |
| 59 |
|
| 60 |
// Verify old expiration is gone. |
| 61 |
require_Error(t, hw.Remove(1, oldExpires), ErrTaskNotFound) |
| 62 |
require_Equal(t, hw.count, 1) |
| 63 |
|
| 64 |
// Verify new expiration exists |
| 65 |
require_NoError(t, hw.Remove(1, newExpires)) |
| 66 |
require_Equal(t, hw.count, 0) |
| 67 |
} |
| 68 |
|
| 69 |
func TestHashWheelExpiration(t *testing.T) { |
| 70 |
hw := NewHashWheel() |
| 71 |
now := time.Now() |
| 72 |
|
| 73 |
// Add sequences with different expiration times. |
| 74 |
seqs := map[uint64]int64{ |
| 75 |
1: now.Add(-1 * time.Second).UnixNano(), // Already expired |
| 76 |
2: now.Add(1 * time.Second).UnixNano(), // Expires soon |
| 77 |
3: now.Add(10 * time.Second).UnixNano(), // Expires later |
| 78 |
4: now.Add(60 * time.Second).UnixNano(), // Expires much later |
| 79 |
} |
| 80 |
|
| 81 |
for seq, expires := range seqs { |
| 82 |
require_NoError(t, hw.Add(seq, expires)) |
| 83 |
} |
| 84 |
require_Equal(t, hw.count, uint64(len(seqs))) |
| 85 |
|
| 86 |
// Process expired tasks. |
| 87 |
expired := make(map[uint64]bool) |
| 88 |
hw.ExpireTasks(func(seq uint64, expires int64) bool { |
| 89 |
expired[seq] = true |
| 90 |
return true |
| 91 |
}) |
| 92 |
|
| 93 |
// Verify only sequence 1 expired. |
| 94 |
require_Equal(t, len(expired), 1) |
| 95 |
require_True(t, expired[1]) |
| 96 |
require_Equal(t, hw.count, 3) |
| 97 |
} |
| 98 |
|
| 99 |
func TestHashWheelManualExpiration(t *testing.T) { |
| 100 |
hw := NewHashWheel() |
| 101 |
now := time.Now().UnixNano() |
| 102 |
|
| 103 |
for seq := uint64(1); seq <= 4; seq++ { |
| 104 |
require_NoError(t, hw.Add(seq, now)) |
| 105 |
} |
| 106 |
require_Equal(t, hw.count, 4) |
| 107 |
|
| 108 |
// Loop over expired multiple times, but without removing them. |
| 109 |
expired := make(map[uint64]uint64) |
| 110 |
for i := uint64(0); i <= 1; i++ { |
| 111 |
hw.ExpireTasks(func(seq uint64, expires int64) bool { |
| 112 |
expired[seq]++ |
| 113 |
return false |
| 114 |
}) |
| 115 |
|
| 116 |
require_Equal(t, len(expired), 4) |
| 117 |
require_Equal(t, expired[1], 1+i) |
| 118 |
require_Equal(t, expired[2], 1+i) |
| 119 |
require_Equal(t, expired[3], 1+i) |
| 120 |
require_Equal(t, expired[4], 1+i) |
| 121 |
require_Equal(t, hw.count, 4) |
| 122 |
} |
| 123 |
|
| 124 |
// Only remove even sequences. |
| 125 |
for i := uint64(0); i <= 1; i++ { |
| 126 |
hw.ExpireTasks(func(seq uint64, expires int64) bool { |
| 127 |
expired[seq]++ |
| 128 |
return seq%2 == 0 |
| 129 |
}) |
| 130 |
|
| 131 |
// Verify even sequences are removed. |
| 132 |
require_Equal(t, expired[1], 3+i) |
| 133 |
require_Equal(t, expired[2], 3) |
| 134 |
require_Equal(t, expired[3], 3+i) |
| 135 |
require_Equal(t, expired[4], 3) |
| 136 |
require_Equal(t, hw.count, 2) |
| 137 |
} |
| 138 |
|
| 139 |
// Manually remove last items. |
| 140 |
require_NoError(t, hw.Remove(1, now)) |
| 141 |
require_NoError(t, hw.Remove(3, now)) |
| 142 |
require_Equal(t, hw.count, 0) |
| 143 |
} |
| 144 |
|
| 145 |
func TestHashWheelExpirationLargerThanWheel(t *testing.T) { |
| 146 |
hw := NewHashWheel() |
| 147 |
|
| 148 |
// Add sequences such that they can be expired immediately. |
| 149 |
seqs := map[uint64]int64{ |
| 150 |
1: 0, |
| 151 |
2: int64(time.Second), |
| 152 |
} |
| 153 |
for seq, expires := range seqs { |
| 154 |
require_NoError(t, hw.Add(seq, expires)) |
| 155 |
} |
| 156 |
require_Equal(t, hw.count, 2) |
| 157 |
|
| 158 |
// Pick a timestamp such that the expiration needs to wrap around the whole wheel. |
| 159 |
now := int64(time.Second) * wheelMask |
| 160 |
|
| 161 |
// Process expired tasks. |
| 162 |
expired := make(map[uint64]bool) |
| 163 |
hw.expireTasks(now, func(seq uint64, expires int64) bool { |
| 164 |
expired[seq] = true |
| 165 |
return true |
| 166 |
}) |
| 167 |
|
| 168 |
// Verify both sequences are expired. |
| 169 |
require_Equal(t, len(expired), 2) |
| 170 |
require_Equal(t, hw.count, 0) |
| 171 |
} |
| 172 |
|
| 173 |
func TestHashWheelNextExpiration(t *testing.T) { |
| 174 |
hw := NewHashWheel() |
| 175 |
now := time.Now() |
| 176 |
|
| 177 |
// Add sequences with different expiration times. |
| 178 |
seqs := map[uint64]int64{ |
| 179 |
1: now.Add(5 * time.Second).UnixNano(), |
| 180 |
2: now.Add(3 * time.Second).UnixNano(), // Earliest |
| 181 |
3: now.Add(10 * time.Second).UnixNano(), |
| 182 |
} |
| 183 |
|
| 184 |
for seq, expires := range seqs { |
| 185 |
require_NoError(t, hw.Add(seq, expires)) |
| 186 |
} |
| 187 |
require_Equal(t, hw.count, uint64(len(seqs))) |
| 188 |
|
| 189 |
// Test GetNextExpiration. |
| 190 |
nextExternalTick := now.Add(6 * time.Second).UnixNano() |
| 191 |
// Should return sequence 2's expiration |
| 192 |
require_Equal(t, hw.GetNextExpiration(nextExternalTick), seqs[2]) |
| 193 |
|
| 194 |
// Test with empty wheel. |
| 195 |
empty := NewHashWheel() |
| 196 |
require_Equal(t, empty.GetNextExpiration(now.Add(1*time.Second).UnixNano()), math.MaxInt64) |
| 197 |
} |
| 198 |
|
| 199 |
func TestHashWheelStress(t *testing.T) { |
| 200 |
hw := NewHashWheel() |
| 201 |
now := time.Now() |
| 202 |
|
| 203 |
// Add many sequences. |
| 204 |
numSequences := 100_000 |
| 205 |
for seq := 0; seq < numSequences; seq++ { |
| 206 |
expires := now.Add(time.Duration(seq) * time.Second).UnixNano() |
| 207 |
require_NoError(t, hw.Add(uint64(seq), expires)) |
| 208 |
} |
| 209 |
|
| 210 |
// Update many sequences. |
| 211 |
for seq := 0; seq < numSequences; seq += 2 { // Update every other sequence |
| 212 |
oldExpires := now.Add(time.Duration(seq) * time.Second).UnixNano() |
| 213 |
newExpires := now.Add(time.Duration(seq+numSequences) * time.Second).UnixNano() |
| 214 |
require_NoError(t, hw.Update(uint64(seq), oldExpires, newExpires)) |
| 215 |
} |
| 216 |
|
| 217 |
// Remove many sequences. |
| 218 |
for seq := 1; seq < numSequences; seq += 2 { // Remove odd-numbered sequences |
| 219 |
expires := now.Add(time.Duration(seq) * time.Second).UnixNano() |
| 220 |
require_NoError(t, hw.Remove(uint64(seq), expires)) |
| 221 |
} |
| 222 |
} |
| 223 |
|
| 224 |
func TestHashWheelEncodeDecode(t *testing.T) { |
| 225 |
hw := NewHashWheel() |
| 226 |
now := time.Now() |
| 227 |
|
| 228 |
// Add many sequences. |
| 229 |
numSequences := 100_000 |
| 230 |
for seq := 0; seq < numSequences; seq++ { |
| 231 |
expires := now.Add(time.Duration(seq) * time.Second).UnixNano() |
| 232 |
require_NoError(t, hw.Add(uint64(seq), expires)) |
| 233 |
} |
| 234 |
|
| 235 |
b := hw.Encode(12345) |
| 236 |
require_True(t, len(b) > 17) // Bigger than just the header |
| 237 |
|
| 238 |
nhw := NewHashWheel() |
| 239 |
stamp, err := nhw.Decode(b) |
| 240 |
require_NoError(t, err) |
| 241 |
require_Equal(t, stamp, 12345) |
| 242 |
require_Equal(t, hw.GetNextExpiration(math.MaxInt64), nhw.GetNextExpiration(math.MaxInt64)) |
| 243 |
|
| 244 |
for s, slot := range hw.wheel { |
| 245 |
nslot := nhw.wheel[s] |
| 246 |
require_Equal(t, slot.lowest, nslot.lowest) |
| 247 |
require_Equal(t, len(slot.entries), len(nslot.entries)) |
| 248 |
for v, ts := range slot.entries { |
| 249 |
nts, ok := nslot.entries[v] |
| 250 |
require_True(t, ok) |
| 251 |
require_Equal(t, ts, nts) |
| 252 |
} |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
func TestHashWheelDecodeRejectsMalformed(t *testing.T) { |
| 257 |
// Build a valid header that claims the given number of entries. |
| 258 |
header := func(count uint64) []byte { |
| 259 |
b := make([]byte, headerLen) |
| 260 |
b[0] = 1 // Magic version |
| 261 |
binary.LittleEndian.PutUint64(b[1:], count) // Entry count |
| 262 |
binary.LittleEndian.PutUint64(b[9:], 0) // High sequence stamp |
| 263 |
return b |
| 264 |
} |
| 265 |
|
| 266 |
for _, test := range []struct { |
| 267 |
title string |
| 268 |
buf []byte |
| 269 |
err error |
| 270 |
}{ |
| 271 |
{title: "ShortHeader", buf: make([]byte, headerLen-1), err: io.ErrShortBuffer}, |
| 272 |
{title: "BadVersion", buf: func() []byte { b := header(0); b[0] = 2; return b }(), err: ErrInvalidVersion}, |
| 273 |
// Claims one entry but the buffer ends right after the header. |
| 274 |
{title: "TruncatedAtVarints", buf: header(1), err: io.ErrUnexpectedEOF}, |
| 275 |
// Has the timestamp varint but the seq varint is missing. |
| 276 |
{title: "TruncatedSeq", buf: append(header(1), binary.AppendVarint(nil, 12345)...), err: io.ErrUnexpectedEOF}, |
| 277 |
} { |
| 278 |
t.Run(test.title, func(t *testing.T) { |
| 279 |
hw := NewHashWheel() |
| 280 |
_, err := hw.Decode(test.buf) |
| 281 |
require_Error(t, err, test.err) |
| 282 |
}) |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
// Benchmarks |
| 287 |
|
| 288 |
func BenchmarkHashWheel_Add(b *testing.B) { |
| 289 |
hw := NewHashWheel() |
| 290 |
now := time.Now() |
| 291 |
|
| 292 |
// Create different ranges for expires to spread across slots |
| 293 |
expires := make([]int64, b.N) |
| 294 |
for i := 0; i < b.N; i++ { |
| 295 |
expires[i] = now.Add(time.Duration(i%3600) * time.Second).UnixNano() |
| 296 |
} |
| 297 |
|
| 298 |
b.ResetTimer() |
| 299 |
for i := 0; i < b.N; i++ { |
| 300 |
hw.Add(uint64(i), expires[i]) |
| 301 |
} |
| 302 |
} |
| 303 |
|
| 304 |
func BenchmarkHashWheel_Add_SameSlot(b *testing.B) { |
| 305 |
hw := NewHashWheel() |
| 306 |
expires := time.Now().Add(time.Second).UnixNano() |
| 307 |
|
| 308 |
b.ResetTimer() |
| 309 |
for i := 0; i < b.N; i++ { |
| 310 |
hw.Add(uint64(i), expires) |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
func BenchmarkHashWheel_Update(b *testing.B) { |
| 315 |
hw := NewHashWheel() |
| 316 |
now := time.Now() |
| 317 |
|
| 318 |
// First add N items |
| 319 |
expires := make([]int64, b.N) |
| 320 |
for i := 0; i < b.N; i++ { |
| 321 |
expires[i] = now.Add(time.Duration(i%3600) * time.Second).UnixNano() |
| 322 |
hw.Add(uint64(i), expires[i]) |
| 323 |
} |
| 324 |
|
| 325 |
newExpires := now.Add(2 * time.Hour).UnixNano() |
| 326 |
b.ResetTimer() |
| 327 |
|
| 328 |
for i := 0; i < b.N; i++ { |
| 329 |
hw.Update(uint64(i), expires[i], newExpires) |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
func BenchmarkHashWheel_Update_SameSlot(b *testing.B) { |
| 334 |
hw := NewHashWheel() |
| 335 |
now := time.Now() |
| 336 |
oldExpires := now.Add(time.Second).UnixNano() |
| 337 |
newExpires := now.Add(2 * time.Second).UnixNano() |
| 338 |
|
| 339 |
// First add N items |
| 340 |
for i := 0; i < b.N; i++ { |
| 341 |
hw.Add(uint64(i), oldExpires) |
| 342 |
} |
| 343 |
|
| 344 |
b.ResetTimer() |
| 345 |
for i := 0; i < b.N; i++ { |
| 346 |
hw.Update(uint64(i), oldExpires, newExpires) |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
// Benchmark memory allocation |
| 351 |
func BenchmarkHashWheel_Add_Memory(b *testing.B) { |
| 352 |
b.ReportAllocs() |
| 353 |
hw := NewHashWheel() |
| 354 |
now := time.Now() |
| 355 |
|
| 356 |
expires := make([]int64, b.N) |
| 357 |
for i := 0; i < b.N; i++ { |
| 358 |
expires[i] = now.Add(time.Duration(i%3600) * time.Second).UnixNano() |
| 359 |
} |
| 360 |
|
| 361 |
b.ResetTimer() |
| 362 |
for i := 0; i < b.N; i++ { |
| 363 |
hw.Add(uint64(i), expires[i]) |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
// Large scale test |
| 368 |
func BenchmarkHashWheel_LargeScale(b *testing.B) { |
| 369 |
hw := NewHashWheel() |
| 370 |
now := time.Now() |
| 371 |
|
| 372 |
// Pre-populate with 100k items |
| 373 |
for i := 0; i < 100_000; i++ { |
| 374 |
expires := now.Add(time.Duration(i%3600) * time.Second).UnixNano() |
| 375 |
hw.Add(uint64(i), expires) |
| 376 |
} |
| 377 |
|
| 378 |
expires := make([]int64, b.N) |
| 379 |
for i := 0; i < b.N; i++ { |
| 380 |
expires[i] = now.Add(time.Duration(i%3600) * time.Second).UnixNano() |
| 381 |
} |
| 382 |
|
| 383 |
b.ResetTimer() |
| 384 |
for i := 0; i < b.N; i++ { |
| 385 |
hw.Add(uint64(i+100000), expires[i]) |
| 386 |
} |
| 387 |
} |