| 1 |
// Copyright 2022-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 |
// This test file is skipped by default to avoid accidentally running (e.g. `go test ./server`) |
| 15 |
//go:build !skip_js_tests && include_js_long_tests |
| 16 |
|
| 17 |
package server |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"math/rand" |
| 24 |
"slices" |
| 25 |
"strings" |
| 26 |
"sync" |
| 27 |
"sync/atomic" |
| 28 |
"testing" |
| 29 |
"time" |
| 30 |
|
| 31 |
"github.com/nats-io/nats.go" |
| 32 |
) |
| 33 |
|
| 34 |
// TestLongKVPutWithServerRestarts overwrites values in a replicated KV bucket for a fixed amount of time. |
| 35 |
// Also restarts a random server at fixed interval. |
| 36 |
// The test fails if updates fail for a continuous interval of time, or if a server fails to restart and catch up. |
| 37 |
func TestLongKVPutWithServerRestarts(t *testing.T) { |
| 38 |
// RNG Seed |
| 39 |
const Seed = 123456 |
| 40 |
// Number of keys in bucket |
| 41 |
const NumKeys = 1000 |
| 42 |
// Size of (random) values |
| 43 |
const ValueSize = 1024 |
| 44 |
// Test duration |
| 45 |
const Duration = 3 * time.Minute |
| 46 |
// If no updates successful for this interval, then fail the test |
| 47 |
const MaxRetry = 5 * time.Second |
| 48 |
// Minimum time between put operations |
| 49 |
const UpdatesInterval = 1 * time.Millisecond |
| 50 |
// Time between progress reports to console |
| 51 |
const ProgressInterval = 10 * time.Second |
| 52 |
// Time between server restarts |
| 53 |
const ServerRestartInterval = 5 * time.Second |
| 54 |
|
| 55 |
type Parameters struct { |
| 56 |
numServers int |
| 57 |
replicas int |
| 58 |
storage nats.StorageType |
| 59 |
} |
| 60 |
|
| 61 |
test := func(t *testing.T, p Parameters) { |
| 62 |
rng := rand.New(rand.NewSource(Seed)) |
| 63 |
|
| 64 |
// Create cluster |
| 65 |
clusterName := fmt.Sprintf("C_%d-%s", p.numServers, p.storage) |
| 66 |
cluster := createJetStreamClusterExplicit(t, clusterName, p.numServers) |
| 67 |
defer cluster.shutdown() |
| 68 |
|
| 69 |
// Connect to a random server but client will discover others too. |
| 70 |
nc, js := jsClientConnect(t, cluster.randomServer()) |
| 71 |
defer nc.Close() |
| 72 |
|
| 73 |
// Create bucket |
| 74 |
kv, err := js.CreateKeyValue(&nats.KeyValueConfig{ |
| 75 |
Bucket: "TEST", |
| 76 |
Replicas: p.replicas, |
| 77 |
Storage: p.storage, |
| 78 |
}) |
| 79 |
require_NoError(t, err) |
| 80 |
|
| 81 |
// Initialize list of keys |
| 82 |
keys := make([]string, NumKeys) |
| 83 |
for i := 0; i < NumKeys; i++ { |
| 84 |
keys[i] = fmt.Sprintf("key-%d", i) |
| 85 |
} |
| 86 |
|
| 87 |
// Initialize keys in bucket with an empty value |
| 88 |
for _, key := range keys { |
| 89 |
_, err := kv.Put(key, []byte{}) |
| 90 |
require_NoError(t, err) |
| 91 |
} |
| 92 |
|
| 93 |
// Track statistics |
| 94 |
var stats = struct { |
| 95 |
start time.Time |
| 96 |
lastSuccessfulUpdate time.Time |
| 97 |
updateOk uint64 |
| 98 |
updateErr uint64 |
| 99 |
restarts uint64 |
| 100 |
restartsMap map[string]int |
| 101 |
}{ |
| 102 |
start: time.Now(), |
| 103 |
lastSuccessfulUpdate: time.Now(), |
| 104 |
restartsMap: make(map[string]int, p.numServers), |
| 105 |
} |
| 106 |
for _, server := range cluster.servers { |
| 107 |
stats.restartsMap[server.Name()] = 0 |
| 108 |
} |
| 109 |
|
| 110 |
// Print statistics |
| 111 |
printProgress := func() { |
| 112 |
|
| 113 |
t.Logf( |
| 114 |
"[%s] %d updates %d errors, %d server restarts (%v)", |
| 115 |
time.Since(stats.start).Round(time.Second), |
| 116 |
stats.updateOk, |
| 117 |
stats.updateErr, |
| 118 |
stats.restarts, |
| 119 |
stats.restartsMap, |
| 120 |
) |
| 121 |
} |
| 122 |
|
| 123 |
// Print update on completion |
| 124 |
defer printProgress() |
| 125 |
|
| 126 |
// Pick a random key and update it with a random value |
| 127 |
valueBuffer := make([]byte, ValueSize) |
| 128 |
updateRandomKey := func() error { |
| 129 |
key := keys[rand.Intn(NumKeys)] |
| 130 |
_, err := rng.Read(valueBuffer) |
| 131 |
require_NoError(t, err) |
| 132 |
_, err = kv.Put(key, valueBuffer) |
| 133 |
return err |
| 134 |
} |
| 135 |
|
| 136 |
// Set up timers and tickers |
| 137 |
endTestTimer := time.After(Duration) |
| 138 |
nextUpdateTicker := time.NewTicker(UpdatesInterval) |
| 139 |
progressTicker := time.NewTicker(ProgressInterval) |
| 140 |
restartServerTicker := time.NewTicker(ServerRestartInterval) |
| 141 |
|
| 142 |
runLoop: |
| 143 |
for { |
| 144 |
select { |
| 145 |
|
| 146 |
case <-endTestTimer: |
| 147 |
break runLoop |
| 148 |
|
| 149 |
case <-nextUpdateTicker.C: |
| 150 |
err := updateRandomKey() |
| 151 |
if err == nil { |
| 152 |
stats.updateOk++ |
| 153 |
stats.lastSuccessfulUpdate = time.Now() |
| 154 |
} else { |
| 155 |
stats.updateErr++ |
| 156 |
if time.Since(stats.lastSuccessfulUpdate) > MaxRetry { |
| 157 |
t.Fatalf("Could not successfully update for over %s", MaxRetry) |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
case <-restartServerTicker.C: |
| 162 |
randomServer := cluster.servers[rng.Intn(len(cluster.servers))] |
| 163 |
randomServer.Shutdown() |
| 164 |
randomServer.WaitForShutdown() |
| 165 |
restartedServer := cluster.restartServer(randomServer) |
| 166 |
cluster.waitOnClusterReady() |
| 167 |
cluster.waitOnServerHealthz(restartedServer) |
| 168 |
cluster.waitOnAllCurrent() |
| 169 |
stats.restarts++ |
| 170 |
stats.restartsMap[randomServer.Name()]++ |
| 171 |
|
| 172 |
case <-progressTicker.C: |
| 173 |
printProgress() |
| 174 |
} |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
testCases := []Parameters{ |
| 179 |
{numServers: 5, replicas: 3, storage: nats.MemoryStorage}, |
| 180 |
{numServers: 5, replicas: 3, storage: nats.FileStorage}, |
| 181 |
} |
| 182 |
|
| 183 |
for _, testCase := range testCases { |
| 184 |
name := fmt.Sprintf("N:%d,R:%d,%s", testCase.numServers, testCase.replicas, testCase.storage) |
| 185 |
t.Run( |
| 186 |
name, |
| 187 |
func(t *testing.T) { test(t, testCase) }, |
| 188 |
) |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
// This is a RaftChainOfBlocks test that randomly starts and stops nodes to exercise recovery and snapshots. |
| 193 |
func TestLongNRGChainOfBlocks(t *testing.T) { |
| 194 |
const ( |
| 195 |
ClusterSize = 3 |
| 196 |
GroupSize = 3 |
| 197 |
ConvergenceTimeout = 30 * time.Second |
| 198 |
Duration = 10 * time.Minute |
| 199 |
PrintStateInterval = 3 * time.Second |
| 200 |
) |
| 201 |
|
| 202 |
// Create cluster |
| 203 |
c := createJetStreamClusterExplicit(t, "Test", ClusterSize) |
| 204 |
defer c.shutdown() |
| 205 |
|
| 206 |
rg := c.createRaftGroup("ChainOfBlocks", GroupSize, newRaftChainStateMachine) |
| 207 |
rg.waitOnLeader() |
| 208 |
|
| 209 |
// Available operations |
| 210 |
type TestOperation string |
| 211 |
const ( |
| 212 |
StopOne TestOperation = "Stop one active node" |
| 213 |
StopAll = "Stop all active nodes" |
| 214 |
RestartOne = "Restart one stopped node" |
| 215 |
RestartAll = "Restart all stopped nodes" |
| 216 |
Snapshot = "Snapshot one active node" |
| 217 |
Propose = "Propose a value via one active node" |
| 218 |
ProposeLeader = "Propose a value via leader" |
| 219 |
Pause = "Let things run undisturbed for a while" |
| 220 |
Check = "Wait for nodes to converge" |
| 221 |
) |
| 222 |
|
| 223 |
// Weighted distribution of operations, one is randomly chosen from this vector in each iteration |
| 224 |
opsWeighted := []TestOperation{ |
| 225 |
StopOne, |
| 226 |
StopOne, |
| 227 |
StopOne, |
| 228 |
StopAll, |
| 229 |
StopAll, |
| 230 |
RestartOne, |
| 231 |
RestartOne, |
| 232 |
RestartOne, |
| 233 |
RestartAll, |
| 234 |
RestartAll, |
| 235 |
RestartAll, |
| 236 |
Snapshot, |
| 237 |
Snapshot, |
| 238 |
Propose, |
| 239 |
Propose, |
| 240 |
Propose, |
| 241 |
Propose, |
| 242 |
ProposeLeader, |
| 243 |
ProposeLeader, |
| 244 |
ProposeLeader, |
| 245 |
ProposeLeader, |
| 246 |
Pause, |
| 247 |
Pause, |
| 248 |
Pause, |
| 249 |
Pause, |
| 250 |
Check, |
| 251 |
Check, |
| 252 |
Check, |
| 253 |
Check, |
| 254 |
} |
| 255 |
|
| 256 |
rngSeed := time.Now().UnixNano() |
| 257 |
rng := rand.New(rand.NewSource(rngSeed)) |
| 258 |
t.Logf("Seed: %d", rngSeed) |
| 259 |
|
| 260 |
// Chose a node from the list (and remove it) |
| 261 |
pickRandomNode := func(nodes []stateMachine) ([]stateMachine, stateMachine) { |
| 262 |
if len(nodes) == 0 { |
| 263 |
// Input list is empty |
| 264 |
return nodes, nil |
| 265 |
} |
| 266 |
// Pick random node |
| 267 |
i := rng.Intn(len(nodes)) |
| 268 |
node := nodes[i] |
| 269 |
// Move last element in its place |
| 270 |
nodes[i] = nodes[len(nodes)-1] |
| 271 |
// Return slice excluding last element |
| 272 |
return nodes[:len(nodes)-1], node |
| 273 |
} |
| 274 |
|
| 275 |
// Create summary status string for all replicas |
| 276 |
chainStatusString := func() string { |
| 277 |
b := strings.Builder{} |
| 278 |
for _, sm := range rg { |
| 279 |
csm := sm.(*RCOBStateMachine) |
| 280 |
running, blocksCount, blockHash := csm.getCurrentHash() |
| 281 |
if running { |
| 282 |
b.WriteString( |
| 283 |
fmt.Sprintf( |
| 284 |
" [%s (%s): %d blocks, hash=%s],", |
| 285 |
csm.server().Name(), |
| 286 |
csm.node().ID(), |
| 287 |
blocksCount, |
| 288 |
blockHash, |
| 289 |
), |
| 290 |
) |
| 291 |
} else { |
| 292 |
b.WriteString( |
| 293 |
fmt.Sprintf( |
| 294 |
" [%s (%s): STOPPED],", |
| 295 |
csm.server().Name(), |
| 296 |
csm.node().ID(), |
| 297 |
), |
| 298 |
) |
| 299 |
|
| 300 |
} |
| 301 |
} |
| 302 |
return b.String() |
| 303 |
} |
| 304 |
|
| 305 |
// Track the highest number of blocks applied by any of the replicas |
| 306 |
highestBlocksCount := uint64(0) |
| 307 |
|
| 308 |
// Track active and stopped nodes |
| 309 |
activeNodes := make([]stateMachine, 0, GroupSize) |
| 310 |
stoppedNodes := make([]stateMachine, 0, GroupSize) |
| 311 |
|
| 312 |
// Initially all nodes are active |
| 313 |
activeNodes = append(activeNodes, rg...) |
| 314 |
|
| 315 |
defer func() { |
| 316 |
t.Logf("Final state: %s", chainStatusString()) |
| 317 |
}() |
| 318 |
|
| 319 |
printStateTicker := time.NewTicker(PrintStateInterval) |
| 320 |
testTimer := time.NewTimer(Duration) |
| 321 |
start := time.Now() |
| 322 |
iteration := 0 |
| 323 |
stopCooldown := 0 |
| 324 |
|
| 325 |
for { |
| 326 |
|
| 327 |
iteration++ |
| 328 |
select { |
| 329 |
case <-printStateTicker.C: |
| 330 |
t.Logf( |
| 331 |
"[%s] State: %s", |
| 332 |
time.Since(start).Round(time.Second), |
| 333 |
chainStatusString(), |
| 334 |
) |
| 335 |
case <-testTimer.C: |
| 336 |
// Test completed |
| 337 |
return |
| 338 |
default: |
| 339 |
// Continue |
| 340 |
} |
| 341 |
|
| 342 |
// Choose a random operation to perform in this iteration |
| 343 |
nextOperation := opsWeighted[rng.Intn(len(opsWeighted))] |
| 344 |
|
| 345 |
// If we're about to stop one or all nodes, do some sanity checks to ensure we don't |
| 346 |
// spam stops which would constantly interrupt the chance of making progress. |
| 347 |
if nextOperation == StopOne || nextOperation == StopAll { |
| 348 |
if stopCooldown > 0 { |
| 349 |
nextOperation = Propose |
| 350 |
} else { |
| 351 |
stopCooldown = 50 |
| 352 |
} |
| 353 |
} |
| 354 |
if stopCooldown > 0 { |
| 355 |
stopCooldown-- |
| 356 |
} |
| 357 |
|
| 358 |
if RCOBOptions.verbose { |
| 359 |
t.Logf("Iteration %d: %s", iteration, nextOperation) |
| 360 |
} |
| 361 |
|
| 362 |
switch nextOperation { |
| 363 |
|
| 364 |
case StopOne: |
| 365 |
// Stop an active node (if any are left active) |
| 366 |
var n stateMachine |
| 367 |
activeNodes, n = pickRandomNode(activeNodes) |
| 368 |
if n != nil { |
| 369 |
n.stop() |
| 370 |
stoppedNodes = append(stoppedNodes, n) |
| 371 |
} |
| 372 |
|
| 373 |
case StopAll: |
| 374 |
// Stop all active nodes (if any are active) |
| 375 |
for _, node := range activeNodes { |
| 376 |
node.stop() |
| 377 |
} |
| 378 |
stoppedNodes = append(stoppedNodes, activeNodes...) |
| 379 |
activeNodes = make([]stateMachine, 0, GroupSize) |
| 380 |
|
| 381 |
case RestartOne: |
| 382 |
// Restart a stopped node (if any are stopped) |
| 383 |
var n stateMachine |
| 384 |
stoppedNodes, n = pickRandomNode(stoppedNodes) |
| 385 |
if n != nil { |
| 386 |
n.restart() |
| 387 |
activeNodes = append(activeNodes, n) |
| 388 |
} |
| 389 |
|
| 390 |
case RestartAll: |
| 391 |
// Restart all stopped nodes (if any) |
| 392 |
for _, node := range stoppedNodes { |
| 393 |
node.restart() |
| 394 |
} |
| 395 |
activeNodes = append(activeNodes, stoppedNodes...) |
| 396 |
stoppedNodes = make([]stateMachine, 0, GroupSize) |
| 397 |
|
| 398 |
case Snapshot: |
| 399 |
// Choose a random active node and tell it to create a snapshot |
| 400 |
if len(activeNodes) > 0 { |
| 401 |
n := activeNodes[rng.Intn(len(activeNodes))] |
| 402 |
n.(*RCOBStateMachine).createSnapshot() |
| 403 |
} |
| 404 |
|
| 405 |
case Propose: |
| 406 |
// Make an active node propose the next block (if any nodes are active) |
| 407 |
if len(activeNodes) > 0 { |
| 408 |
n := activeNodes[rng.Intn(len(activeNodes))] |
| 409 |
n.(*RCOBStateMachine).proposeBlock() |
| 410 |
} |
| 411 |
|
| 412 |
case ProposeLeader: |
| 413 |
// Make the leader propose the next block (if a leader is active) |
| 414 |
leader := rg.leader() |
| 415 |
if leader != nil { |
| 416 |
leader.(*RCOBStateMachine).proposeBlock() |
| 417 |
} |
| 418 |
|
| 419 |
case Pause: |
| 420 |
// Noop, let things run undisturbed for a little bit |
| 421 |
time.Sleep(time.Duration(rng.Intn(250)) * time.Millisecond) |
| 422 |
|
| 423 |
case Check: |
| 424 |
// Restart any stopped node |
| 425 |
for _, node := range stoppedNodes { |
| 426 |
node.restart() |
| 427 |
} |
| 428 |
activeNodes = append(activeNodes, stoppedNodes...) |
| 429 |
stoppedNodes = make([]stateMachine, 0, GroupSize) |
| 430 |
|
| 431 |
// Ensure all nodes (eventually) converge |
| 432 |
checkFor(t, ConvergenceTimeout, 250*time.Millisecond, |
| 433 |
func() error { |
| 434 |
referenceNode := rg[0] |
| 435 |
// Save block count and hash of first node as reference |
| 436 |
_, referenceBlocksCount, referenceHash := referenceNode.(*RCOBStateMachine).getCurrentHash() |
| 437 |
|
| 438 |
// Compare each node against reference |
| 439 |
for _, n := range rg { |
| 440 |
sm := n.(*RCOBStateMachine) |
| 441 |
running, blocksCount, blockHash := sm.getCurrentHash() |
| 442 |
if !running { |
| 443 |
return fmt.Errorf( |
| 444 |
"node not running: %s (%s)", |
| 445 |
sm.server().Name(), |
| 446 |
sm.node().ID(), |
| 447 |
) |
| 448 |
} |
| 449 |
|
| 450 |
// Track the highest block delivered by any node |
| 451 |
if blocksCount > highestBlocksCount { |
| 452 |
if RCOBOptions.verbose { |
| 453 |
t.Logf( |
| 454 |
"New highest blocks count: %d (%s (%s))", |
| 455 |
blocksCount, |
| 456 |
sm.s.Name(), |
| 457 |
sm.n.ID(), |
| 458 |
) |
| 459 |
} |
| 460 |
highestBlocksCount = blocksCount |
| 461 |
} |
| 462 |
|
| 463 |
// Each replica must match the reference node |
| 464 |
|
| 465 |
if blocksCount != referenceBlocksCount { |
| 466 |
return fmt.Errorf( |
| 467 |
"different number of blocks %d (%s (%s) vs. %d (%s (%s))", |
| 468 |
blocksCount, |
| 469 |
sm.server().Name(), |
| 470 |
sm.node().ID(), |
| 471 |
referenceBlocksCount, |
| 472 |
referenceNode.server().Name(), |
| 473 |
referenceNode.node().ID(), |
| 474 |
) |
| 475 |
} else if blockHash != referenceHash { |
| 476 |
return fmt.Errorf( |
| 477 |
"different hash after %d blocks %s (%s (%s) vs. %s (%s (%s))", |
| 478 |
blocksCount, |
| 479 |
blockHash, |
| 480 |
sm.server().Name(), |
| 481 |
sm.node().ID(), |
| 482 |
referenceHash, |
| 483 |
referenceNode.server().Name(), |
| 484 |
referenceNode.node().ID(), |
| 485 |
) |
| 486 |
} |
| 487 |
} |
| 488 |
|
| 489 |
// Verify consistency check was against the highest block known |
| 490 |
if referenceBlocksCount < highestBlocksCount { |
| 491 |
return fmt.Errorf( |
| 492 |
"nodes converged below highest known block count: %d: %s", |
| 493 |
highestBlocksCount, |
| 494 |
chainStatusString(), |
| 495 |
) |
| 496 |
} |
| 497 |
|
| 498 |
// All nodes reached the same state, check passed |
| 499 |
return nil |
| 500 |
}, |
| 501 |
) |
| 502 |
} |
| 503 |
} |
| 504 |
} |
| 505 |
|
| 506 |
func TestLongClusterWorkQueueMessagesNotSkipped(t *testing.T) { |
| 507 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 508 |
defer c.shutdown() |
| 509 |
|
| 510 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 511 |
defer nc.Close() |
| 512 |
|
| 513 |
iterations := 500_000 |
| 514 |
stream := "s1" |
| 515 |
subjf := "subj.>" |
| 516 |
consumers := map[string]string{ |
| 517 |
"c1": "subj.c1", |
| 518 |
"c2": "subj.c2.*", |
| 519 |
"c3": "subj.c3", |
| 520 |
} |
| 521 |
|
| 522 |
sig := make(chan *nats.Msg, 900) |
| 523 |
|
| 524 |
_, err := js.AddStream(&nats.StreamConfig{ |
| 525 |
Name: stream, |
| 526 |
Storage: nats.FileStorage, |
| 527 |
Subjects: []string{subjf}, |
| 528 |
Retention: nats.WorkQueuePolicy, |
| 529 |
Duplicates: time.Minute * 2, |
| 530 |
Replicas: 3, |
| 531 |
MaxAge: time.Hour, |
| 532 |
}) |
| 533 |
require_NoError(t, err) |
| 534 |
|
| 535 |
for name, subjf := range consumers { |
| 536 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 537 |
defer nc.Close() |
| 538 |
|
| 539 |
_, err = js.AddConsumer(stream, &nats.ConsumerConfig{ |
| 540 |
Name: name, |
| 541 |
FilterSubject: subjf, |
| 542 |
Replicas: 3, |
| 543 |
AckPolicy: nats.AckExplicitPolicy, |
| 544 |
DeliverPolicy: nats.DeliverAllPolicy, |
| 545 |
}) |
| 546 |
require_NoError(t, err) |
| 547 |
|
| 548 |
ps, err := js.PullSubscribe(subjf, "", nats.Bind(stream, name)) |
| 549 |
require_NoError(t, err) |
| 550 |
|
| 551 |
go func() { |
| 552 |
for { |
| 553 |
msgs, err := ps.FetchBatch(300) |
| 554 |
if errors.Is(err, nats.ErrTimeout) { |
| 555 |
continue |
| 556 |
} |
| 557 |
if errors.Is(err, nats.ErrConnectionClosed) || errors.Is(err, nats.ErrSubscriptionClosed) { |
| 558 |
return // ... for when the test finishes |
| 559 |
} |
| 560 |
require_NoError(t, err) |
| 561 |
for msg := range msgs.Messages() { |
| 562 |
go func() { |
| 563 |
time.Sleep(time.Millisecond * time.Duration(rand.Int31n(100))) |
| 564 |
require_NoError(t, msg.Ack()) |
| 565 |
sig <- msg |
| 566 |
}() |
| 567 |
} |
| 568 |
} |
| 569 |
}() |
| 570 |
} |
| 571 |
|
| 572 |
go func() { |
| 573 |
hdrs := nats.Header{} |
| 574 |
for i := 1; i <= iterations; i++ { |
| 575 |
// Pick a random consumer to hit this time (map iteration order is |
| 576 |
// non-deterministic, but break to do it just once). |
| 577 |
for _, subj := range consumers { |
| 578 |
hdrs.Set("Nats-Msg-Id", fmt.Sprintf("msg-%d", i)) |
| 579 |
if strings.HasPrefix(subj, "*") { |
| 580 |
subj = strings.Replace(subj, "*", fmt.Sprintf("%d", i), 1) |
| 581 |
} |
| 582 |
_, err := js.PublishMsg(&nats.Msg{ |
| 583 |
Subject: subj, |
| 584 |
Header: hdrs, |
| 585 |
}) |
| 586 |
require_NoError(t, err) |
| 587 |
break |
| 588 |
} |
| 589 |
} |
| 590 |
}() |
| 591 |
|
| 592 |
for i := 1; i <= iterations; i++ { |
| 593 |
if i%10000 == 0 { |
| 594 |
t.Logf("%d messages out of %d", i, iterations) |
| 595 |
} |
| 596 |
|
| 597 |
select { |
| 598 |
case <-sig: |
| 599 |
case <-time.After(time.Second * 2): |
| 600 |
si, err := js.StreamInfo(stream) |
| 601 |
require_NoError(t, err) |
| 602 |
t.Logf("Stream info: %+v", si.State) |
| 603 |
|
| 604 |
for name := range consumers { |
| 605 |
ci, err := js.ConsumerInfo(stream, name) |
| 606 |
require_NoError(t, err) |
| 607 |
t.Logf("Consumer %q info: %+v, %+v", name, ci.AckFloor, ci.Delivered) |
| 608 |
} |
| 609 |
|
| 610 |
t.Fatalf("Didn't receive message %d", i) |
| 611 |
} |
| 612 |
} |
| 613 |
} |
| 614 |
|
| 615 |
func TestLongClusterJetStreamKeyValueSync(t *testing.T) { |
| 616 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 617 |
defer c.shutdown() |
| 618 |
|
| 619 |
for _, s := range c.servers { |
| 620 |
s.optsMu.Lock() |
| 621 |
s.opts.LameDuckDuration = 15 * time.Second |
| 622 |
s.opts.LameDuckGracePeriod = -15 * time.Second |
| 623 |
s.optsMu.Unlock() |
| 624 |
} |
| 625 |
s := c.randomNonLeader() |
| 626 |
connect := func(t *testing.T) (*nats.Conn, nats.JetStreamContext) { |
| 627 |
return jsClientConnect(t, s) |
| 628 |
} |
| 629 |
|
| 630 |
const accountName = "$G" |
| 631 |
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" |
| 632 |
createData := func(n int) []byte { |
| 633 |
b := make([]byte, n) |
| 634 |
for i := range b { |
| 635 |
b[i] = letterBytes[rand.Intn(len(letterBytes))] |
| 636 |
} |
| 637 |
return b |
| 638 |
} |
| 639 |
getOrCreateKvStore := func(kvname string) (nats.KeyValue, error) { |
| 640 |
_, js := connect(t) |
| 641 |
kvExists := false |
| 642 |
existingKvnames := js.KeyValueStoreNames() |
| 643 |
for existingKvname := range existingKvnames { |
| 644 |
if existingKvname == kvname { |
| 645 |
kvExists = true |
| 646 |
break |
| 647 |
} |
| 648 |
} |
| 649 |
if !kvExists { |
| 650 |
return js.CreateKeyValue(&nats.KeyValueConfig{ |
| 651 |
Bucket: kvname, |
| 652 |
Replicas: 3, |
| 653 |
Storage: nats.FileStorage, |
| 654 |
}) |
| 655 |
} else { |
| 656 |
return js.KeyValue(kvname) |
| 657 |
} |
| 658 |
} |
| 659 |
abs := func(x int64) int64 { |
| 660 |
if x < 0 { |
| 661 |
return -x |
| 662 |
} |
| 663 |
return x |
| 664 |
} |
| 665 |
var counter int64 |
| 666 |
var errorCounter int64 |
| 667 |
|
| 668 |
checkMsgsEqual := func(t *testing.T, accountName, streamName string) error { |
| 669 |
// Gather all the streams replicas and compare contents. |
| 670 |
msets := make(map[*Server]*stream) |
| 671 |
for _, s := range c.servers { |
| 672 |
acc, err := s.LookupAccount(accountName) |
| 673 |
if err != nil { |
| 674 |
return err |
| 675 |
} |
| 676 |
mset, err := acc.lookupStream(streamName) |
| 677 |
if err != nil { |
| 678 |
return err |
| 679 |
} |
| 680 |
msets[s] = mset |
| 681 |
} |
| 682 |
|
| 683 |
str := getStreamDetails(t, c, accountName, streamName) |
| 684 |
if str == nil { |
| 685 |
return fmt.Errorf("could not get stream leader state") |
| 686 |
} |
| 687 |
state := str.State |
| 688 |
for seq := state.FirstSeq; seq <= state.LastSeq; seq++ { |
| 689 |
var msgId string |
| 690 |
var smv StoreMsg |
| 691 |
for replica, mset := range msets { |
| 692 |
mset.mu.RLock() |
| 693 |
sm, err := mset.store.LoadMsg(seq, &smv) |
| 694 |
mset.mu.RUnlock() |
| 695 |
if err != nil { |
| 696 |
if err == ErrStoreMsgNotFound || err == errDeletedMsg { |
| 697 |
// Skip these. |
| 698 |
} else { |
| 699 |
t.Logf("WRN: Error loading message (seq=%d) from stream %q on replica %q: %v", seq, streamName, replica, err) |
| 700 |
} |
| 701 |
continue |
| 702 |
} |
| 703 |
if msgId == _EMPTY_ { |
| 704 |
msgId = string(sm.hdr) |
| 705 |
} else if msgId != string(sm.hdr) { |
| 706 |
t.Errorf("MsgIds do not match for seq %d on stream %q: %q vs %q", seq, streamName, msgId, sm.hdr) |
| 707 |
} |
| 708 |
} |
| 709 |
} |
| 710 |
return nil |
| 711 |
} |
| 712 |
|
| 713 |
keyUpdater := func(ctx context.Context, cancel context.CancelFunc, kvname string, numKeys int) { |
| 714 |
kv, err := getOrCreateKvStore(kvname) |
| 715 |
if err != nil { |
| 716 |
t.Fatalf("[%s]:%v", kvname, err) |
| 717 |
} |
| 718 |
for i := 0; i < numKeys; i++ { |
| 719 |
key := fmt.Sprintf("key-%d", i) |
| 720 |
kv.Create(key, createData(160)) |
| 721 |
} |
| 722 |
lastData := make(map[string][]byte) |
| 723 |
revisions := make(map[string]uint64) |
| 724 |
for { |
| 725 |
select { |
| 726 |
case <-ctx.Done(): |
| 727 |
return |
| 728 |
default: |
| 729 |
} |
| 730 |
r := rand.Intn(numKeys) |
| 731 |
key := fmt.Sprintf("key-%d", r) |
| 732 |
|
| 733 |
for i := 0; i < 5; i++ { |
| 734 |
_, err := kv.Get(key) |
| 735 |
if err != nil { |
| 736 |
atomic.AddInt64(&errorCounter, 1) |
| 737 |
if err == nats.ErrKeyNotFound { |
| 738 |
t.Logf("WRN: Key not found! [%s/%s] - [%s]", kvname, key, err) |
| 739 |
cancel() |
| 740 |
} |
| 741 |
} |
| 742 |
} |
| 743 |
|
| 744 |
k, err := kv.Get(key) |
| 745 |
if err != nil { |
| 746 |
atomic.AddInt64(&errorCounter, 1) |
| 747 |
} else { |
| 748 |
if revisions[key] != 0 && abs(int64(k.Revision())-int64(revisions[key])) < 2 { |
| 749 |
lastDataVal, ok := lastData[key] |
| 750 |
if ok && k.Revision() == revisions[key] && slices.Compare(lastDataVal, k.Value()) != 0 { |
| 751 |
t.Logf("data loss [%s/%s][rev:%d] expected:[%v] is:[%v]", kvname, key, revisions[key], string(lastDataVal), string(k.Value())) |
| 752 |
} |
| 753 |
} |
| 754 |
newData := createData(160) |
| 755 |
revisions[key], err = kv.Update(key, newData, k.Revision()) |
| 756 |
if err != nil && err != nats.ErrTimeout { |
| 757 |
atomic.AddInt64(&errorCounter, 1) |
| 758 |
} else { |
| 759 |
lastData[key] = newData |
| 760 |
} |
| 761 |
atomic.AddInt64(&counter, 1) |
| 762 |
} |
| 763 |
} |
| 764 |
} |
| 765 |
|
| 766 |
streamCount := 50 |
| 767 |
keysCount := 100 |
| 768 |
streamPrefix := "IKV" |
| 769 |
|
| 770 |
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) |
| 771 |
defer cancel() |
| 772 |
|
| 773 |
// The keyUpdaters will run for less time. |
| 774 |
kctx, kcancel := context.WithTimeout(context.Background(), 3*time.Minute) |
| 775 |
defer kcancel() |
| 776 |
|
| 777 |
var wg sync.WaitGroup |
| 778 |
var streams []string |
| 779 |
for i := 0; i < streamCount; i++ { |
| 780 |
streamName := fmt.Sprintf("%s-%d", streamPrefix, i) |
| 781 |
streams = append(streams, "KV_"+streamName) |
| 782 |
|
| 783 |
wg.Add(1) |
| 784 |
go func(i int) { |
| 785 |
defer wg.Done() |
| 786 |
keyUpdater(kctx, cancel, streamName, keysCount) |
| 787 |
}(i) |
| 788 |
} |
| 789 |
|
| 790 |
debug := false |
| 791 |
nc2, _ := jsClientConnect(t, s) |
| 792 |
if debug { |
| 793 |
go func() { |
| 794 |
for range time.NewTicker(5 * time.Second).C { |
| 795 |
select { |
| 796 |
case <-ctx.Done(): |
| 797 |
return |
| 798 |
default: |
| 799 |
} |
| 800 |
for _, str := range streams { |
| 801 |
leaderSrv := c.streamLeader(accountName, str) |
| 802 |
if leaderSrv == nil { |
| 803 |
continue |
| 804 |
} |
| 805 |
streamLeader := getStreamDetails(t, c, accountName, str) |
| 806 |
if streamLeader == nil { |
| 807 |
continue |
| 808 |
} |
| 809 |
t.Logf("|------------------------------------------------------------------------------------------------------------------------|") |
| 810 |
lstate := streamLeader.State |
| 811 |
t.Logf("| %-10s | %-10s | msgs:%-10d | bytes:%-10d | deleted:%-10d | first:%-10d | last:%-10d |", |
| 812 |
str, leaderSrv.String()+"*", lstate.Msgs, lstate.Bytes, lstate.NumDeleted, lstate.FirstSeq, lstate.LastSeq, |
| 813 |
) |
| 814 |
for _, srv := range c.servers { |
| 815 |
if srv == leaderSrv { |
| 816 |
continue |
| 817 |
} |
| 818 |
acc, err := srv.LookupAccount(accountName) |
| 819 |
if err != nil { |
| 820 |
continue |
| 821 |
} |
| 822 |
stream, err := acc.lookupStream(str) |
| 823 |
if err != nil { |
| 824 |
t.Logf("Error looking up stream %s on %s replica", str, srv) |
| 825 |
continue |
| 826 |
} |
| 827 |
state := stream.state() |
| 828 |
|
| 829 |
unsynced := lstate.Msgs != state.Msgs || lstate.Bytes != state.Bytes || |
| 830 |
lstate.NumDeleted != state.NumDeleted || lstate.FirstSeq != state.FirstSeq || lstate.LastSeq != state.LastSeq |
| 831 |
|
| 832 |
var result string |
| 833 |
if unsynced { |
| 834 |
result = "UNSYNCED" |
| 835 |
} |
| 836 |
t.Logf("| %-10s | %-10s | msgs:%-10d | bytes:%-10d | deleted:%-10d | first:%-10d | last:%-10d | %s", |
| 837 |
str, srv, state.Msgs, state.Bytes, state.NumDeleted, state.FirstSeq, state.LastSeq, result, |
| 838 |
) |
| 839 |
} |
| 840 |
} |
| 841 |
t.Logf("|------------------------------------------------------------------------------------------------------------------------| %v", nc2.ConnectedUrl()) |
| 842 |
} |
| 843 |
}() |
| 844 |
} |
| 845 |
|
| 846 |
checkStreams := func(t *testing.T) { |
| 847 |
for _, str := range streams { |
| 848 |
checkFor(t, time.Minute, 500*time.Millisecond, func() error { |
| 849 |
return checkState(t, c, accountName, str) |
| 850 |
}) |
| 851 |
checkFor(t, time.Minute, 500*time.Millisecond, func() error { |
| 852 |
return checkMsgsEqual(t, accountName, str) |
| 853 |
}) |
| 854 |
} |
| 855 |
} |
| 856 |
|
| 857 |
Loop: |
| 858 |
for range time.NewTicker(30 * time.Second).C { |
| 859 |
select { |
| 860 |
case <-ctx.Done(): |
| 861 |
break Loop |
| 862 |
default: |
| 863 |
} |
| 864 |
rollout := func(t *testing.T) { |
| 865 |
for _, s := range c.servers { |
| 866 |
// For graceful mode |
| 867 |
s.lameDuckMode() |
| 868 |
s.WaitForShutdown() |
| 869 |
s = c.restartServer(s) |
| 870 |
|
| 871 |
hctx, hcancel := context.WithTimeout(context.Background(), 15*time.Second) |
| 872 |
defer hcancel() |
| 873 |
|
| 874 |
Healthz: |
| 875 |
for range time.NewTicker(2 * time.Second).C { |
| 876 |
select { |
| 877 |
case <-hctx.Done(): |
| 878 |
default: |
| 879 |
} |
| 880 |
|
| 881 |
status := s.healthz(nil) |
| 882 |
if status.StatusCode == 200 { |
| 883 |
break Healthz |
| 884 |
} |
| 885 |
} |
| 886 |
c.waitOnClusterReady() |
| 887 |
checkStreams(t) |
| 888 |
} |
| 889 |
} |
| 890 |
rollout(t) |
| 891 |
checkStreams(t) |
| 892 |
} |
| 893 |
wg.Wait() |
| 894 |
checkStreams(t) |
| 895 |
} |
| 896 |
|
| 897 |
func TestLongClusterCLFSOnDuplicates(t *testing.T) { |
| 898 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 899 |
defer c.shutdown() |
| 900 |
|
| 901 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 902 |
defer nc.Close() |
| 903 |
|
| 904 |
nc2, js2 := jsClientConnect(t, c.randomServer()) |
| 905 |
defer nc2.Close() |
| 906 |
|
| 907 |
streamName := "TESTW" |
| 908 |
_, err := js.AddStream(&nats.StreamConfig{ |
| 909 |
Name: streamName, |
| 910 |
Subjects: []string{"foo"}, |
| 911 |
Replicas: 3, |
| 912 |
Storage: nats.FileStorage, |
| 913 |
MaxAge: 3 * time.Minute, |
| 914 |
Duplicates: 2 * time.Minute, |
| 915 |
}) |
| 916 |
require_NoError(t, err) |
| 917 |
|
| 918 |
c.waitOnStreamLeader(globalAccountName, streamName) |
| 919 |
|
| 920 |
var wg sync.WaitGroup |
| 921 |
|
| 922 |
// The test will be successful if it runs for this long without dup issues. |
| 923 |
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) |
| 924 |
defer cancel() |
| 925 |
|
| 926 |
go func() { |
| 927 |
tick := time.NewTicker(10 * time.Second) |
| 928 |
for { |
| 929 |
select { |
| 930 |
case <-ctx.Done(): |
| 931 |
wg.Done() |
| 932 |
return |
| 933 |
case <-tick.C: |
| 934 |
c.streamLeader(globalAccountName, streamName).JetStreamStepdownStream(globalAccountName, streamName) |
| 935 |
} |
| 936 |
} |
| 937 |
}() |
| 938 |
wg.Add(1) |
| 939 |
|
| 940 |
for i := 0; i < 5; i++ { |
| 941 |
go func(i int) { |
| 942 |
var err error |
| 943 |
sub, err := js2.PullSubscribe("foo", fmt.Sprintf("A:%d", i)) |
| 944 |
require_NoError(t, err) |
| 945 |
|
| 946 |
for { |
| 947 |
select { |
| 948 |
case <-ctx.Done(): |
| 949 |
wg.Done() |
| 950 |
return |
| 951 |
default: |
| 952 |
} |
| 953 |
|
| 954 |
msgs, err := sub.Fetch(100, nats.MaxWait(200*time.Millisecond)) |
| 955 |
if err != nil { |
| 956 |
continue |
| 957 |
} |
| 958 |
for _, msg := range msgs { |
| 959 |
msg.Ack() |
| 960 |
} |
| 961 |
} |
| 962 |
}(i) |
| 963 |
wg.Add(1) |
| 964 |
} |
| 965 |
|
| 966 |
// Sync producer that only does a couple of duplicates, cancel the test |
| 967 |
// if we get too many errors without responses. |
| 968 |
errCh := make(chan error, 10) |
| 969 |
go func() { |
| 970 |
// Try sync publishes normally in this state and see if it times out. |
| 971 |
for i := 0; ; i++ { |
| 972 |
select { |
| 973 |
case <-ctx.Done(): |
| 974 |
wg.Done() |
| 975 |
return |
| 976 |
default: |
| 977 |
} |
| 978 |
|
| 979 |
var succeeded bool |
| 980 |
var failures int |
| 981 |
for n := 0; n < 10; n++ { |
| 982 |
_, err := js.Publish( |
| 983 |
"foo", []byte("test"), |
| 984 |
nats.MsgId(fmt.Sprintf("sync:checking:%d", i)), |
| 985 |
nats.RetryAttempts(30), |
| 986 |
nats.AckWait(500*time.Millisecond), |
| 987 |
) |
| 988 |
if err != nil { |
| 989 |
failures++ |
| 990 |
continue |
| 991 |
} |
| 992 |
succeeded = true |
| 993 |
} |
| 994 |
if !succeeded { |
| 995 |
errCh <- fmt.Errorf("Too many publishes failed with timeout: failures=%d, i=%d", failures, i) |
| 996 |
} |
| 997 |
} |
| 998 |
}() |
| 999 |
wg.Add(1) |
| 1000 |
|
| 1001 |
Loop: |
| 1002 |
for n := uint64(0); true; n++ { |
| 1003 |
select { |
| 1004 |
case <-ctx.Done(): |
| 1005 |
break Loop |
| 1006 |
case e := <-errCh: |
| 1007 |
t.Error(e) |
| 1008 |
break Loop |
| 1009 |
default: |
| 1010 |
} |
| 1011 |
// Cause a lot of duplicates very fast until producer stalls. |
| 1012 |
for i := 0; i < 128; i++ { |
| 1013 |
msgID := nats.MsgId(fmt.Sprintf("id.%d.%d", n, i)) |
| 1014 |
js.PublishAsync("foo", []byte("test"), msgID, nats.RetryAttempts(10)) |
| 1015 |
} |
| 1016 |
} |
| 1017 |
cancel() |
| 1018 |
wg.Wait() |
| 1019 |
} |
| 1020 |
|
| 1021 |
func TestLongClusterJetStreamRestartThenScaleStreamReplicas(t *testing.T) { |
| 1022 |
t.Skip("This test takes too long, need to make shorter") |
| 1023 |
|
| 1024 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 1025 |
defer c.shutdown() |
| 1026 |
|
| 1027 |
s := c.randomNonLeader() |
| 1028 |
nc, js := jsClientConnect(t, s) |
| 1029 |
defer nc.Close() |
| 1030 |
|
| 1031 |
nc2, producer := jsClientConnect(t, s) |
| 1032 |
defer nc2.Close() |
| 1033 |
|
| 1034 |
_, err := js.AddStream(&nats.StreamConfig{ |
| 1035 |
Name: "TEST", |
| 1036 |
Subjects: []string{"foo"}, |
| 1037 |
Replicas: 3, |
| 1038 |
}) |
| 1039 |
require_NoError(t, err) |
| 1040 |
c.waitOnStreamLeader(globalAccountName, "TEST") |
| 1041 |
|
| 1042 |
ctx, cancel := context.WithCancel(context.Background()) |
| 1043 |
defer cancel() |
| 1044 |
|
| 1045 |
end := time.Now().Add(2 * time.Second) |
| 1046 |
for time.Now().Before(end) { |
| 1047 |
producer.Publish("foo", []byte(strings.Repeat("A", 128))) |
| 1048 |
time.Sleep(time.Millisecond) |
| 1049 |
} |
| 1050 |
|
| 1051 |
var wg sync.WaitGroup |
| 1052 |
for i := 0; i < 5; i++ { |
| 1053 |
sub, err := js.PullSubscribe("foo", fmt.Sprintf("C-%d", i)) |
| 1054 |
require_NoError(t, err) |
| 1055 |
|
| 1056 |
wg.Add(1) |
| 1057 |
go func() { |
| 1058 |
defer wg.Done() |
| 1059 |
for range time.NewTicker(10 * time.Millisecond).C { |
| 1060 |
select { |
| 1061 |
case <-ctx.Done(): |
| 1062 |
return |
| 1063 |
default: |
| 1064 |
} |
| 1065 |
|
| 1066 |
msgs, err := sub.Fetch(1) |
| 1067 |
if err != nil && !errors.Is(err, nats.ErrTimeout) && !errors.Is(err, nats.ErrConnectionClosed) { |
| 1068 |
t.Logf("Pull Error: %v", err) |
| 1069 |
} |
| 1070 |
for _, msg := range msgs { |
| 1071 |
msg.Ack() |
| 1072 |
} |
| 1073 |
} |
| 1074 |
}() |
| 1075 |
} |
| 1076 |
c.lameDuckRestartAll() |
| 1077 |
c.waitOnStreamLeader(globalAccountName, "TEST") |
| 1078 |
|
| 1079 |
// Swap the logger to try to detect the condition after the restart. |
| 1080 |
loggers := make([]*captureDebugLogger, 3) |
| 1081 |
for i, srv := range c.servers { |
| 1082 |
l := &captureDebugLogger{dbgCh: make(chan string, 10)} |
| 1083 |
loggers[i] = l |
| 1084 |
srv.SetLogger(l, true, false) |
| 1085 |
} |
| 1086 |
condition := `Direct proposal ignored, not leader (state: CLOSED)` |
| 1087 |
errCh := make(chan error, 10) |
| 1088 |
|
| 1089 |
wg.Add(1) |
| 1090 |
go func() { |
| 1091 |
defer wg.Done() |
| 1092 |
for { |
| 1093 |
select { |
| 1094 |
case dl := <-loggers[0].dbgCh: |
| 1095 |
if strings.Contains(dl, condition) { |
| 1096 |
errCh <- errors.New(condition) |
| 1097 |
} |
| 1098 |
case dl := <-loggers[1].dbgCh: |
| 1099 |
if strings.Contains(dl, condition) { |
| 1100 |
errCh <- errors.New(condition) |
| 1101 |
} |
| 1102 |
case dl := <-loggers[2].dbgCh: |
| 1103 |
if strings.Contains(dl, condition) { |
| 1104 |
errCh <- errors.New(condition) |
| 1105 |
} |
| 1106 |
case <-ctx.Done(): |
| 1107 |
return |
| 1108 |
} |
| 1109 |
} |
| 1110 |
}() |
| 1111 |
|
| 1112 |
// Start publishing again for a while. |
| 1113 |
end = time.Now().Add(2 * time.Second) |
| 1114 |
for time.Now().Before(end) { |
| 1115 |
producer.Publish("foo", []byte(strings.Repeat("A", 128))) |
| 1116 |
time.Sleep(time.Millisecond) |
| 1117 |
} |
| 1118 |
|
| 1119 |
// Try to do a stream edit back to R=1 after doing all the upgrade. |
| 1120 |
info, _ := js.StreamInfo("TEST") |
| 1121 |
sconfig := info.Config |
| 1122 |
sconfig.Replicas = 1 |
| 1123 |
_, err = js.UpdateStream(&sconfig) |
| 1124 |
require_NoError(t, err) |
| 1125 |
|
| 1126 |
// Leave running for some time after the update. |
| 1127 |
time.Sleep(2 * time.Second) |
| 1128 |
|
| 1129 |
info, _ = js.StreamInfo("TEST") |
| 1130 |
sconfig = info.Config |
| 1131 |
sconfig.Replicas = 3 |
| 1132 |
_, err = js.UpdateStream(&sconfig) |
| 1133 |
require_NoError(t, err) |
| 1134 |
|
| 1135 |
select { |
| 1136 |
case e := <-errCh: |
| 1137 |
t.Fatalf("Bad condition on raft node: %v", e) |
| 1138 |
case <-time.After(2 * time.Second): |
| 1139 |
// Done |
| 1140 |
} |
| 1141 |
|
| 1142 |
// Stop goroutines and wait for them to exit. |
| 1143 |
cancel() |
| 1144 |
wg.Wait() |
| 1145 |
} |
| 1146 |
|
| 1147 |
func TestLongFileStoreEnforceMsgPerSubjectLimit(t *testing.T) { |
| 1148 |
td := t.TempDir() |
| 1149 |
fs, err := newFileStore( |
| 1150 |
FileStoreConfig{StoreDir: td, BlockSize: 1024}, |
| 1151 |
StreamConfig{ |
| 1152 |
Name: "zzz", Subjects: []string{"test.>"}, Storage: FileStorage, |
| 1153 |
}, |
| 1154 |
) |
| 1155 |
require_NoError(t, err) |
| 1156 |
defer fs.Stop() |
| 1157 |
|
| 1158 |
t.Logf("Starting publishes") |
| 1159 |
for i := 0; i < 100_000; i++ { |
| 1160 |
_, _, err := fs.StoreMsg(fmt.Sprintf("test.%06d", i), nil, nil, 0) |
| 1161 |
require_NoError(t, err) |
| 1162 |
} |
| 1163 |
// Now update some of them. Leave a bit of a mess with some big gaps. |
| 1164 |
for i := 0; i < 5_000_000; i++ { |
| 1165 |
n := rand.Int31n(100_000) |
| 1166 |
if n < 5000 { |
| 1167 |
continue |
| 1168 |
} |
| 1169 |
_, _, err := fs.StoreMsg(fmt.Sprintf("test.%06d", n), nil, nil, 0) |
| 1170 |
require_NoError(t, err) |
| 1171 |
} |
| 1172 |
t.Logf("Publish complete") |
| 1173 |
|
| 1174 |
require_NoError(t, fs.Stop()) |
| 1175 |
fs, err = newFileStore( |
| 1176 |
FileStoreConfig{StoreDir: td, BlockSize: 1024}, |
| 1177 |
StreamConfig{ |
| 1178 |
Name: "zzz", Subjects: []string{"test.>"}, Storage: FileStorage, |
| 1179 |
MaxMsgsPer: 1, |
| 1180 |
}, |
| 1181 |
) |
| 1182 |
require_NoError(t, err) |
| 1183 |
defer fs.Stop() |
| 1184 |
|
| 1185 |
// Mangle the filestore state and then see how long it takes to enforce |
| 1186 |
// the per-subject limit. |
| 1187 |
fs.state.Msgs++ |
| 1188 |
start := time.Now() |
| 1189 |
fs.enforceMsgPerSubjectLimit(false) |
| 1190 |
require_LessThan(t, time.Since(start), time.Minute) |
| 1191 |
t.Logf("Took %s", time.Since(start)) |
| 1192 |
} |