Debian Codegraph @

jetstream/test/testservice_helper_test.go

raw
1 // Copyright 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 test
15
16 import (
17 "context"
18 "errors"
19 "fmt"
20 "net/url"
21 "os"
22 "strings"
23 "sync"
24 "testing"
25 "time"
26
27 "github.com/nats-io/nats.go"
28 "github.com/nats-io/nats.go/jetstream"
29 testservice "github.com/synadia-io/orbit.go/ntf-client"
30 )
31
32 // testserviceHost returns the hostname clients use to reach the tester (and
33 // the servers it spawns). Used by cross-domain leafnode tests that need to
34 // embed the hub host:port in the leaf's remotes.
35 func testserviceHost(t *testing.T) string {
36 t.Helper()
37 u, err := url.Parse(testerURL)
38 if err != nil {
39 t.Fatalf("could not parse tester URL %q: %v", testerURL, err)
40 }
41 return u.Hostname()
42 }
43
44 // emptyAccountsBody clears the built-in USERS1..USERS5 / $SYS accounts block.
45 func emptyAccountsBody() string {
46 return `# accounts block intentionally empty`
47 }
48
49 // noSystemAccountBody clears the built-in `system_account: "$SYS"` line.
50 func noSystemAccountBody() string {
51 return `# system_account intentionally unset`
52 }
53
54 // testerProbe caches a one-time reachability check of the tester service so
55 // that when it is down, every test fails fast with one actionable message
56 // instead of its own raw dial error.
57 var testerProbe struct {
58 once sync.Once
59 err error
60 }
61
62 // testerURL is set by TestMain: TESTER_NATS_URL when set, otherwise the
63 // in-process tester it started.
64 var testerURL string
65
66 // newTester returns a tester Client connected to the tester service. Close is
67 // registered with t.Cleanup.
68 func newTester(t testing.TB) *testservice.Client {
69 t.Helper()
70 testerProbe.once.Do(func() {
71 nc, err := nats.Connect(testerURL)
72 if err != nil {
73 testerProbe.err = fmt.Errorf("cannot reach the tester at %s (unset TESTER_NATS_URL to use the in-process one, or start it with 'make tester-up-host'): %w", testerURL, err)
74 return
75 }
76 fmt.Fprintf(os.Stderr, "tester at %s: nats-server %s\n", testerURL, nc.ConnectedServerVersion())
77 nc.Close()
78 })
79 if testerProbe.err != nil {
80 t.Fatal(testerProbe.err)
81 }
82 c := testservice.New(t, testerURL)
83 t.Cleanup(func() { c.Close(t) })
84 return c
85 }
86
87 // newTesterCtx returns a context with the given timeout; cancel is registered
88 // with t.Cleanup.
89 func newTesterCtx(t *testing.T, d time.Duration) context.Context {
90 t.Helper()
91 ctx, cancel := context.WithTimeout(context.Background(), d)
92 t.Cleanup(cancel)
93 return ctx
94 }
95
96 // withJSServer creates a single JetStream server, dials it, and invokes fn with
97 // a connection and a jetstream.JetStream handle. Cleanup is via t.Cleanup.
98 func withJSServer(t *testing.T, fn func(*testing.T, *nats.Conn, jetstream.JetStream), opts ...testservice.CreateOption) {
99 t.Helper()
100 withJSServerInstance(t, func(t *testing.T, nc *nats.Conn, js jetstream.JetStream, _ *testservice.Instance) {
101 fn(t, nc, js)
102 }, opts...)
103 }
104
105 // withJSServerInstance is withJSServer plus the *testservice.Instance handle,
106 // so tests can stop/start the server or inspect Ports.
107 func withJSServerInstance(t *testing.T, fn func(*testing.T, *nats.Conn, jetstream.JetStream, *testservice.Instance), opts ...testservice.CreateOption) {
108 t.Helper()
109 c := newTester(t)
110 inst := c.CreateServer(t, true, opts...)
111 t.Cleanup(func() { inst.Destroy(t) })
112
113 nc := dialInstance(t, inst)
114 js := newJetStream(t, nc)
115 fn(t, nc, js, inst)
116 }
117
118 // withJSCluster creates a JetStream cluster of `size` servers, dials all member
119 // URLs (so reconnect survives any single node going down), and invokes fn with
120 // connection, JetStream handle, and *testservice.Instance — cluster tests
121 // effectively always want the instance, so we pass it unconditionally.
122 func withJSCluster(t *testing.T, size int, fn func(*testing.T, *nats.Conn, jetstream.JetStream, *testservice.Instance), opts ...testservice.CreateOption) {
123 t.Helper()
124 c := newTester(t)
125 inst := c.CreateCluster(t, size, true, opts...)
126 t.Cleanup(func() { inst.Destroy(t) })
127
128 if got := len(inst.Servers); got != size {
129 t.Fatalf("expected %d servers in cluster, got %d", size, got)
130 }
131
132 nc := dialInstance(t, inst)
133 c.WaitForJetStream(t, nc)
134 js := newJetStream(t, nc)
135 waitForJSCluster(t, js)
136 fn(t, nc, js, inst)
137 }
138
139 // waitForStream blocks until the stream is queryable and has a leader.
140 // StartServer returns on ack, not on readiness, so a publish issued right
141 // after a restart can race JetStream recovery. A bare lookup is not enough:
142 // a replica of a group that has been leaderless for a while answers
143 // STREAM.INFO itself, and only the leader subscribes to the stream subjects.
144 func waitForStream(t *testing.T, js jetstream.JetStream, name string) {
145 t.Helper()
146 // Per-attempt timeout so one slow lookup cannot eat the whole budget:
147 // after a cluster restart the first lookups block until a leader exists.
148 deadline := time.Now().Add(30 * time.Second)
149 var err error
150 for time.Now().Before(deadline) {
151 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
152 var s jetstream.Stream
153 s, err = js.Stream(ctx, name)
154 cancel()
155 if err == nil {
156 if ci := s.CachedInfo().Cluster; ci == nil || ci.Leader != "" {
157 return
158 }
159 err = errors.New("stream has no leader")
160 }
161 time.Sleep(100 * time.Millisecond)
162 }
163 t.Fatalf("stream %q not ready after restart: %v", name, err)
164 }
165
166 // waitForJSCluster blocks until the meta leader is elected. WaitForJetStream
167 // only checks the transport error, so a leaderless cluster answering
168 // JSClusterNotAvail satisfies it; AccountInfo parses the response body.
169 func waitForJSCluster(t *testing.T, js jetstream.JetStream) {
170 t.Helper()
171 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
172 defer cancel()
173 for {
174 _, err := js.AccountInfo(ctx)
175 if err == nil {
176 return
177 }
178 select {
179 case <-ctx.Done():
180 t.Fatalf("jetstream cluster not ready: %v", err)
181 case <-time.After(100 * time.Millisecond):
182 }
183 }
184 }
185
186 // dialInstance returns a connection that lists every server URL in inst, so
187 // reconnect survives any single node going down. nats.MaxReconnects(-1) is
188 // always set; additional connect options (e.g. credentials) may be passed.
189 // Tests that need custom dial behavior call CreateServer/CreateCluster
190 // themselves and then dialInstance directly. Accepts testing.TB so benchmarks
191 // can share the helper.
192 func dialInstance(t testing.TB, inst *testservice.Instance, opts ...nats.Option) *nats.Conn {
193 t.Helper()
194 urls := make([]string, len(inst.Servers))
195 for i, s := range inst.Servers {
196 urls[i] = s.URL
197 }
198 connectOpts := append([]nats.Option{nats.MaxReconnects(-1)}, opts...)
199 nc, err := nats.Connect(strings.Join(urls, ","), connectOpts...)
200 if err != nil {
201 t.Fatalf("nats.Connect: %v", err)
202 }
203 t.Cleanup(nc.Close)
204 return nc
205 }
206
207 func newJetStream(t *testing.T, nc *nats.Conn) jetstream.JetStream {
208 t.Helper()
209 js, err := jetstream.New(nc)
210 if err != nil {
211 t.Fatalf("jetstream.New: %v", err)
212 }
213 return js
214 }