Debian Codegraph @

js_test.go

raw
1 // Copyright 2012-2026 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 nats
15
16 ////////////////////////////////////////////////////////////////////////////////
17 // Package scoped specific tests here..
18 ////////////////////////////////////////////////////////////////////////////////
19
20 import (
21 "errors"
22 "fmt"
23 "strings"
24 "testing"
25 )
26
27 func TestIsWrongLastSeqErr(t *testing.T) {
28 // 10164 is the replicated-stream variant of the 10071 "wrong last
29 // sequence" CAS conflict; both must be recognized (issue #2097).
30 for _, code := range []ErrorCode{JSErrCodeStreamWrongLastSequence, JSErrCodeStreamWrongLastSequenceConstant} {
31 if !isWrongLastSeqErr(&APIError{Code: 400, ErrorCode: code}) {
32 t.Fatalf("err code %d should be recognized as wrong-last-sequence", code)
33 }
34 }
35 if isWrongLastSeqErr(&APIError{Code: 404, ErrorCode: JSErrCodeStreamNotFound}) {
36 t.Fatal("unrelated error code should not be recognized")
37 }
38 }
39
40 func TestMapRevisionMismatch(t *testing.T) {
41 // Both 10071 and its replicated-stream variant 10164 must map to
42 // ErrKeyRevisionMismatch, while preserving the underlying
43 // APIError for callers that inspect the code.
44 for _, code := range []ErrorCode{JSErrCodeStreamWrongLastSequence, JSErrCodeStreamWrongLastSequenceConstant} {
45 err := mapRevisionMismatch(&APIError{Code: 400, ErrorCode: code})
46 if !errors.Is(err, ErrKeyRevisionMismatch) {
47 t.Fatalf("err code %d should map to ErrKeyRevisionMismatch, got: %v", code, err)
48 }
49 var apiErr *APIError
50 if !errors.As(err, &apiErr) || apiErr.ErrorCode != code {
51 t.Fatalf("underlying APIError (code %d) should be preserved, got: %v", code, err)
52 }
53 }
54
55 // Unrelated errors pass through untouched.
56 other := &APIError{Code: 404, ErrorCode: JSErrCodeStreamNotFound}
57 if err := mapRevisionMismatch(other); err != other || errors.Is(err, ErrKeyRevisionMismatch) {
58 t.Fatalf("unrelated error should pass through unchanged, got: %v", err)
59 }
60
61 if mapRevisionMismatch(nil) != nil {
62 t.Fatal("nil should map to nil")
63 }
64 }
65
66 func TestJetStreamConvertDirectMsgResponseToMsg(t *testing.T) {
67 // This test checks the conversion of a "direct get message" response
68 // to a JS message based on the content of specific NATS headers.
69 // It is very specific to the order headers retrieval is made in
70 // convertDirectGetMsgResponseToMsg(), so it may need adjustment
71 // if changes are made there.
72
73 msg := NewMsg("inbox")
74
75 check := func(errTxt string) {
76 t.Helper()
77 m, err := convertDirectGetMsgResponseToMsg("test", msg)
78 if err == nil || !strings.Contains(err.Error(), errTxt) {
79 t.Fatalf("Expected error contain %q, got %v", errTxt, err)
80 }
81 if m != nil {
82 t.Fatalf("Expected nil message, got %v", m)
83 }
84 }
85
86 check("should have headers")
87
88 msg.Header.Set(statusHdr, noMessagesSts)
89 check(ErrMsgNotFound.Error())
90
91 msg.Header.Set(statusHdr, reqTimeoutSts)
92 check("unable to get message")
93
94 msg.Header.Set(descrHdr, "some error text")
95 check("some error text")
96
97 msg.Header.Del(statusHdr)
98 msg.Header.Del(descrHdr)
99 msg.Header.Set("some", "header")
100 check("missing stream")
101
102 msg.Header.Set(JSStream, "test")
103 check("missing sequence")
104
105 msg.Header.Set(JSSequence, "abc")
106 check("invalid sequence")
107
108 msg.Header.Set(JSSequence, "1")
109 check("missing timestamp")
110
111 msg.Header.Set(JSTimeStamp, "aaaaaaaaa bbbbbbbbbbbb cccccccccc ddddddddddd eeeeeeeeee ffffff")
112 check("invalid timestamp")
113
114 msg.Header.Set(JSTimeStamp, "2006-01-02 15:04:05.999999999 +0000 UTC")
115 check("missing subject")
116
117 msg.Header.Set(JSSubject, "foo")
118 r, err := convertDirectGetMsgResponseToMsg("test", msg)
119 if err != nil {
120 t.Fatalf("Error during convert: %v", err)
121 }
122 if r.Subject != "foo" {
123 t.Fatalf("Expected subject to be 'foo', got %q", r.Subject)
124 }
125 if r.Sequence != 1 {
126 t.Fatalf("Expected sequence to be 1, got %v", r.Sequence)
127 }
128 if r.Time.UnixNano() != 0xFC4A4D639917BFF {
129 t.Fatalf("Invalid timestamp: %v", r.Time.UnixNano())
130 }
131 if r.Header.Get("some") != "header" {
132 t.Fatalf("Wrong header: %v", r.Header)
133 }
134 }
135
136 func TestApplyNewSIDUnregisteredSub(t *testing.T) {
137 newConn := func() (*Conn, *Subscription) {
138 nc := &Conn{subs: make(map[int64]*Subscription)}
139 sub := &Subscription{conn: nc}
140 nc.ssid++
141 sub.sid = nc.ssid
142 nc.subs[sub.sid] = sub
143 return nc, sub
144 }
145
146 t.Run("registered sub is re-keyed", func(t *testing.T) {
147 nc, sub := newConn()
148 sub.mu.Lock()
149 osid, nsid, ok := sub.applyNewSID()
150 sub.mu.Unlock()
151 if !ok {
152 t.Fatal("expected the sid swap to succeed for a registered sub")
153 }
154 if osid != 1 || nsid != 2 {
155 t.Fatalf("expected sids 1 -> 2, got %d -> %d", osid, nsid)
156 }
157 if sub.sid != nsid || nc.subs[nsid] != sub || len(nc.subs) != 1 {
158 t.Fatalf("sub not registered under the new sid only: sid=%d subs=%v", sub.sid, nc.subs)
159 }
160 })
161
162 t.Run("removed sub is not re-registered", func(t *testing.T) {
163 // Simulates removeSub winning the race: the sub was unsubscribed
164 // while applyNewSID had released sub.mu.
165 nc, sub := newConn()
166 delete(nc.subs, sub.sid)
167 sub.mu.Lock()
168 _, _, ok := sub.applyNewSID()
169 sub.mu.Unlock()
170 if ok {
171 t.Fatal("expected the sid swap to be refused for an unregistered sub")
172 }
173 if len(nc.subs) != 0 {
174 t.Fatalf("unsubscribed sub was resurrected in the subs map: %v", nc.subs)
175 }
176 if sub.sid != 1 {
177 t.Fatalf("sid of an unregistered sub should be untouched, got %d", sub.sid)
178 }
179 })
180
181 t.Run("closed connection does not panic", func(t *testing.T) {
182 // close() sets nc.subs to nil, and writing to a nil map panics.
183 nc, sub := newConn()
184 nc.subs = nil
185 sub.mu.Lock()
186 _, _, ok := sub.applyNewSID()
187 sub.mu.Unlock()
188 if ok {
189 t.Fatal("expected the sid swap to be refused on a closed connection")
190 }
191 })
192 }
193
194 func TestRewireOrderedSub(t *testing.T) {
195 const osid, nsid, deliver, maxStr = 1, 2, "_INBOX.new", "5"
196 newConn := func() (*Conn, *Subscription) {
197 // A writer with a large limit never flushes, so the protocol lines
198 // stay in bufs for inspection.
199 nc := &Conn{subs: make(map[int64]*Subscription), bw: &natsWriter{limit: 1 << 20}}
200 sub := &Subscription{conn: nc, sid: nsid}
201 nc.ssid = nsid
202 nc.subs[nsid] = sub
203 return nc, sub
204 }
205 unsubOld := fmt.Sprintf(unsubProto, osid, _EMPTY_)
206 subNew := fmt.Sprintf(subProto, deliver, _EMPTY_, nsid)
207 unsubMax := fmt.Sprintf(unsubProto, nsid, maxStr)
208
209 t.Run("registered sub is moved to the new sid", func(t *testing.T) {
210 nc, sub := newConn()
211 if !nc.rewireOrderedSub(sub, osid, nsid, deliver, maxStr) {
212 t.Fatal("expected the rewire to proceed for a registered sub")
213 }
214 if got, want := string(nc.bw.bufs), unsubOld+subNew+unsubMax; got != want {
215 t.Fatalf("unexpected protocol:\n got %q\nwant %q", got, want)
216 }
217 })
218
219 t.Run("removed sub only gets the old sid unsubscribed", func(t *testing.T) {
220 // Simulates Unsubscribe landing between applyNewSID and the
221 // goroutine that sends the protocol: it removed the sub under the
222 // new sid, so no interest (nor consumer) must be created for it.
223 nc, sub := newConn()
224 delete(nc.subs, nsid)
225 if nc.rewireOrderedSub(sub, osid, nsid, deliver, maxStr) {
226 t.Fatal("expected the rewire to be refused for an unregistered sub")
227 }
228 if got, want := string(nc.bw.bufs), unsubOld; got != want {
229 t.Fatalf("unexpected protocol:\n got %q\nwant %q", got, want)
230 }
231 })
232
233 t.Run("draining sub only gets the old sid unsubscribed", func(t *testing.T) {
234 // A draining sub stays in nc.subs until the drain completes, and it
235 // is then removed without an UNSUB, so subscribing the new sid would
236 // leave interest on the server for the life of the connection.
237 nc, sub := newConn()
238 sub.draining = true
239 if nc.rewireOrderedSub(sub, osid, nsid, deliver, maxStr) {
240 t.Fatal("expected the rewire to be refused for a draining sub")
241 }
242 if got, want := string(nc.bw.bufs), unsubOld; got != want {
243 t.Fatalf("unexpected protocol:\n got %q\nwant %q", got, want)
244 }
245 })
246
247 t.Run("closed connection only gets the old sid unsubscribed", func(t *testing.T) {
248 nc, sub := newConn()
249 nc.subs = nil
250 if nc.rewireOrderedSub(sub, osid, nsid, deliver, maxStr) {
251 t.Fatal("expected the rewire to be refused on a closed connection")
252 }
253 if got, want := string(nc.bw.bufs), unsubOld; got != want {
254 t.Fatalf("unexpected protocol:\n got %q\nwant %q", got, want)
255 }
256 })
257 }