| 1 |
// Copyright 2012-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 |
package test |
| 15 |
|
| 16 |
import ( |
| 17 |
"crypto/rand" |
| 18 |
"encoding/hex" |
| 19 |
"encoding/json" |
| 20 |
"fmt" |
| 21 |
"io" |
| 22 |
"net" |
| 23 |
"os" |
| 24 |
"regexp" |
| 25 |
"runtime" |
| 26 |
"strconv" |
| 27 |
"strings" |
| 28 |
"testing" |
| 29 |
"time" |
| 30 |
|
| 31 |
"github.com/nats-io/nats-server/v2/server" |
| 32 |
|
| 33 |
srvlog "github.com/nats-io/nats-server/v2/logger" |
| 34 |
) |
| 35 |
|
| 36 |
// So we can pass tests and benchmarks.. |
| 37 |
type tLogger interface { |
| 38 |
Fatalf(format string, args ...any) |
| 39 |
Errorf(format string, args ...any) |
| 40 |
} |
| 41 |
|
| 42 |
// DefaultTestOptions are default options for the unit tests. |
| 43 |
var DefaultTestOptions = server.Options{ |
| 44 |
Host: "127.0.0.1", |
| 45 |
Port: 4222, |
| 46 |
NoLog: true, |
| 47 |
NoSigs: true, |
| 48 |
MaxControlLine: 4096, |
| 49 |
DisableShortFirstPing: true, |
| 50 |
} |
| 51 |
|
| 52 |
// RunDefaultServer starts a new Go routine based server using the default options |
| 53 |
func RunDefaultServer() *server.Server { |
| 54 |
dto := DefaultTestOptions |
| 55 |
return RunServer(&dto) |
| 56 |
} |
| 57 |
|
| 58 |
func RunRandClientPortServer() *server.Server { |
| 59 |
opts := DefaultTestOptions |
| 60 |
opts.Port = -1 |
| 61 |
return RunServer(&opts) |
| 62 |
} |
| 63 |
|
| 64 |
// To turn on server tracing and debugging and logging which are |
| 65 |
// normally suppressed. |
| 66 |
var ( |
| 67 |
doLog = false |
| 68 |
doTrace = false |
| 69 |
doDebug = false |
| 70 |
) |
| 71 |
|
| 72 |
// RunServer starts a new Go routine based server |
| 73 |
func RunServer(opts *server.Options) *server.Server { |
| 74 |
return RunServerCallback(opts, nil) |
| 75 |
} |
| 76 |
|
| 77 |
func RunServerCallback(opts *server.Options, callback func(*server.Server)) *server.Server { |
| 78 |
if opts == nil { |
| 79 |
dto := DefaultTestOptions |
| 80 |
opts = &dto |
| 81 |
} |
| 82 |
// Optionally override for individual debugging of tests |
| 83 |
opts.NoLog = !doLog |
| 84 |
opts.Trace = doTrace |
| 85 |
opts.Debug = doDebug |
| 86 |
// For all tests in the "test" package, we will disable route pooling. |
| 87 |
opts.Cluster.PoolSize = -1 |
| 88 |
// Also disable compression for "test" package. |
| 89 |
opts.Cluster.Compression.Mode = server.CompressionOff |
| 90 |
opts.LeafNode.Compression.Mode = server.CompressionOff |
| 91 |
|
| 92 |
s, err := server.NewServer(opts) |
| 93 |
if err != nil || s == nil { |
| 94 |
panic(fmt.Sprintf("No NATS Server object returned: %v", err)) |
| 95 |
} |
| 96 |
|
| 97 |
if doLog { |
| 98 |
s.ConfigureLogger() |
| 99 |
} |
| 100 |
|
| 101 |
if ll := os.Getenv("NATS_LOGGING"); ll != "" { |
| 102 |
log := srvlog.NewTestLogger(fmt.Sprintf("[%s] | ", s), true) |
| 103 |
debug := ll == "debug" || ll == "trace" |
| 104 |
trace := ll == "trace" |
| 105 |
s.SetLoggerV2(log, debug, trace, false) |
| 106 |
} |
| 107 |
|
| 108 |
if callback != nil { |
| 109 |
callback(s) |
| 110 |
} |
| 111 |
|
| 112 |
// Run server in Go routine. |
| 113 |
go s.Start() |
| 114 |
|
| 115 |
// Wait for accept loop(s) to be started |
| 116 |
if !s.ReadyForConnections(10 * time.Second) { |
| 117 |
panic("Unable to start NATS Server in Go Routine") |
| 118 |
} |
| 119 |
return s |
| 120 |
} |
| 121 |
|
| 122 |
// LoadConfig loads a configuration from a filename |
| 123 |
func LoadConfig(configFile string) *server.Options { |
| 124 |
opts, err := server.ProcessConfigFile(configFile) |
| 125 |
if err != nil { |
| 126 |
panic(fmt.Sprintf("Error processing configuration file: %v", err)) |
| 127 |
} |
| 128 |
return opts |
| 129 |
} |
| 130 |
|
| 131 |
// RunServerWithConfig starts a new Go routine based server with a configuration file. |
| 132 |
func RunServerWithConfig(configFile string) (srv *server.Server, opts *server.Options) { |
| 133 |
opts = LoadConfig(configFile) |
| 134 |
srv = RunServer(opts) |
| 135 |
return |
| 136 |
} |
| 137 |
|
| 138 |
// RunServerWithConfigOverrides starts a new Go routine based server with a configuration file, |
| 139 |
// providing a callback to update the options configured. |
| 140 |
func RunServerWithConfigOverrides(configFile string, optsCallback func(*server.Options), svrCallback func(*server.Server)) (srv *server.Server, opts *server.Options) { |
| 141 |
opts = LoadConfig(configFile) |
| 142 |
if optsCallback != nil { |
| 143 |
optsCallback(opts) |
| 144 |
} |
| 145 |
srv = RunServerCallback(opts, svrCallback) |
| 146 |
return |
| 147 |
} |
| 148 |
|
| 149 |
func stackFatalf(t tLogger, f string, args ...any) { |
| 150 |
lines := make([]string, 0, 32) |
| 151 |
msg := fmt.Sprintf(f, args...) |
| 152 |
lines = append(lines, msg) |
| 153 |
|
| 154 |
// Ignore ourselves |
| 155 |
_, testFile, _, _ := runtime.Caller(0) |
| 156 |
|
| 157 |
// Generate the Stack of callers: |
| 158 |
for i := 0; true; i++ { |
| 159 |
_, file, line, ok := runtime.Caller(i) |
| 160 |
if !ok { |
| 161 |
break |
| 162 |
} |
| 163 |
if file == testFile { |
| 164 |
continue |
| 165 |
} |
| 166 |
msg := fmt.Sprintf("%d - %s:%d", i, file, line) |
| 167 |
lines = append(lines, msg) |
| 168 |
} |
| 169 |
|
| 170 |
t.Fatalf("%s", strings.Join(lines, "\n")) |
| 171 |
} |
| 172 |
|
| 173 |
func acceptRouteConn(t tLogger, host string, timeout time.Duration) net.Conn { |
| 174 |
l, e := net.Listen("tcp", host) |
| 175 |
if e != nil { |
| 176 |
stackFatalf(t, "Error listening for route connection on %v: %v", host, e) |
| 177 |
} |
| 178 |
defer l.Close() |
| 179 |
|
| 180 |
tl := l.(*net.TCPListener) |
| 181 |
tl.SetDeadline(time.Now().Add(timeout)) |
| 182 |
conn, err := l.Accept() |
| 183 |
tl.SetDeadline(time.Time{}) |
| 184 |
|
| 185 |
if err != nil { |
| 186 |
stackFatalf(t, "Did not receive a route connection request: %v", err) |
| 187 |
} |
| 188 |
return conn |
| 189 |
} |
| 190 |
|
| 191 |
func createRouteConn(t tLogger, host string, port int) net.Conn { |
| 192 |
return createClientConn(t, host, port) |
| 193 |
} |
| 194 |
|
| 195 |
func createClientConn(t tLogger, host string, port int) net.Conn { |
| 196 |
addr := net.JoinHostPort(host, fmt.Sprintf("%d", port)) |
| 197 |
c, err := net.DialTimeout("tcp", addr, 3*time.Second) |
| 198 |
if err != nil { |
| 199 |
stackFatalf(t, "Could not connect to server: %v\n", err) |
| 200 |
} |
| 201 |
return c |
| 202 |
} |
| 203 |
|
| 204 |
func checkSocket(t tLogger, addr string, wait time.Duration) { |
| 205 |
end := time.Now().Add(wait) |
| 206 |
for time.Now().Before(end) { |
| 207 |
conn, err := net.Dial("tcp", addr) |
| 208 |
if err != nil { |
| 209 |
// Retry after 50ms |
| 210 |
time.Sleep(50 * time.Millisecond) |
| 211 |
continue |
| 212 |
} |
| 213 |
conn.Close() |
| 214 |
// Wait a bit to give a chance to the server to remove this |
| 215 |
// "client" from its state, which may otherwise interfere with |
| 216 |
// some tests. |
| 217 |
time.Sleep(25 * time.Millisecond) |
| 218 |
return |
| 219 |
} |
| 220 |
// We have failed to bind the socket in the time allowed. |
| 221 |
t.Fatalf("Failed to connect to the socket: %q", addr) |
| 222 |
} |
| 223 |
|
| 224 |
func checkInfoMsg(t tLogger, c net.Conn) server.Info { |
| 225 |
buf := expectResult(t, c, infoRe) |
| 226 |
js := infoRe.FindAllSubmatch(buf, 1)[0][1] |
| 227 |
var sinfo server.Info |
| 228 |
err := json.Unmarshal(js, &sinfo) |
| 229 |
if err != nil { |
| 230 |
stackFatalf(t, "Could not unmarshal INFO json: %v\n", err) |
| 231 |
} |
| 232 |
return sinfo |
| 233 |
} |
| 234 |
|
| 235 |
func doHeadersConnect(t tLogger, c net.Conn, verbose, pedantic, ssl, headers bool) { |
| 236 |
checkInfoMsg(t, c) |
| 237 |
cs := fmt.Sprintf("CONNECT {\"verbose\":%v,\"pedantic\":%v,\"tls_required\":%v,\"headers\":%v}\r\n", |
| 238 |
verbose, pedantic, ssl, headers) |
| 239 |
sendProto(t, c, cs) |
| 240 |
} |
| 241 |
|
| 242 |
func doConnect(t tLogger, c net.Conn, verbose, pedantic, ssl bool) { |
| 243 |
doHeadersConnect(t, c, verbose, pedantic, ssl, false) |
| 244 |
} |
| 245 |
|
| 246 |
func doDefaultHeadersConnect(t tLogger, c net.Conn) { |
| 247 |
doHeadersConnect(t, c, false, false, false, true) |
| 248 |
} |
| 249 |
|
| 250 |
func doDefaultConnect(t tLogger, c net.Conn) { |
| 251 |
// Basic Connect |
| 252 |
doConnect(t, c, false, false, false) |
| 253 |
} |
| 254 |
|
| 255 |
const routeConnectProto = "CONNECT {\"verbose\":false,\"user\":\"%s\",\"pass\":\"%s\",\"name\":\"%s\",\"cluster\":\"xyz\"}\r\n" |
| 256 |
|
| 257 |
func doRouteAuthConnect(t tLogger, c net.Conn, user, pass, id string) { |
| 258 |
cs := fmt.Sprintf(routeConnectProto, user, pass, id) |
| 259 |
sendProto(t, c, cs) |
| 260 |
} |
| 261 |
|
| 262 |
func setupRouteEx(t tLogger, c net.Conn, opts *server.Options, id string) (sendFun, expectFun) { |
| 263 |
user := opts.Cluster.Username |
| 264 |
pass := opts.Cluster.Password |
| 265 |
doRouteAuthConnect(t, c, user, pass, id) |
| 266 |
return sendCommand(t, c), expectCommand(t, c) |
| 267 |
} |
| 268 |
|
| 269 |
func setupRoute(t tLogger, c net.Conn, opts *server.Options) (sendFun, expectFun) { |
| 270 |
u := make([]byte, 16) |
| 271 |
io.ReadFull(rand.Reader, u) |
| 272 |
id := fmt.Sprintf("ROUTER:%s", hex.EncodeToString(u)) |
| 273 |
return setupRouteEx(t, c, opts, id) |
| 274 |
} |
| 275 |
|
| 276 |
func setupHeaderConn(t tLogger, c net.Conn) (sendFun, expectFun) { |
| 277 |
doDefaultHeadersConnect(t, c) |
| 278 |
return sendCommand(t, c), expectCommand(t, c) |
| 279 |
} |
| 280 |
|
| 281 |
func setupConn(t tLogger, c net.Conn) (sendFun, expectFun) { |
| 282 |
doDefaultConnect(t, c) |
| 283 |
return sendCommand(t, c), expectCommand(t, c) |
| 284 |
} |
| 285 |
|
| 286 |
func setupConnWithProto(t tLogger, c net.Conn, proto int) (sendFun, expectFun) { |
| 287 |
checkInfoMsg(t, c) |
| 288 |
cs := fmt.Sprintf("CONNECT {\"verbose\":%v,\"pedantic\":%v,\"tls_required\":%v,\"protocol\":%d}\r\n", false, false, false, proto) |
| 289 |
sendProto(t, c, cs) |
| 290 |
return sendCommand(t, c), expectCommand(t, c) |
| 291 |
} |
| 292 |
|
| 293 |
func setupConnWithAccount(t tLogger, s *server.Server, c net.Conn, account string) (sendFun, expectFun) { |
| 294 |
info := checkInfoMsg(t, c) |
| 295 |
s.RegisterAccount(account) |
| 296 |
acc, err := s.LookupAccount(account) |
| 297 |
if err != nil { |
| 298 |
t.Fatalf("Unexpected Error: %v", err) |
| 299 |
} |
| 300 |
cs := fmt.Sprintf("CONNECT {\"verbose\":%v,\"pedantic\":%v,\"tls_required\":%v}\r\n", false, false, false) |
| 301 |
sendProto(t, c, cs) |
| 302 |
|
| 303 |
send, expect := sendCommand(t, c), expectCommand(t, c) |
| 304 |
send("PING\r\n") |
| 305 |
expect(pongRe) |
| 306 |
|
| 307 |
nc := s.GetClient(info.CID) |
| 308 |
if nc == nil { |
| 309 |
t.Fatalf("Could not get client for CID:%d", info.CID) |
| 310 |
} |
| 311 |
nc.RegisterUser(&server.User{Account: acc}) |
| 312 |
|
| 313 |
return send, expect |
| 314 |
} |
| 315 |
|
| 316 |
func setupConnWithUserPass(t tLogger, c net.Conn, username, password string) (sendFun, expectFun) { |
| 317 |
checkInfoMsg(t, c) |
| 318 |
cs := fmt.Sprintf("CONNECT {\"verbose\":%v,\"pedantic\":%v,\"tls_required\":%v,\"user\":%q,\"pass\":%q}\r\n", |
| 319 |
false, false, false, username, password) |
| 320 |
sendProto(t, c, cs) |
| 321 |
return sendCommand(t, c), expectLefMostCommand(t, c) |
| 322 |
} |
| 323 |
|
| 324 |
type sendFun func(string) |
| 325 |
type expectFun func(*regexp.Regexp) []byte |
| 326 |
|
| 327 |
// Closure version for easier reading |
| 328 |
func sendCommand(t tLogger, c net.Conn) sendFun { |
| 329 |
return func(op string) { |
| 330 |
sendProto(t, c, op) |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
// Closure version for easier reading |
| 335 |
func expectCommand(t tLogger, c net.Conn) expectFun { |
| 336 |
return func(re *regexp.Regexp) []byte { |
| 337 |
return expectResult(t, c, re) |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
// Closure version for easier reading |
| 342 |
func expectLefMostCommand(t tLogger, c net.Conn) expectFun { |
| 343 |
var buf []byte |
| 344 |
return func(re *regexp.Regexp) []byte { |
| 345 |
return expectLeftMostResult(t, c, re, &buf) |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
// Send the protocol command to the server. |
| 350 |
func sendProto(t tLogger, c net.Conn, op string) { |
| 351 |
n, err := c.Write([]byte(op)) |
| 352 |
if err != nil { |
| 353 |
stackFatalf(t, "Error writing command to conn: %v\n", err) |
| 354 |
} |
| 355 |
if n != len(op) { |
| 356 |
stackFatalf(t, "Partial write: %d vs %d\n", n, len(op)) |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
var ( |
| 361 |
anyRe = regexp.MustCompile(`.*`) |
| 362 |
infoRe = regexp.MustCompile(`INFO\s+([^\r\n]+)\r\n`) |
| 363 |
infoStartRe = regexp.MustCompile(`^INFO\s+([^\r\n]+)\r\n`) |
| 364 |
pingRe = regexp.MustCompile(`^PING\r\n`) |
| 365 |
pongRe = regexp.MustCompile(`^PONG\r\n`) |
| 366 |
hmsgRe = regexp.MustCompile(`(?:(?:HMSG\s+([^\s]+)\s+([^\s]+)\s+(([^\s]+)[^\S\r\n]+)?(\d+)\s+(\d+)\s*\r\n([^\\r\\n]*?)\r\n)+?)`) |
| 367 |
msgRe = regexp.MustCompile(`(?:(?:MSG\s+([^\s]+)\s+([^\s]+)\s+(([^\s]+)[^\S\r\n]+)?(\d+)\s*\r\n([^\\r\\n]*?)\r\n)+?)`) |
| 368 |
rawMsgRe = regexp.MustCompile(`(?:(?:MSG\s+([^\s]+)\s+([^\s]+)\s+(([^\s]+)[^\S\r\n]+)?(\d+)\s*\r\n(.*?)))`) |
| 369 |
okRe = regexp.MustCompile(`\A\+OK\r\n`) |
| 370 |
errRe = regexp.MustCompile(`\A\-ERR\s+([^\r\n]+)\r\n`) |
| 371 |
connectRe = regexp.MustCompile(`CONNECT\s+([^\r\n]+)\r\n`) |
| 372 |
rsubRe = regexp.MustCompile(`RS\+\s+([^\s]+)\s+([^\s]+)\s*([^\s]+)?\s*(\d+)?\r\n`) |
| 373 |
runsubRe = regexp.MustCompile(`RS\-\s+([^\s]+)\s+([^\s]+)\s*([^\s]+)?\r\n`) |
| 374 |
rmsgRe = regexp.MustCompile(`(?:(?:RMSG\s+([^\s]+)\s+([^\s]+)\s+(?:([|+]\s+([\w\s]+)|[^\s]+)[^\S\r\n]+)?(\d+)\s*\r\n([^\\r\\n]*?)\r\n)+?)`) |
| 375 |
asubRe = regexp.MustCompile(`A\+\s+([^\r\n]+)\r\n`) |
| 376 |
aunsubRe = regexp.MustCompile(`A\-\s+([^\r\n]+)\r\n`) |
| 377 |
lsubRe = regexp.MustCompile(`LS\+\s+([^\s]+)\s*([^\s]+)?\s*(\d+)?\r\n`) |
| 378 |
lunsubRe = regexp.MustCompile(`LS\-\s+([^\s]+)\s*([^\s]+)\s*([^\s]+)?\r\n`) |
| 379 |
lmsgRe = regexp.MustCompile(`(?:(?:LMSG\s+([^\s]+)\s+(?:([|+]\s+([\w\s]+)|[^\s]+)[^\S\r\n]+)?(\d+)\s*\r\n([^\\r\\n]*?)\r\n)+?)`) |
| 380 |
rlsubRe = regexp.MustCompile(`LS\+\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s*([^\s]+)?\s*(\d+)?\r\n`) |
| 381 |
rlunsubRe = regexp.MustCompile(`LS\-\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s*([^\s]+)?\r\n`) |
| 382 |
) |
| 383 |
|
| 384 |
const ( |
| 385 |
// Regular Messages |
| 386 |
subIndex = 1 |
| 387 |
sidIndex = 2 |
| 388 |
replyIndex = 4 |
| 389 |
lenIndex = 5 |
| 390 |
msgIndex = 6 |
| 391 |
// Headers |
| 392 |
hlenIndex = 5 |
| 393 |
tlenIndex = 6 |
| 394 |
hmsgIndex = 7 |
| 395 |
|
| 396 |
// Routed Messages |
| 397 |
accIndex = 1 |
| 398 |
rsubIndex = 2 |
| 399 |
replyAndQueueIndex = 3 |
| 400 |
) |
| 401 |
|
| 402 |
// Test result from server against regexp and return left most match |
| 403 |
func expectLeftMostResult(t tLogger, c net.Conn, re *regexp.Regexp, buf *[]byte) []byte { |
| 404 |
recv := func() []byte { |
| 405 |
expBuf := make([]byte, 32768) |
| 406 |
// Wait for commands to be processed and results queued for read |
| 407 |
c.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| 408 |
n, err := c.Read(expBuf) |
| 409 |
c.SetReadDeadline(time.Time{}) |
| 410 |
|
| 411 |
if n <= 0 && err != nil { |
| 412 |
stackFatalf(t, "Error reading from conn: %v\n", err) |
| 413 |
} |
| 414 |
return expBuf[:n] |
| 415 |
} |
| 416 |
if len(*buf) == 0 { |
| 417 |
*buf = recv() |
| 418 |
} |
| 419 |
emptyCnt := 0 |
| 420 |
for { |
| 421 |
result := re.Find(*buf) |
| 422 |
if result == nil { |
| 423 |
emptyCnt++ |
| 424 |
if emptyCnt > 5 { |
| 425 |
stackFatalf(t, "Reading empty data too often\n") |
| 426 |
} |
| 427 |
*buf = append(*buf, recv()...) |
| 428 |
} else { |
| 429 |
cutIdx := strings.Index(string(*buf), string(result)) + len(result) |
| 430 |
*buf = (*buf)[cutIdx:] |
| 431 |
return result |
| 432 |
} |
| 433 |
} |
| 434 |
} |
| 435 |
|
| 436 |
// Test result from server against regexp |
| 437 |
func expectResult(t tLogger, c net.Conn, re *regexp.Regexp) []byte { |
| 438 |
expBuf := make([]byte, 32768) |
| 439 |
// Wait for commands to be processed and results queued for read |
| 440 |
c.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| 441 |
n, err := c.Read(expBuf) |
| 442 |
c.SetReadDeadline(time.Time{}) |
| 443 |
|
| 444 |
if n <= 0 && err != nil { |
| 445 |
stackFatalf(t, "Error reading from conn: %v\n", err) |
| 446 |
} |
| 447 |
buf := expBuf[:n] |
| 448 |
if !re.Match(buf) { |
| 449 |
stackFatalf(t, "Response did not match expected: \n\tReceived:'%q'\n\tExpected:'%s'", buf, re) |
| 450 |
} |
| 451 |
return buf |
| 452 |
} |
| 453 |
|
| 454 |
func peek(c net.Conn) []byte { |
| 455 |
expBuf := make([]byte, 32768) |
| 456 |
c.SetReadDeadline(time.Now().Add(50 * time.Millisecond)) |
| 457 |
n, err := c.Read(expBuf) |
| 458 |
c.SetReadDeadline(time.Time{}) |
| 459 |
if err != nil || n <= 0 { |
| 460 |
return nil |
| 461 |
} |
| 462 |
return expBuf |
| 463 |
} |
| 464 |
|
| 465 |
func expectDisconnect(t *testing.T, c net.Conn) { |
| 466 |
t.Helper() |
| 467 |
var b [8]byte |
| 468 |
c.SetReadDeadline(time.Now().Add(200 * time.Millisecond)) |
| 469 |
_, err := c.Read(b[:]) |
| 470 |
c.SetReadDeadline(time.Time{}) |
| 471 |
if err != io.EOF { |
| 472 |
t.Fatalf("Expected a disconnect") |
| 473 |
} |
| 474 |
} |
| 475 |
|
| 476 |
func expectNothing(t tLogger, c net.Conn) { |
| 477 |
expectNothingTimeout(t, c, time.Now().Add(100*time.Millisecond)) |
| 478 |
} |
| 479 |
|
| 480 |
func expectNothingTimeout(t tLogger, c net.Conn, dl time.Time) { |
| 481 |
expBuf := make([]byte, 32) |
| 482 |
c.SetReadDeadline(dl) |
| 483 |
n, err := c.Read(expBuf) |
| 484 |
c.SetReadDeadline(time.Time{}) |
| 485 |
if err == nil && n > 0 { |
| 486 |
stackFatalf(t, "Expected nothing, received: '%q'\n", expBuf[:n]) |
| 487 |
} |
| 488 |
} |
| 489 |
|
| 490 |
// This will check that we got what we expected from a normal message. |
| 491 |
func checkMsg(t tLogger, m [][]byte, subject, sid, reply, len, msg string) { |
| 492 |
if string(m[subIndex]) != subject { |
| 493 |
stackFatalf(t, "Did not get correct subject: expected '%s' got '%s'\n", subject, m[subIndex]) |
| 494 |
} |
| 495 |
if sid != "" && string(m[sidIndex]) != sid { |
| 496 |
stackFatalf(t, "Did not get correct sid: expected '%s' got '%s'\n", sid, m[sidIndex]) |
| 497 |
} |
| 498 |
if string(m[replyIndex]) != reply { |
| 499 |
stackFatalf(t, "Did not get correct reply: expected '%s' got '%s'\n", reply, m[replyIndex]) |
| 500 |
} |
| 501 |
if string(m[lenIndex]) != len { |
| 502 |
stackFatalf(t, "Did not get correct msg length: expected '%s' got '%s'\n", len, m[lenIndex]) |
| 503 |
} |
| 504 |
if string(m[msgIndex]) != msg { |
| 505 |
stackFatalf(t, "Did not get correct msg: expected '%s' got '%s'\n", msg, m[msgIndex]) |
| 506 |
} |
| 507 |
} |
| 508 |
|
| 509 |
func checkRmsg(t tLogger, m [][]byte, account, subject, replyAndQueues, len, msg string) { |
| 510 |
if string(m[accIndex]) != account { |
| 511 |
stackFatalf(t, "Did not get correct account: expected '%s' got '%s'\n", account, m[accIndex]) |
| 512 |
} |
| 513 |
if string(m[rsubIndex]) != subject { |
| 514 |
stackFatalf(t, "Did not get correct subject: expected '%s' got '%s'\n", subject, m[rsubIndex]) |
| 515 |
} |
| 516 |
if string(m[lenIndex]) != len { |
| 517 |
stackFatalf(t, "Did not get correct msg length: expected '%s' got '%s'\n", len, m[lenIndex]) |
| 518 |
} |
| 519 |
if string(m[replyAndQueueIndex]) != replyAndQueues { |
| 520 |
stackFatalf(t, "Did not get correct reply/queues: expected '%s' got '%s'\n", replyAndQueues, m[replyAndQueueIndex]) |
| 521 |
} |
| 522 |
} |
| 523 |
|
| 524 |
func checkLmsg(t tLogger, m [][]byte, subject, replyAndQueues, len, msg string) { |
| 525 |
if string(m[rsubIndex-1]) != subject { |
| 526 |
stackFatalf(t, "Did not get correct subject: expected '%s' got '%s'\n", subject, m[rsubIndex-1]) |
| 527 |
} |
| 528 |
if string(m[lenIndex-1]) != len { |
| 529 |
stackFatalf(t, "Did not get correct msg length: expected '%s' got '%s'\n", len, m[lenIndex-1]) |
| 530 |
} |
| 531 |
if string(m[replyAndQueueIndex-1]) != replyAndQueues { |
| 532 |
stackFatalf(t, "Did not get correct reply/queues: expected '%s' got '%s'\n", replyAndQueues, m[replyAndQueueIndex-1]) |
| 533 |
} |
| 534 |
} |
| 535 |
|
| 536 |
// This will check that we got what we expected from a header message. |
| 537 |
func checkHmsg(t tLogger, m [][]byte, subject, sid, reply, hlen, len, hdr, msg string) { |
| 538 |
if string(m[subIndex]) != subject { |
| 539 |
stackFatalf(t, "Did not get correct subject: expected '%s' got '%s'\n", subject, m[subIndex]) |
| 540 |
} |
| 541 |
if sid != "" && string(m[sidIndex]) != sid { |
| 542 |
stackFatalf(t, "Did not get correct sid: expected '%s' got '%s'\n", sid, m[sidIndex]) |
| 543 |
} |
| 544 |
if string(m[replyIndex]) != reply { |
| 545 |
stackFatalf(t, "Did not get correct reply: expected '%s' got '%s'\n", reply, m[replyIndex]) |
| 546 |
} |
| 547 |
if string(m[hlenIndex]) != hlen { |
| 548 |
stackFatalf(t, "Did not get correct header length: expected '%s' got '%s'\n", hlen, m[hlenIndex]) |
| 549 |
} |
| 550 |
if string(m[tlenIndex]) != len { |
| 551 |
stackFatalf(t, "Did not get correct msg length: expected '%s' got '%s'\n", len, m[tlenIndex]) |
| 552 |
} |
| 553 |
// Extract the payload and break up the headers and msg. |
| 554 |
payload := string(m[hmsgIndex]) |
| 555 |
hi, _ := strconv.Atoi(hlen) |
| 556 |
rhdr, rmsg := payload[:hi], payload[hi:] |
| 557 |
if rhdr != hdr { |
| 558 |
stackFatalf(t, "Did not get correct headers: expected '%s' got '%s'\n", hdr, rhdr) |
| 559 |
} |
| 560 |
if rmsg != msg { |
| 561 |
stackFatalf(t, "Did not get correct msg: expected '%s' got '%s'\n", msg, rmsg) |
| 562 |
} |
| 563 |
} |
| 564 |
|
| 565 |
// Closure for expectMsgs |
| 566 |
func expectRmsgsCommand(t tLogger, ef expectFun) func(int) [][][]byte { |
| 567 |
return func(expected int) [][][]byte { |
| 568 |
buf := ef(rmsgRe) |
| 569 |
matches := rmsgRe.FindAllSubmatch(buf, -1) |
| 570 |
if len(matches) != expected { |
| 571 |
stackFatalf(t, "Did not get correct # routed msgs: %d vs %d\n", len(matches), expected) |
| 572 |
} |
| 573 |
return matches |
| 574 |
} |
| 575 |
} |
| 576 |
|
| 577 |
// Closure for expectHMsgs |
| 578 |
func expectHeaderMsgsCommand(t tLogger, ef expectFun) func(int) [][][]byte { |
| 579 |
return func(expected int) [][][]byte { |
| 580 |
buf := ef(hmsgRe) |
| 581 |
matches := hmsgRe.FindAllSubmatch(buf, -1) |
| 582 |
if len(matches) != expected { |
| 583 |
stackFatalf(t, "Did not get correct # msgs: %d vs %d\n", len(matches), expected) |
| 584 |
} |
| 585 |
return matches |
| 586 |
} |
| 587 |
} |
| 588 |
|
| 589 |
// Closure for expectMsgs |
| 590 |
func expectMsgsCommand(t tLogger, ef expectFun) func(int) [][][]byte { |
| 591 |
return func(expected int) [][][]byte { |
| 592 |
buf := ef(msgRe) |
| 593 |
matches := msgRe.FindAllSubmatch(buf, -1) |
| 594 |
if len(matches) != expected { |
| 595 |
stackFatalf(t, "Did not get correct # msgs: %d vs %d\n", len(matches), expected) |
| 596 |
} |
| 597 |
return matches |
| 598 |
} |
| 599 |
} |
| 600 |
|
| 601 |
// This will check that the matches include at least one of the sids. Useful for checking |
| 602 |
// that we received messages on a certain queue group. |
| 603 |
func checkForQueueSid(t tLogger, matches [][][]byte, sids []string) { |
| 604 |
seen := make(map[string]int, len(sids)) |
| 605 |
for _, sid := range sids { |
| 606 |
seen[sid] = 0 |
| 607 |
} |
| 608 |
for _, m := range matches { |
| 609 |
sid := string(m[sidIndex]) |
| 610 |
if _, ok := seen[sid]; ok { |
| 611 |
seen[sid]++ |
| 612 |
} |
| 613 |
} |
| 614 |
// Make sure we only see one and exactly one. |
| 615 |
total := 0 |
| 616 |
for _, n := range seen { |
| 617 |
total += n |
| 618 |
} |
| 619 |
if total != 1 { |
| 620 |
stackFatalf(t, "Did not get a msg for queue sids group: expected 1 got %d\n", total) |
| 621 |
} |
| 622 |
} |
| 623 |
|
| 624 |
// This will check that the matches include all of the sids. Useful for checking |
| 625 |
// that we received messages on all subscribers. |
| 626 |
func checkForPubSids(t tLogger, matches [][][]byte, sids []string) { |
| 627 |
seen := make(map[string]int, len(sids)) |
| 628 |
for _, sid := range sids { |
| 629 |
seen[sid] = 0 |
| 630 |
} |
| 631 |
for _, m := range matches { |
| 632 |
sid := string(m[sidIndex]) |
| 633 |
if _, ok := seen[sid]; ok { |
| 634 |
seen[sid]++ |
| 635 |
} |
| 636 |
} |
| 637 |
// Make sure we only see one and exactly one for each sid. |
| 638 |
for sid, n := range seen { |
| 639 |
if n != 1 { |
| 640 |
stackFatalf(t, "Did not get a msg for sid[%s]: expected 1 got %d\n", sid, n) |
| 641 |
|
| 642 |
} |
| 643 |
} |
| 644 |
} |
| 645 |
|
| 646 |
// Helper function to generate next opts to make sure no port conflicts etc. |
| 647 |
func nextServerOpts(opts *server.Options) *server.Options { |
| 648 |
nopts := opts.Clone() |
| 649 |
nopts.Port++ |
| 650 |
nopts.Cluster.Port++ |
| 651 |
nopts.HTTPPort++ |
| 652 |
return nopts |
| 653 |
} |
| 654 |
|
| 655 |
func createTempFile(t testing.TB, prefix string) *os.File { |
| 656 |
t.Helper() |
| 657 |
file, err := os.CreateTemp(t.TempDir(), prefix) |
| 658 |
if err != nil { |
| 659 |
t.Fatal(err) |
| 660 |
} |
| 661 |
return file |
| 662 |
} |