Debian Codegraph @

server/jetstream_sourcing_scaling_test.go

raw
1 // Copyright 2024 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 server
15
16 import (
17 "fmt"
18 "strconv"
19 "testing"
20 "time"
21
22 "github.com/nats-io/nats.go"
23 )
24
25 var serverConfig1 = `
26 server_name: server1
27 listen: 127.0.0.1:4222
28 http: 8222
29
30 prof_port = 18222
31
32 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
33
34 cluster {
35 name: my_cluster
36 listen: 127.0.0.1:4248
37 routes: [nats://127.0.0.1:4249,nats://127.0.0.1:4250]
38 }
39
40 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }}
41 `
42
43 var serverConfig2 = `
44 server_name: server2
45 listen: 127.0.0.1:5222
46 http: 8223
47
48 prof_port = 18223
49
50 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
51
52 cluster {
53 name: my_cluster
54 listen: 127.0.0.1:4249
55 routes: [nats://127.0.0.1:4248,nats://127.0.0.1:4250]
56 }
57
58 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }}
59 `
60
61 var serverConfig3 = `
62 server_name: server3
63 listen: 127.0.0.1:6222
64 http: 8224
65
66 prof_port = 18224
67
68 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
69
70 cluster {
71 name: my_cluster
72 listen: 127.0.0.1:4250
73 routes: [nats://127.0.0.1:4248,nats://127.0.0.1:4249]
74 }
75
76 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }}
77 `
78
79 var connectURL = "nats://127.0.0.1:4222,nats://127.0.0.1:4223,nats://127.0.0.1:4224"
80
81 func createMyLocalCluster(t *testing.T) *cluster {
82 c := &cluster{servers: make([]*Server, 0, 3), opts: make([]*Options, 0, 3), name: "C3"}
83
84 storeDir1 := t.TempDir()
85 s1, o := RunServerWithConfig(createConfFile(t, []byte(fmt.Sprintf(serverConfig1, storeDir1))))
86 c.servers = append(c.servers, s1)
87 c.opts = append(c.opts, o)
88
89 storeDir2 := t.TempDir()
90 s2, o := RunServerWithConfig(createConfFile(t, []byte(fmt.Sprintf(serverConfig2, storeDir2))))
91 c.servers = append(c.servers, s2)
92 c.opts = append(c.opts, o)
93
94 storeDir3 := t.TempDir()
95 s3, o := RunServerWithConfig(createConfFile(t, []byte(fmt.Sprintf(serverConfig3, storeDir3))))
96 c.servers = append(c.servers, s3)
97 c.opts = append(c.opts, o)
98
99 c.t = t
100
101 // Wait til we are formed and have a leader.
102 c.checkClusterFormed()
103 c.waitOnClusterReady()
104
105 return c
106 }
107
108 // This test is being skipped by CI as it takes too long to run and is meant to test the scalability of sourcing
109 // rather than being a unit test.
110 func TestStreamSourcingScalingSourcingManyBenchmark(t *testing.T) {
111 t.Skip()
112
113 var numSourced = 1000
114 var numMsgPerSource = 10_000
115 var batchSize = 200
116 var retries int
117
118 var err error
119
120 c := createMyLocalCluster(t)
121 defer c.shutdown()
122
123 nc, err := nats.Connect(connectURL)
124 if err != nil {
125 t.Fatalf("Failed to create client: %v", err)
126 }
127 js, err := nc.JetStream(nats.MaxWait(10 * time.Second))
128 if err != nil {
129 t.Fatalf("Unexpected error getting JetStream context: %v", err)
130 }
131 defer nc.Close()
132
133 // create n streams to source from
134 for i := 0; i < numSourced; i++ {
135 _, err := js.AddStream(&nats.StreamConfig{
136 Name: fmt.Sprintf("sourced-%d", i),
137 Subjects: []string{strconv.Itoa(i)},
138 Retention: nats.LimitsPolicy,
139 Storage: nats.FileStorage,
140 Discard: nats.DiscardOld,
141 Replicas: 1,
142 AllowDirect: true,
143 MirrorDirect: false,
144 DiscardNewPerSubject: false,
145 })
146 require_NoError(t, err)
147 }
148
149 fmt.Printf("Streams created\n")
150
151 // publish n messages for each sourced stream
152 for j := 0; j < numMsgPerSource; j++ {
153 start := time.Now()
154 var pafs = make([]nats.PubAckFuture, numSourced)
155 for i := 0; i < numSourced; i++ {
156 var err error
157
158 for {
159 pafs[i], err = js.PublishAsync(strconv.Itoa(i), []byte(strconv.Itoa(j)))
160 if err != nil {
161 fmt.Printf("Error async publishing: %v, retrying\n", err)
162 retries++
163 time.Sleep(10 * time.Millisecond)
164 } else {
165 break
166 }
167 }
168
169 if i != 0 && i%batchSize == 0 {
170 <-js.PublishAsyncComplete()
171 }
172
173 }
174
175 <-js.PublishAsyncComplete()
176
177 for i := 0; i < numSourced; i++ {
178 select {
179 case <-pafs[i].Ok():
180 case psae := <-pafs[i].Err():
181 fmt.Printf("Error on PubAckFuture: %v, retrying sync...\n", psae)
182 retries++
183 _, err = js.Publish(strconv.Itoa(i), []byte(strconv.Itoa(j)))
184 require_NoError(t, err)
185 }
186 }
187
188 end := time.Now()
189 if j%1000 == 0 {
190 fmt.Printf("Published round %d, avg pub latency %v\n", j, end.Sub(start)/time.Duration(numSourced))
191 }
192 }
193
194 fmt.Printf("Messages published\n")
195
196 // create the StreamSources
197 streamSources := make([]*nats.StreamSource, numSourced)
198
199 for i := 0; i < numSourced; i++ {
200 streamSources[i] = &nats.StreamSource{Name: fmt.Sprintf("sourced-%d", i), FilterSubject: strconv.Itoa(i)}
201 }
202
203 // create a stream that sources from them
204 _, err = js.AddStream(&nats.StreamConfig{
205 Name: "sourcing",
206 Subjects: []string{"foo"},
207 Sources: streamSources,
208 Retention: nats.LimitsPolicy,
209 Storage: nats.FileStorage,
210 Discard: nats.DiscardOld,
211 Replicas: 3,
212 AllowDirect: true,
213 MirrorDirect: false,
214 DiscardNewPerSubject: false,
215 })
216 require_NoError(t, err)
217 c.waitOnStreamLeader(globalAccountName, "sourcing")
218 sl := c.streamLeader(globalAccountName, "sourcing")
219 fmt.Printf("Sourcing stream created leader is *** %s ***\n", sl.Name())
220
221 expectedSeq := make([]int, numSourced)
222
223 start := time.Now()
224
225 var lastMsgs uint64
226 mset, err := sl.GlobalAccount().lookupStream("sourcing")
227 require_NoError(t, err)
228
229 checkFor(t, 5*time.Minute, 1000*time.Millisecond, func() error {
230 mset.mu.RLock()
231 var state StreamState
232 mset.store.FastState(&state)
233 mset.mu.RUnlock()
234
235 if state.Msgs == uint64(numMsgPerSource*numSourced) {
236 fmt.Printf("👍 Test passed: expected %d messages, got %d and took %v\n", uint64(numMsgPerSource*numSourced), state.Msgs, time.Since(start))
237 return nil
238 } else if state.Msgs < uint64(numMsgPerSource*numSourced) {
239 fmt.Printf("Current Rate %d per second - Received %d\n", state.Msgs-lastMsgs, state.Msgs)
240 lastMsgs = state.Msgs
241 return fmt.Errorf("Expected %d messages, got %d", uint64(numMsgPerSource*numSourced), state.Msgs)
242 } else {
243 fmt.Printf("Too many messages! expected %d (retries=%d), got %d\n", uint64(numMsgPerSource*numSourced), retries, state.Msgs)
244 return fmt.Errorf("Too many messages: expected %d (retries=%d), got %d", uint64(numMsgPerSource*numSourced), retries, state.Msgs)
245 }
246 })
247
248 // Check that all the messages sourced in the stream are correct
249 // Note: expects to see exactly increasing matching sequence numbers, so could theoretically fail if some messages
250 // get recorded 'out of order' (according to the payload value) because asynchronous JS publication is used to
251 // publish the messages.
252 // However, that should not happen if the publish 'batch size' is not more than the number of streams being sourced.
253
254 // create a consumer on sourcing
255 _, err = js.AddConsumer("sourcing", &nats.ConsumerConfig{AckPolicy: nats.AckExplicitPolicy})
256 require_NoError(t, err)
257 syncSub, err := js.SubscribeSync("", nats.BindStream("sourcing"))
258 require_NoError(t, err)
259
260 start = time.Now()
261
262 print("Checking the messages\n")
263 for i := 0; i < numSourced*numMsgPerSource; i++ {
264 msg, err := syncSub.NextMsg(30 * time.Second)
265 require_NoError(t, err)
266 sId, err := strconv.Atoi(msg.Subject)
267 require_NoError(t, err)
268 seq, err := strconv.Atoi(string(msg.Data))
269 require_NoError(t, err)
270 if expectedSeq[sId] == seq {
271 expectedSeq[sId]++
272 } else {
273 t.Fatalf("Expected seq number %d got %d for source %d\n", expectedSeq[sId], seq, sId)
274 }
275 msg.Ack()
276 if i%100_000 == 0 {
277 now := time.Now()
278 fmt.Printf("[%v] Checked %d messages: %f msgs/sec \n", now, i, 100_000/now.Sub(start).Seconds())
279 start = now
280 }
281 }
282 print("👍 Done. \n")
283 }