Debian Codegraph @

jetstream/jetstream_test.go

raw
1 // Copyright 2022-2023 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 jetstream
15
16 import (
17 "errors"
18 "fmt"
19 "testing"
20 "time"
21
22 "github.com/nats-io/nats.go"
23 )
24
25 func TestMessageMetadata(t *testing.T) {
26 tests := []struct {
27 name string
28 givenReply string
29 expectedMetadata MsgMetadata
30 withError error
31 }{
32 {
33 name: "valid metadata",
34 givenReply: "$JS.ACK.domain.hash-123.stream.cons.5.10.20.123456789.1.token",
35 expectedMetadata: MsgMetadata{
36 Sequence: SequencePair{
37 Consumer: 20,
38 Stream: 10,
39 },
40 NumDelivered: 5,
41 NumPending: 1,
42 Timestamp: time.Unix(0, 123456789),
43 Stream: "stream",
44 Consumer: "cons",
45 Domain: "domain",
46 },
47 },
48 {
49 name: "no reply subject",
50 givenReply: "",
51 withError: ErrMsgNoReply,
52 },
53 {
54 name: "not a JetStream message",
55 givenReply: "ABC",
56 withError: ErrNotJSMessage,
57 },
58 }
59
60 for _, test := range tests {
61 t.Run(test.name, func(t *testing.T) {
62 msg := &jetStreamMsg{
63 msg: &nats.Msg{
64 Reply: test.givenReply,
65 Sub: &nats.Subscription{},
66 },
67 }
68 res, err := msg.Metadata()
69 if test.withError != nil {
70 if err == nil || !errors.Is(err, test.withError) {
71 t.Fatalf("Expected error: %v; got: %v", test.withError, err)
72 }
73 return
74 }
75 if err != nil {
76 t.Fatalf("Unexpected error: %v", err)
77 }
78 if *res != test.expectedMetadata {
79 t.Fatalf("Invalid metadata; want: %v; got: %v", test.expectedMetadata, res)
80 }
81 })
82 }
83 }
84
85 func TestValidateSubject(t *testing.T) {
86 tests := []struct {
87 subject string
88 withError bool
89 }{
90 {"test.A", false},
91 {"test.*", false},
92 {"*", false},
93 {"*.*", false},
94 {"test.*.A", false},
95 {"test.>", false},
96 {">", false},
97 {">.", true},
98 {"test.>.A", true},
99 {"", true},
100 {"test A", true},
101 }
102
103 for _, test := range tests {
104 tName := fmt.Sprintf("subj=%s,err=%t", test.subject, test.withError)
105 t.Run(tName, func(t *testing.T) {
106 err := validateSubject(test.subject)
107 if test.withError {
108 if err == nil {
109 t.Fatal("Expected error; got nil")
110 }
111 return
112 }
113 if err != nil {
114 t.Fatalf("Unexpected error: %v", err)
115 }
116 })
117 }
118 }
119
120 func TestValidateStreamName(t *testing.T) {
121 tests := []struct {
122 name string
123 withError bool
124 }{
125 {"test", false},
126 {"test-stream_1", false},
127 {"", true},
128 {"stream.name", true},
129 {"stream name", true},
130 {"stream>", true},
131 {"stream*", true},
132 {"stream/name", true},
133 {"stream\\name", true},
134 {"stream\tname", true},
135 {"stream\rname", true},
136 {"stream\nname", true},
137 }
138
139 for _, test := range tests {
140 t.Run(fmt.Sprintf("name=%q,err=%t", test.name, test.withError), func(t *testing.T) {
141 err := validateStreamName(test.name)
142 if test.withError {
143 if err == nil {
144 t.Fatal("Expected error; got nil")
145 }
146 return
147 }
148 if err != nil {
149 t.Fatalf("Unexpected error: %v", err)
150 }
151 })
152 }
153 }
154
155 func TestValidateConsumerName(t *testing.T) {
156 tests := []struct {
157 name string
158 withError bool
159 }{
160 {"test", false},
161 {"test-consumer_1", false},
162 {"", true},
163 {"consumer.name", true},
164 {"consumer name", true},
165 {"consumer>", true},
166 {"consumer*", true},
167 {"consumer/name", true},
168 {"consumer\\name", true},
169 {"consumer\tname", true},
170 {"consumer\rname", true},
171 {"consumer\nname", true},
172 }
173
174 for _, test := range tests {
175 t.Run(fmt.Sprintf("name=%q,err=%t", test.name, test.withError), func(t *testing.T) {
176 err := validateConsumerName(test.name)
177 if test.withError {
178 if err == nil {
179 t.Fatal("Expected error; got nil")
180 }
181 return
182 }
183 if err != nil {
184 t.Fatalf("Unexpected error: %v", err)
185 }
186 })
187 }
188 }
189
190 func TestRetryWithBackoff(t *testing.T) {
191 tests := []struct {
192 name string
193 givenOpts backoffOpts
194 withError bool
195 timeout time.Duration
196 cancelAfter time.Duration
197 successfulAttemptNum int
198 expectedAttemptsCount int
199 }{
200 {
201 name: "infinite attempts, 5 tries before success",
202 givenOpts: backoffOpts{
203 attempts: -1,
204 initialInterval: 10 * time.Millisecond,
205 maxInterval: 60 * time.Millisecond,
206 },
207 withError: false,
208 successfulAttemptNum: 5,
209 // 0ms + 10ms + 20ms + 40ms + 60ms = 130ms
210 timeout: 200 * time.Millisecond,
211 expectedAttemptsCount: 5,
212 },
213 {
214 name: "infinite attempts, 5 tries before success, without initial execution",
215 givenOpts: backoffOpts{
216 attempts: -1,
217 initialInterval: 10 * time.Millisecond,
218 disableInitialExecution: true,
219 factor: 2,
220 maxInterval: 60 * time.Millisecond,
221 },
222 withError: false,
223 successfulAttemptNum: 5,
224 // 10ms + 20ms + 40ms + 60ms + 60 = 190ms
225 timeout: 250 * time.Millisecond,
226 expectedAttemptsCount: 5,
227 },
228 {
229 name: "5 attempts, unsuccessful",
230 givenOpts: backoffOpts{
231 attempts: 5,
232 initialInterval: 10 * time.Millisecond,
233 factor: 2,
234 maxInterval: 60 * time.Millisecond,
235 },
236 withError: true,
237 // 0ms + 10ms + 20ms + 40ms + 60ms = 130ms
238 timeout: 200 * time.Millisecond,
239 expectedAttemptsCount: 5,
240 },
241 {
242 name: "custom backoff values, should override other settings",
243 givenOpts: backoffOpts{
244 initialInterval: 2 * time.Second,
245 factor: 2,
246 maxInterval: 100 * time.Millisecond,
247 customBackoff: []time.Duration{10 * time.Millisecond, 20 * time.Millisecond, 30 * time.Millisecond, 40 * time.Millisecond, 50 * time.Millisecond},
248 },
249 withError: false,
250 successfulAttemptNum: 4,
251 // 10ms + 20ms + 30ms + 40ms = 100ms
252 timeout: 150 * time.Millisecond,
253 expectedAttemptsCount: 4,
254 },
255 {
256 name: "no custom backoff, with cancel",
257 givenOpts: backoffOpts{
258 attempts: -1,
259 initialInterval: 100 * time.Millisecond,
260 factor: 1,
261 },
262 withError: false,
263 cancelAfter: 150 * time.Millisecond,
264 timeout: 200 * time.Millisecond,
265 expectedAttemptsCount: 2,
266 },
267 {
268 name: "custom backoff, with cancel",
269 givenOpts: backoffOpts{
270 customBackoff: []time.Duration{100 * time.Millisecond, 100 * time.Millisecond, 100 * time.Millisecond},
271 },
272 cancelAfter: 150 * time.Millisecond,
273 expectedAttemptsCount: 1,
274 timeout: 200 * time.Millisecond,
275 },
276 {
277 name: "attempts num not provided",
278 givenOpts: backoffOpts{
279 initialInterval: 100 * time.Millisecond,
280 factor: 1,
281 },
282 withError: true,
283 timeout: 1 * time.Second,
284 expectedAttemptsCount: 1,
285 },
286 {
287 name: "custom backoff, but attempts num provided",
288 givenOpts: backoffOpts{
289 customBackoff: []time.Duration{100 * time.Millisecond, 100 * time.Millisecond, 100 * time.Millisecond},
290 attempts: 5,
291 },
292 withError: true,
293 timeout: 1 * time.Second,
294 expectedAttemptsCount: 1,
295 },
296 }
297
298 for _, test := range tests {
299 t.Run(test.name, func(t *testing.T) {
300 ok := make(chan struct{})
301 errs := make(chan error, 1)
302
303 var cancelChan chan struct{}
304 if test.cancelAfter != 0 {
305 cancelChan = make(chan struct{})
306 test.givenOpts.cancel = cancelChan
307 }
308 var count int
309 go func() {
310 err := retryWithBackoff(func(attempt int) (bool, error) {
311 count = attempt
312 if test.successfulAttemptNum != 0 && attempt == test.successfulAttemptNum-1 {
313 return false, nil
314 }
315 return true, fmt.Errorf("error %d", attempt)
316 }, test.givenOpts)
317 if err != nil {
318 errs <- err
319 return
320 }
321 close(ok)
322 }()
323 if test.cancelAfter > 0 {
324 go func() {
325 time.Sleep(test.cancelAfter)
326 close(cancelChan)
327 }()
328 }
329 select {
330 case <-ok:
331 if test.withError {
332 t.Fatal("Expected error; got nil")
333 }
334 case err := <-errs:
335 if !test.withError {
336 t.Fatalf("Unexpected error: %v", err)
337 }
338 case <-time.After(test.timeout):
339 t.Fatalf("Timeout after %v", test.timeout)
340 }
341
342 if count != test.expectedAttemptsCount-1 {
343 t.Fatalf("Invalid count; got: %d, want: %d", count, test.expectedAttemptsCount-1)
344 }
345 })
346 }
347 }
348
349 func TestPullConsumer_checkPending(t *testing.T) {
350
351 tests := []struct {
352 name string
353 givenSub *pullSubscription
354 fetchInProgress bool
355 shouldSend bool
356 expectedPullRequest *pullRequest
357 }{
358 {
359 name: "msgs threshold not reached, bytes not set, no pull request",
360 givenSub: &pullSubscription{
361 pending: pendingMsgs{
362 msgCount: 10,
363 },
364 consumeOpts: &consumeOpts{
365 ThresholdMessages: 5,
366 MaxMessages: 10,
367 },
368 },
369 shouldSend: false,
370 },
371 {
372 name: "pending msgs below threshold, send pull request",
373 givenSub: &pullSubscription{
374 pending: pendingMsgs{
375 msgCount: 4,
376 byteCount: 400, // byte count should be ignored
377 },
378 consumeOpts: &consumeOpts{
379 ThresholdMessages: 5,
380 MaxMessages: 10,
381 },
382 },
383 shouldSend: true,
384 expectedPullRequest: &pullRequest{
385 Batch: 6,
386 MaxBytes: 0,
387 },
388 },
389 {
390 name: "pending msgs below threshold but PR in progress",
391 givenSub: &pullSubscription{
392 pending: pendingMsgs{
393 msgCount: 4,
394 },
395 consumeOpts: &consumeOpts{
396 ThresholdMessages: 5,
397 MaxMessages: 10,
398 },
399 },
400 fetchInProgress: true,
401 shouldSend: false,
402 },
403 {
404 name: "pending bytes below threshold, send pull request",
405 givenSub: &pullSubscription{
406 pending: pendingMsgs{
407 byteCount: 400,
408 msgCount: 1000000, // msgs count should be ignored
409 },
410 consumeOpts: &consumeOpts{
411 MaxMessages: 1000000,
412 ThresholdBytes: 500,
413 MaxBytes: 1000,
414 },
415 },
416 shouldSend: true,
417 expectedPullRequest: &pullRequest{
418 Batch: 1000000,
419 MaxBytes: 600,
420 },
421 },
422 {
423 name: "pending bytes above threshold, no pull request",
424 givenSub: &pullSubscription{
425 pending: pendingMsgs{
426 byteCount: 600,
427 },
428 consumeOpts: &consumeOpts{
429 ThresholdBytes: 500,
430 MaxBytes: 1000,
431 },
432 },
433 shouldSend: false,
434 },
435 {
436 name: "pending bytes below threshold, fetch in progress, no pull request",
437 givenSub: &pullSubscription{
438 pending: pendingMsgs{
439 byteCount: 400,
440 },
441 consumeOpts: &consumeOpts{
442 ThresholdBytes: 500,
443 MaxBytes: 1000,
444 },
445 },
446 fetchInProgress: true,
447 shouldSend: false,
448 },
449 {
450 name: "StopAfter set, pending msgs below StopAfter, send pull request",
451 givenSub: &pullSubscription{
452 pending: pendingMsgs{
453 msgCount: 4,
454 },
455 consumeOpts: &consumeOpts{
456 ThresholdMessages: 5,
457 MaxMessages: 10,
458 StopAfter: 8,
459 },
460 delivered: 2,
461 },
462 shouldSend: true,
463 expectedPullRequest: &pullRequest{
464 Batch: 2, // StopAfter (8) - delivered (2) - pending (4)
465 MaxBytes: 0,
466 },
467 },
468 {
469 name: "StopAfter set, pending msgs equal to StopAfter, no pull request",
470 givenSub: &pullSubscription{
471 pending: pendingMsgs{
472 msgCount: 6,
473 },
474 consumeOpts: &consumeOpts{
475 ThresholdMessages: 5,
476 MaxMessages: 10,
477 StopAfter: 6,
478 },
479 delivered: 0,
480 },
481 shouldSend: false,
482 },
483 }
484
485 for _, test := range tests {
486 t.Run(test.name, func(t *testing.T) {
487 prChan := make(chan *pullRequest, 1)
488 test.givenSub.fetchNext = prChan
489 if test.fetchInProgress {
490 test.givenSub.fetchInProgress.Store(1)
491 }
492 errs := make(chan error, 1)
493 ok := make(chan struct{}, 1)
494 go func() {
495 if test.shouldSend {
496 select {
497 case pr := <-prChan:
498 if *pr != *test.expectedPullRequest {
499 errs <- fmt.Errorf("Invalid pull request; want: %#v; got: %#v", test.expectedPullRequest, pr)
500 return
501 }
502 ok <- struct{}{}
503 case <-time.After(1 * time.Second):
504 errs <- errors.New("Timeout")
505 return
506 }
507 } else {
508 select {
509 case <-prChan:
510 errs <- errors.New("Unexpected pull request")
511 case <-time.After(100 * time.Millisecond):
512 ok <- struct{}{}
513 return
514 }
515 }
516 }()
517
518 test.givenSub.checkPending()
519 select {
520 case <-ok:
521 // ok
522 case err := <-errs:
523 t.Fatal(err)
524 }
525
526 })
527 }
528 }
529
530 func TestIsWrongLastSeqErr(t *testing.T) {
531 // 10164 is the replicated-stream variant of the 10071 "wrong last
532 // sequence" CAS conflict; both must be recognized (issue #2097).
533 for _, code := range []ErrorCode{JSErrCodeStreamWrongLastSequence, JSErrCodeStreamWrongLastSequenceConstant} {
534 if !isWrongLastSeqErr(&APIError{Code: 400, ErrorCode: code}) {
535 t.Fatalf("err code %d should be recognized as wrong-last-sequence", code)
536 }
537 }
538 if isWrongLastSeqErr(&APIError{Code: 404, ErrorCode: JSErrCodeStreamNotFound}) {
539 t.Fatal("unrelated error code should not be recognized")
540 }
541 }
542
543 func TestMapRevisionMismatch(t *testing.T) {
544 // Both 10071 and its replicated-stream variant 10164 must map to
545 // ErrKeyRevisionMismatch, while preserving the underlying
546 // APIError for callers that inspect the code.
547 for _, code := range []ErrorCode{JSErrCodeStreamWrongLastSequence, JSErrCodeStreamWrongLastSequenceConstant} {
548 err := mapRevisionMismatch(&APIError{Code: 400, ErrorCode: code})
549 if !errors.Is(err, ErrKeyRevisionMismatch) {
550 t.Fatalf("err code %d should map to ErrKeyRevisionMismatch, got: %v", code, err)
551 }
552 var apiErr *APIError
553 if !errors.As(err, &apiErr) || apiErr.ErrorCode != code {
554 t.Fatalf("underlying APIError (code %d) should be preserved, got: %v", code, err)
555 }
556 }
557
558 // Unrelated errors pass through untouched.
559 other := &APIError{Code: 404, ErrorCode: JSErrCodeStreamNotFound}
560 if err := mapRevisionMismatch(other); err != other || errors.Is(err, ErrKeyRevisionMismatch) {
561 t.Fatalf("unrelated error should pass through unchanged, got: %v", err)
562 }
563
564 if mapRevisionMismatch(nil) != nil {
565 t.Fatal("nil should map to nil")
566 }
567 }
568
569 func TestKV_keyValid(t *testing.T) {
570 tests := []struct {
571 key string
572 ok bool
573 }{
574 {key: "foo123", ok: true},
575 {key: "foo.bar", ok: true},
576 {key: "Foo.123=bar_baz-abc", ok: true},
577 {key: "foo.*.bar", ok: false},
578 {key: "foo.>", ok: false},
579 {key: ">", ok: false},
580 {key: "*", ok: false},
581 {key: "foo!", ok: false},
582 {key: "foo bar", ok: false},
583 {key: "", ok: false},
584 {key: " ", ok: false},
585 {key: ".", ok: false},
586 {key: ".foo", ok: false},
587 {key: "foo.", ok: false},
588 }
589
590 for _, test := range tests {
591 t.Run(test.key, func(t *testing.T) {
592 res := keyValid(test.key)
593 if res != test.ok {
594 t.Fatalf("Invalid result; want: %v; got: %v", test.ok, res)
595 }
596 })
597 }
598 }
599
600 func TestKV_searchKeyValid(t *testing.T) {
601 tests := []struct {
602 key string
603 ok bool
604 }{
605 {key: "foo123", ok: true},
606 {key: "foo.bar", ok: true},
607 {key: "Foo.123=bar_baz-abc", ok: true},
608 {key: "foo.*.bar", ok: true},
609 {key: "foo.>", ok: true},
610 {key: ">", ok: true},
611 {key: "*", ok: true},
612 {key: "foo!", ok: false},
613 {key: "foo bar", ok: false},
614 {key: "", ok: false},
615 {key: " ", ok: false},
616 {key: ".", ok: false},
617 {key: ".foo", ok: false},
618 {key: "foo.", ok: false},
619 }
620
621 for _, test := range tests {
622 t.Run(test.key, func(t *testing.T) {
623 res := searchKeyValid(test.key)
624 if res != test.ok {
625 t.Fatalf("Invalid result; want: %v; got: %v", test.ok, res)
626 }
627 })
628 }
629 }
630
631 func TestKV_bucketValid(t *testing.T) {
632 tests := []struct {
633 key string
634 ok bool
635 }{
636 {key: "foo123", ok: true},
637 {key: "Foo123-bar_baz", ok: true},
638 {key: "foo.bar", ok: false},
639 {key: "foo.*.bar", ok: false},
640 {key: "foo.>", ok: false},
641 {key: ">", ok: false},
642 {key: "*", ok: false},
643 {key: "foo!", ok: false},
644 {key: "foo bar", ok: false},
645 {key: "", ok: false},
646 {key: " ", ok: false},
647 {key: ".", ok: false},
648 {key: ".foo", ok: false},
649 {key: "foo.", ok: false},
650 }
651
652 for _, test := range tests {
653 t.Run(test.key, func(t *testing.T) {
654 res := bucketValid(test.key)
655 if res != test.ok {
656 t.Fatalf("Invalid result; want: %v; got: %v", test.ok, res)
657 }
658 })
659 }
660 }