diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 35b85b60a23..7ba6d06d660 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -83,6 +83,24 @@ jobs: - name: Build NATS Server run: go build + store: + name: Store tests + needs: [build-latest, build-supported, lint] + runs-on: ${{ vars.GHA_WORKER_MEDIUM }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Go + uses: actions/setup-go@v5 + with: + go-version: stable + + - name: Run unit tests + run: | + go test -race -v -run=TestMemStore ./server/... -count=1 -vet=off -timeout=30m -failfast + go test -race -v -run=TestFileStore ./server/... -count=1 -vet=off -timeout=30m -failfast + js-no-cluster: name: JetStream tests needs: [build-latest, build-supported, lint] @@ -212,8 +230,24 @@ jobs: - name: Run unit tests run: go test -race -v -run=TestMQTT ./server/... -count=1 -vet=off -timeout=30m -failfast + msgtrace: + name: MsgTrace tests + needs: [build-latest, build-supported, lint] + runs-on: ${{ vars.GHA_WORKER_MEDIUM }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Go + uses: actions/setup-go@v5 + with: + go-version: stable + + - name: Run unit tests + run: go test -race -v -run=TestMsgTrace ./server/... -count=1 -vet=off -timeout=30m -failfast + server-pkg-non-js: - name: Non-JetStream/MQTT tests + name: Non-JetStream/MQTT/MsgTrace tests needs: [build-latest, build-supported, lint] runs-on: ${{ vars.GHA_WORKER_LARGE }} steps: @@ -226,7 +260,7 @@ jobs: go-version: stable - name: Run unit tests - run: go test -race -v -p=1 ./server/... -tags=skip_js_tests,skip_mqtt_tests -count=1 -vet=off -timeout=30m -failfast + run: go test -race -v -p=1 ./server/... -tags=skip_js_tests,skip_store_tests,skip_mqtt_tests,skip_msgtrace_tests -count=1 -vet=off -timeout=30m -failfast timeout-minutes: 15 non-server-pkg: diff --git a/.travis.yml b/.travis.yml index 01ef9557102..ad9dcc1181c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,6 +24,8 @@ jobs: env: TEST_SUITE=compile - name: "Run TestNoRace tests" env: TEST_SUITE=no_race_tests + - name: "Run Store tests" + env: TEST_SUITE=store_tests - name: "Run JetStream tests" env: TEST_SUITE=js_tests - name: "Run JetStream cluster tests (1)" @@ -36,7 +38,9 @@ jobs: env: TEST_SUITE=js_super_cluster_tests - name: "Run MQTT tests" env: TEST_SUITE=mqtt_tests - - name: "Run non JetStream/MQTT tests from the server package" + - name: "Run Message Tracing tests" + env: TEST_SUITE=msgtrace_tests + - name: "Run all other tests from the server package" env: TEST_SUITE=srv_pkg_non_js_tests - name: "Run all tests from all other packages" env: TEST_SUITE=non_srv_pkg_tests diff --git a/conf/lex.go b/conf/lex.go index b18447df864..013b8838663 100644 --- a/conf/lex.go +++ b/conf/lex.go @@ -236,7 +236,7 @@ func (lx *lexer) peek() rune { // errorf stops all lexing by emitting an error and returning `nil`. // Note that any value that is a character is escaped if it's a special // character (new lines, tabs, etc.). -func (lx *lexer) errorf(format string, values ...interface{}) stateFn { +func (lx *lexer) errorf(format string, values ...any) stateFn { for i, value := range values { if v, ok := value.(rune); ok { values[i] = escapeSpecial(v) diff --git a/conf/parse.go b/conf/parse.go index c104c307f11..bf5953c1b26 100644 --- a/conf/parse.go +++ b/conf/parse.go @@ -36,14 +36,14 @@ import ( ) type parser struct { - mapping map[string]interface{} + mapping map[string]any lx *lexer // The current scoped context, can be array or map - ctx interface{} + ctx any // stack of contexts, either map or array/slice stack - ctxs []interface{} + ctxs []any // Keys stack keys []string @@ -58,10 +58,10 @@ type parser struct { pedantic bool } -// Parse will return a map of keys to interface{}, although concrete types +// Parse will return a map of keys to any, although concrete types // underly them. The values supported are string, bool, int64, float64, DateTime. // Arrays and nested Maps are also supported. -func Parse(data string) (map[string]interface{}, error) { +func Parse(data string) (map[string]any, error) { p, err := parse(data, "", false) if err != nil { return nil, err @@ -70,7 +70,7 @@ func Parse(data string) (map[string]interface{}, error) { } // ParseFile is a helper to open file, etc. and parse the contents. -func ParseFile(fp string) (map[string]interface{}, error) { +func ParseFile(fp string) (map[string]any, error) { data, err := os.ReadFile(fp) if err != nil { return nil, fmt.Errorf("error opening config file: %v", err) @@ -84,7 +84,7 @@ func ParseFile(fp string) (map[string]interface{}, error) { } // ParseFileWithChecks is equivalent to ParseFile but runs in pedantic mode. -func ParseFileWithChecks(fp string) (map[string]interface{}, error) { +func ParseFileWithChecks(fp string) (map[string]any, error) { data, err := os.ReadFile(fp) if err != nil { return nil, err @@ -100,12 +100,12 @@ func ParseFileWithChecks(fp string) (map[string]interface{}, error) { type token struct { item item - value interface{} + value any usedVariable bool sourceFile string } -func (t *token) Value() interface{} { +func (t *token) Value() any { return t.value } @@ -127,9 +127,9 @@ func (t *token) Position() int { func parse(data, fp string, pedantic bool) (p *parser, err error) { p = &parser{ - mapping: make(map[string]interface{}), + mapping: make(map[string]any), lx: lex(data), - ctxs: make([]interface{}, 0, 4), + ctxs: make([]any, 0, 4), keys: make([]string, 0, 4), ikeys: make([]item, 0, 4), fp: filepath.Dir(fp), @@ -160,12 +160,12 @@ func (p *parser) next() item { return p.lx.nextItem() } -func (p *parser) pushContext(ctx interface{}) { +func (p *parser) pushContext(ctx any) { p.ctxs = append(p.ctxs, ctx) p.ctx = ctx } -func (p *parser) popContext() interface{} { +func (p *parser) popContext() any { if len(p.ctxs) == 0 { panic("BUG in parser, context stack empty") } @@ -205,7 +205,7 @@ func (p *parser) popItemKey() item { } func (p *parser) processItem(it item, fp string) error { - setValue := func(it item, v interface{}) { + setValue := func(it item, v any) { if p.pedantic { p.setValue(&token{it, v, false, fp}) } else { @@ -226,7 +226,7 @@ func (p *parser) processItem(it item, fp string) error { p.pushItemKey(it) } case itemMapStart: - newCtx := make(map[string]interface{}) + newCtx := make(map[string]any) p.pushContext(newCtx) case itemMapEnd: setValue(it, p.popContext()) @@ -309,7 +309,7 @@ func (p *parser) processItem(it item, fp string) error { } setValue(it, dt) case itemArrayStart: - var array = make([]interface{}, 0) + var array = make([]any, 0) p.pushContext(array) case itemArrayEnd: array := p.ctx @@ -342,7 +342,7 @@ func (p *parser) processItem(it item, fp string) error { } case itemInclude: var ( - m map[string]interface{} + m map[string]any err error ) if p.pedantic { @@ -380,7 +380,7 @@ const bcryptPrefix = "2a$" // ignore array contexts and only process the map contexts.. // // Returns true for ok if it finds something, similar to map. -func (p *parser) lookupVariable(varReference string) (interface{}, bool, error) { +func (p *parser) lookupVariable(varReference string) (any, bool, error) { // Do special check to see if it is a raw bcrypt string. if strings.HasPrefix(varReference, bcryptPrefix) { return "$" + varReference, true, nil @@ -390,7 +390,7 @@ func (p *parser) lookupVariable(varReference string) (interface{}, bool, error) for i := len(p.ctxs) - 1; i >= 0; i-- { ctx := p.ctxs[i] // Process if it is a map context - if m, ok := ctx.(map[string]interface{}); ok { + if m, ok := ctx.(map[string]any); ok { if v, ok := m[varReference]; ok { return v, ok, nil } @@ -411,17 +411,17 @@ func (p *parser) lookupVariable(varReference string) (interface{}, bool, error) return nil, false, nil } -func (p *parser) setValue(val interface{}) { +func (p *parser) setValue(val any) { // Test to see if we are on an array or a map // Array processing - if ctx, ok := p.ctx.([]interface{}); ok { + if ctx, ok := p.ctx.([]any); ok { p.ctx = append(ctx, val) p.ctxs[len(p.ctxs)-1] = p.ctx } // Map processing - if ctx, ok := p.ctx.(map[string]interface{}); ok { + if ctx, ok := p.ctx.(map[string]any); ok { key := p.popKey() if p.pedantic { diff --git a/conf/parse_test.go b/conf/parse_test.go index 4e965d698ea..8cf1ea98f3b 100644 --- a/conf/parse_test.go +++ b/conf/parse_test.go @@ -12,7 +12,7 @@ import ( // Test to make sure we get what we expect. -func test(t *testing.T, data string, ex map[string]interface{}) { +func test(t *testing.T, data string, ex map[string]any) { t.Helper() m, err := Parse(data) if err != nil { @@ -28,7 +28,7 @@ func test(t *testing.T, data string, ex map[string]interface{}) { } func TestSimpleTopLevel(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "foo": "1", "bar": float64(2.2), "baz": true, @@ -38,7 +38,7 @@ func TestSimpleTopLevel(t *testing.T) { } func TestBools(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "foo": true, } test(t, "foo=true", ex) @@ -54,7 +54,7 @@ var varSample = ` ` func TestSimpleVariable(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "index": int64(22), "foo": int64(22), } @@ -71,9 +71,9 @@ var varNestedSample = ` ` func TestNestedVariable(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "index": int64(22), - "nest": map[string]interface{}{ + "nest": map[string]any{ "index": int64(11), "foo": int64(11), }, @@ -93,7 +93,7 @@ func TestMissingVariable(t *testing.T) { } func TestEnvVariable(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "foo": int64(22), } evar := "__UNIQ22__" @@ -103,7 +103,7 @@ func TestEnvVariable(t *testing.T) { } func TestEnvVariableString(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "foo": "xyz", } evar := "__UNIQ22__" @@ -124,7 +124,7 @@ func TestEnvVariableStringStartingWithNumber(t *testing.T) { } func TestEnvVariableStringStartingWithNumberAndSizeUnit(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "foo": "3Gyz", } evar := "__UNIQ22__" @@ -134,7 +134,7 @@ func TestEnvVariableStringStartingWithNumberAndSizeUnit(t *testing.T) { } func TestEnvVariableStringStartingWithNumberUsingQuotes(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "foo": "3xyz", } evar := "__UNIQ22__" @@ -144,7 +144,7 @@ func TestEnvVariableStringStartingWithNumberUsingQuotes(t *testing.T) { } func TestBcryptVariable(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "password": "$2a$11$ooo", } test(t, "password: $2a$11$ooo", ex) @@ -172,7 +172,7 @@ pib = 22PiB ` func TestConvenientNumbers(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "k": int64(8 * 1000), "kb": int64(4 * 1024), "ki": int64(3 * 1024), @@ -206,13 +206,13 @@ foo { ` func TestSample1(t *testing.T) { - ex := map[string]interface{}{ - "foo": map[string]interface{}{ - "host": map[string]interface{}{ + ex := map[string]any{ + "foo": map[string]any{ + "host": map[string]any{ "ip": "127.0.0.1", "port": int64(4242), }, - "servers": []interface{}{"a.com", "b.com", "c.com"}, + "servers": []any{"a.com", "b.com", "c.com"}, }, } test(t, sample1, ex) @@ -242,15 +242,15 @@ cluster { ` func TestSample2(t *testing.T) { - ex := map[string]interface{}{ - "cluster": map[string]interface{}{ + ex := map[string]any{ + "cluster": map[string]any{ "port": int64(4244), - "authorization": map[string]interface{}{ + "authorization": map[string]any{ "user": "route_user", "password": "top_secret", "timeout": int64(1), }, - "routes": []interface{}{ + "routes": []any{ "nats-route://foo:bar@apcera.me:4245", "nats-route://foo:bar@apcera.me:4246", }, @@ -269,8 +269,8 @@ text block.' ` func TestSample3(t *testing.T) { - ex := map[string]interface{}{ - "foo": map[string]interface{}{ + ex := map[string]any{ + "foo": map[string]any{ "expr": "(true == \"false\")", "text": "This is a multi-line\ntext block.", }, @@ -286,10 +286,10 @@ var sample4 = ` ` func TestSample4(t *testing.T) { - ex := map[string]interface{}{ - "array": []interface{}{ - map[string]interface{}{"abc": int64(123)}, - map[string]interface{}{"xyz": "word"}, + ex := map[string]any{ + "array": []any{ + map[string]any{"abc": int64(123)}, + map[string]any{"xyz": "word"}, }, } test(t, sample4, ex) @@ -303,7 +303,7 @@ var sample5 = ` func TestSample5(t *testing.T) { dt, _ := time.Parse("2006-01-02T15:04:05Z", "2016-05-04T18:53:41Z") - ex := map[string]interface{}{ + ex := map[string]any{ "now": dt, "gmt": false, } @@ -311,16 +311,16 @@ func TestSample5(t *testing.T) { } func TestIncludes(t *testing.T) { - ex := map[string]interface{}{ + ex := map[string]any{ "listen": "127.0.0.1:4222", - "authorization": map[string]interface{}{ + "authorization": map[string]any{ "ALICE_PASS": "$2a$10$UHR6GhotWhpLsKtVP0/i6.Nh9.fuY73cWjLoJjb2sKT8KISBcUW5q", "BOB_PASS": "$2a$11$dZM98SpGeI7dCFFGSpt.JObQcix8YHml4TBUZoge9R1uxnMIln5ly", - "users": []interface{}{ - map[string]interface{}{ + "users": []any{ + map[string]any{ "user": "alice", "password": "$2a$10$UHR6GhotWhpLsKtVP0/i6.Nh9.fuY73cWjLoJjb2sKT8KISBcUW5q"}, - map[string]interface{}{ + map[string]any{ "user": "bob", "password": "$2a$11$dZM98SpGeI7dCFFGSpt.JObQcix8YHml4TBUZoge9R1uxnMIln5ly"}, }, @@ -366,11 +366,11 @@ func TestIncludeVariablesWithChecks(t *testing.T) { if !ok { t.Errorf("Expected %q to be in the config", key) } - expectKeyVal := func(t *testing.T, m interface{}, expectedKey string, expectedVal string, expectedLine, expectedPos int) { + expectKeyVal := func(t *testing.T, m any, expectedKey string, expectedVal string, expectedLine, expectedPos int) { t.Helper() tk := m.(*token) v := tk.Value() - vv := v.(map[string]interface{}) + vv := v.(map[string]any) value, ok := vv[expectedKey] if !ok { t.Errorf("Expected key %q", expectedKey) @@ -603,7 +603,7 @@ func TestJSONParseCompat(t *testing.T) { name string input string includes map[string]string - expected map[string]interface{} + expected map[string]any }{ { "JSON with nested blocks", @@ -623,13 +623,13 @@ func TestJSONParseCompat(t *testing.T) { } `, nil, - map[string]interface{}{ + map[string]any{ "http_port": int64(8227), "port": int64(4227), "write_deadline": "1h", - "cluster": map[string]interface{}{ + "cluster": map[string]any{ "port": int64(6222), - "routes": []interface{}{ + "routes": []any{ "nats://127.0.0.1:4222", "nats://127.0.0.1:4223", "nats://127.0.0.1:4224", @@ -649,8 +649,8 @@ func TestJSONParseCompat(t *testing.T) { } `, nil, - map[string]interface{}{ - "jetstream": map[string]interface{}{ + map[string]any{ + "jetstream": map[string]any{ "store_dir": "/tmp/nats", "max_mem": int64(1_000_000), }, @@ -662,7 +662,7 @@ func TestJSONParseCompat(t *testing.T) { "JSON empty object in one line", `{}`, nil, - map[string]interface{}{}, + map[string]any{}, }, { "JSON empty object with line breaks", @@ -671,7 +671,7 @@ func TestJSONParseCompat(t *testing.T) { } `, nil, - map[string]interface{}{}, + map[string]any{}, }, { "JSON includes", @@ -684,28 +684,28 @@ func TestJSONParseCompat(t *testing.T) { `, map[string]string{ "foo.json": `{ "users": [ {"user": "foo"} ] }`, - "bar.json": `{ - "users": [ {"user": "bar"} ] + "bar.json": `{ + "users": [ {"user": "bar"} ] }`, "quux.json": `{}`, }, - map[string]interface{}{ - "accounts": map[string]interface{}{ - "foo": map[string]interface{}{ - "users": []interface{}{ - map[string]interface{}{ + map[string]any{ + "accounts": map[string]any{ + "foo": map[string]any{ + "users": []any{ + map[string]any{ "user": "foo", }, }, }, - "bar": map[string]interface{}{ - "users": []interface{}{ - map[string]interface{}{ + "bar": map[string]any{ + "users": []any{ + map[string]any{ "user": "bar", }, }, }, - "quux": map[string]interface{}{}, + "quux": map[string]any{}, }, }, }, diff --git a/internal/testhelper/logging.go b/internal/testhelper/logging.go index 2ae9ce6bb1d..b84f6206492 100644 --- a/internal/testhelper/logging.go +++ b/internal/testhelper/logging.go @@ -46,37 +46,37 @@ func (l *DummyLogger) aggregate() { } } -func (l *DummyLogger) Noticef(format string, v ...interface{}) { +func (l *DummyLogger) Noticef(format string, v ...any) { l.Lock() defer l.Unlock() l.Msg = fmt.Sprintf(format, v...) l.aggregate() } -func (l *DummyLogger) Errorf(format string, v ...interface{}) { +func (l *DummyLogger) Errorf(format string, v ...any) { l.Lock() defer l.Unlock() l.Msg = fmt.Sprintf(format, v...) l.aggregate() } -func (l *DummyLogger) Warnf(format string, v ...interface{}) { +func (l *DummyLogger) Warnf(format string, v ...any) { l.Lock() defer l.Unlock() l.Msg = fmt.Sprintf(format, v...) l.aggregate() } -func (l *DummyLogger) Fatalf(format string, v ...interface{}) { +func (l *DummyLogger) Fatalf(format string, v ...any) { l.Lock() defer l.Unlock() l.Msg = fmt.Sprintf(format, v...) l.aggregate() } -func (l *DummyLogger) Debugf(format string, v ...interface{}) { +func (l *DummyLogger) Debugf(format string, v ...any) { l.Lock() defer l.Unlock() l.Msg = fmt.Sprintf(format, v...) l.aggregate() } -func (l *DummyLogger) Tracef(format string, v ...interface{}) { +func (l *DummyLogger) Tracef(format string, v ...any) { l.Lock() defer l.Unlock() l.Msg = fmt.Sprintf(format, v...) diff --git a/logger/log.go b/logger/log.go index c90a50fd0bd..c0bb7563d4a 100644 --- a/logger/log.go +++ b/logger/log.go @@ -178,7 +178,7 @@ func (l *fileLogger) setMaxNumFiles(max int) { l.Unlock() } -func (l *fileLogger) logDirect(label, format string, v ...interface{}) int { +func (l *fileLogger) logDirect(label, format string, v ...any) int { var entrya = [256]byte{} var entry = entrya[:0] if l.pid != "" { @@ -368,34 +368,34 @@ func setColoredLabelFormats(l *Logger) { } // Noticef logs a notice statement -func (l *Logger) Noticef(format string, v ...interface{}) { +func (l *Logger) Noticef(format string, v ...any) { l.logger.Printf(l.infoLabel+format, v...) } // Warnf logs a notice statement -func (l *Logger) Warnf(format string, v ...interface{}) { +func (l *Logger) Warnf(format string, v ...any) { l.logger.Printf(l.warnLabel+format, v...) } // Errorf logs an error statement -func (l *Logger) Errorf(format string, v ...interface{}) { +func (l *Logger) Errorf(format string, v ...any) { l.logger.Printf(l.errorLabel+format, v...) } // Fatalf logs a fatal error -func (l *Logger) Fatalf(format string, v ...interface{}) { +func (l *Logger) Fatalf(format string, v ...any) { l.logger.Fatalf(l.fatalLabel+format, v...) } // Debugf logs a debug statement -func (l *Logger) Debugf(format string, v ...interface{}) { +func (l *Logger) Debugf(format string, v ...any) { if l.debug { l.logger.Printf(l.debugLabel+format, v...) } } // Tracef logs a trace statement -func (l *Logger) Tracef(format string, v ...interface{}) { +func (l *Logger) Tracef(format string, v ...any) { if l.trace { l.logger.Printf(l.traceLabel+format, v...) } diff --git a/logger/syslog.go b/logger/syslog.go index 6b5c429bc13..04b71d264be 100644 --- a/logger/syslog.go +++ b/logger/syslog.go @@ -99,34 +99,34 @@ func getNetworkAndAddr(fqn string) (network, addr string) { } // Noticef logs a notice statement -func (l *SysLogger) Noticef(format string, v ...interface{}) { +func (l *SysLogger) Noticef(format string, v ...any) { l.writer.Notice(fmt.Sprintf(format, v...)) } // Warnf logs a warning statement -func (l *SysLogger) Warnf(format string, v ...interface{}) { +func (l *SysLogger) Warnf(format string, v ...any) { l.writer.Warning(fmt.Sprintf(format, v...)) } // Fatalf logs a fatal error -func (l *SysLogger) Fatalf(format string, v ...interface{}) { +func (l *SysLogger) Fatalf(format string, v ...any) { l.writer.Crit(fmt.Sprintf(format, v...)) } // Errorf logs an error statement -func (l *SysLogger) Errorf(format string, v ...interface{}) { +func (l *SysLogger) Errorf(format string, v ...any) { l.writer.Err(fmt.Sprintf(format, v...)) } // Debugf logs a debug statement -func (l *SysLogger) Debugf(format string, v ...interface{}) { +func (l *SysLogger) Debugf(format string, v ...any) { if l.debug { l.writer.Debug(fmt.Sprintf(format, v...)) } } // Tracef logs a trace statement -func (l *SysLogger) Tracef(format string, v ...interface{}) { +func (l *SysLogger) Tracef(format string, v ...any) { if l.trace { l.writer.Notice(fmt.Sprintf(format, v...)) } diff --git a/logger/syslog_windows.go b/logger/syslog_windows.go index 77a098ce61b..f3c58266bff 100644 --- a/logger/syslog_windows.go +++ b/logger/syslog_windows.go @@ -70,42 +70,42 @@ func NewRemoteSysLogger(fqn string, debug, trace bool) *SysLogger { } } -func formatMsg(tag, format string, v ...interface{}) string { +func formatMsg(tag, format string, v ...any) string { orig := fmt.Sprintf(format, v...) return fmt.Sprintf("pid[%d][%s]: %s", os.Getpid(), tag, orig) } // Noticef logs a notice statement -func (l *SysLogger) Noticef(format string, v ...interface{}) { +func (l *SysLogger) Noticef(format string, v ...any) { l.writer.Info(1, formatMsg("NOTICE", format, v...)) } // Warnf logs a warning statement -func (l *SysLogger) Warnf(format string, v ...interface{}) { +func (l *SysLogger) Warnf(format string, v ...any) { l.writer.Info(1, formatMsg("WARN", format, v...)) } // Fatalf logs a fatal error -func (l *SysLogger) Fatalf(format string, v ...interface{}) { +func (l *SysLogger) Fatalf(format string, v ...any) { msg := formatMsg("FATAL", format, v...) l.writer.Error(5, msg) panic(msg) } // Errorf logs an error statement -func (l *SysLogger) Errorf(format string, v ...interface{}) { +func (l *SysLogger) Errorf(format string, v ...any) { l.writer.Error(2, formatMsg("ERROR", format, v...)) } // Debugf logs a debug statement -func (l *SysLogger) Debugf(format string, v ...interface{}) { +func (l *SysLogger) Debugf(format string, v ...any) { if l.debug { l.writer.Info(3, formatMsg("DEBUG", format, v...)) } } // Tracef logs a trace statement -func (l *SysLogger) Tracef(format string, v ...interface{}) { +func (l *SysLogger) Tracef(format string, v ...any) { if l.trace { l.writer.Info(4, formatMsg("TRACE", format, v...)) } diff --git a/scripts/runTestsOnTravis.sh b/scripts/runTestsOnTravis.sh index d7c47983a42..960c0b4c547 100755 --- a/scripts/runTestsOnTravis.sh +++ b/scripts/runTestsOnTravis.sh @@ -23,6 +23,14 @@ elif [ "$1" = "no_race_tests" ]; then go test -v -p=1 -run=TestNoRace ./... -count=1 -vet=off -timeout=30m -failfast +elif [ "$1" = "store_tests" ]; then + + # Run store tests. By convention, all file store tests start with `TestFileStore`, + # and memory store tests start with `TestMemStore`. + + go test -race -v -run=TestMemStore ./server -count=1 -vet=off -timeout=30m -failfast + go test -race -v -run=TestFileStore ./server -count=1 -vet=off -timeout=30m -failfast + elif [ "$1" = "js_tests" ]; then # Run JetStream non-clustered tests. By convention, all JS tests start @@ -76,13 +84,20 @@ elif [ "$1" = "mqtt_tests" ]; then go test -race -v -run=TestMQTT ./server -count=1 -vet=off -timeout=30m -failfast +elif [ "$1" = "msgtrace_tests" ]; then + + # Run Message Tracing tests. By convention, all message tracing tests start with `TestMsgTrace`. + + go test -race -v -run=TestMsgTrace ./server -count=1 -vet=off -timeout=30m -failfast + elif [ "$1" = "srv_pkg_non_js_tests" ]; then # Run all non JetStream tests in the server package. We exclude the - # JS tests by using the `skip_js_tests` build tag and MQTT tests by - # using the `skip_mqtt_tests` + # store tests by using the `skip_store_tests` build tag, the JS tests + # by using `skip_js_tests`, MQTT tests by using `skip_mqtt_tests` and + # message tracing tests by using `skip_msgtrace_tests`. - go test -race -v -p=1 ./server/... -tags=skip_js_tests,skip_mqtt_tests -count=1 -vet=off -timeout=30m -failfast + go test -race -v -p=1 ./server/... -tags=skip_store_tests,skip_js_tests,skip_mqtt_tests,skip_msgtrace_tests -count=1 -vet=off -timeout=30m -failfast elif [ "$1" = "non_srv_pkg_tests" ]; then diff --git a/server/accounts.go b/server/accounts.go index 9b4136eae70..9ba0d7547bf 100644 --- a/server/accounts.go +++ b/server/accounts.go @@ -1157,7 +1157,7 @@ func (a *Account) TrackServiceExportWithSampling(service, results string, sampli } // Now track down the imports and add in latency as needed to enable. - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) acc.mu.Lock() for _, im := range acc.imports.services { @@ -1198,7 +1198,7 @@ func (a *Account) UnTrackServiceExport(service string) { } // Now track down the imports and clean them up. - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) acc.mu.Lock() for _, im := range acc.imports.services { @@ -3498,7 +3498,7 @@ func (s *Server) updateAccountClaimsWithRefresh(a *Account, ac *jwt.AccountClaim clients := map[*client]struct{}{} // We need to check all accounts that have an import claim from this account. awcsti := map[string]struct{}{} - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) // Move to the next if this account is actually account "a". if acc.Name == a.Name { @@ -3528,7 +3528,7 @@ func (s *Server) updateAccountClaimsWithRefresh(a *Account, ac *jwt.AccountClaim } // Now check if service exports have changed. if !a.checkServiceExportsEqual(old) || signersChanged || serviceTokenExpirationChanged { - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) // Move to the next if this account is actually account "a". if acc.Name == a.Name { @@ -3723,7 +3723,7 @@ func (s *Server) updateAccountClaimsWithRefresh(a *Account, ac *jwt.AccountClaim if _, ok := s.incompleteAccExporterMap.Load(old.Name); ok && refreshImportingAccounts { s.incompleteAccExporterMap.Delete(old.Name) - s.accounts.Range(func(key, value interface{}) bool { + s.accounts.Range(func(key, value any) bool { acc := value.(*Account) acc.mu.RLock() incomplete := acc.incomplete @@ -4026,13 +4026,13 @@ func handleListRequest(store *DirJWTStore, s *Server, reply string) { } else { s.Debugf("list request responded with %d account ids", len(accIds)) server := &ServerInfo{} - response := map[string]interface{}{"server": server, "data": accIds} + response := map[string]any{"server": server, "data": accIds} s.sendInternalMsgLocked(reply, _EMPTY_, server, response) } } func handleDeleteRequest(store *DirJWTStore, s *Server, msg []byte, reply string) { - var accIds []interface{} + var accIds []any var subj, sysAccName string if sysAcc := s.SystemAccount(); sysAcc != nil { sysAccName = sysAcc.GetName() @@ -4049,7 +4049,7 @@ func handleDeleteRequest(store *DirJWTStore, s *Server, msg []byte, reply string err = fmt.Errorf("not trusted") } else if list, ok := gk.Data["accounts"]; !ok { err = fmt.Errorf("malformed request") - } else if accIds, ok = list.([]interface{}); !ok { + } else if accIds, ok = list.([]any); !ok { err = fmt.Errorf("malformed request") } else { for _, entry := range accIds { diff --git a/server/avl/norace_test.go b/server/avl/norace_test.go index 6ea26c0493e..14c9a1c63f4 100644 --- a/server/avl/norace_test.go +++ b/server/avl/norace_test.go @@ -193,7 +193,7 @@ func friendlyBytes[T int | uint64 | int64](bytes T) string { return fmt.Sprintf("%.2f %sB", fbytes/math.Pow(float64(base), float64(exp)), pre[index]) } -func logResults(format string, args ...interface{}) { +func logResults(format string, args ...any) { if *printResults { fmt.Printf(format, args...) } diff --git a/server/certidp/certidp.go b/server/certidp/certidp.go index e066ed43f08..c1d96782318 100644 --- a/server/certidp/certidp.go +++ b/server/certidp/certidp.go @@ -121,11 +121,11 @@ func NewOCSPPeerConfig() *OCSPPeerConfig { // Log is a neutral method of passing server loggers to plugins type Log struct { - Debugf func(format string, v ...interface{}) - Noticef func(format string, v ...interface{}) - Warnf func(format string, v ...interface{}) - Errorf func(format string, v ...interface{}) - Tracef func(format string, v ...interface{}) + Debugf func(format string, v ...any) + Noticef func(format string, v ...any) + Warnf func(format string, v ...any) + Errorf func(format string, v ...any) + Tracef func(format string, v ...any) } type CertInfo struct { @@ -145,7 +145,7 @@ For client, leaf spoke (remotes), and leaf hub connections, you may enable OCSP ... # short form enables peer verify and takes option defaults ocsp_peer: true - + # long form includes settable options ocsp_peer { # Enable OCSP peer validation (default false) diff --git a/server/client.go b/server/client.go index 3c3a6d5eed2..5ce6de135d8 100644 --- a/server/client.go +++ b/server/client.go @@ -1881,7 +1881,7 @@ func (c *client) traceOutOp(op string, arg []byte) { } func (c *client) traceOp(format, op string, arg []byte) { - opa := []interface{}{} + opa := []any{} if op != _EMPTY_ { opa = append(opa, op) } @@ -3772,7 +3772,7 @@ func (c *client) prunePubPermsCache() { } const maxPruneAtOnce = 1000 r := 0 - c.perms.pcache.Range(func(k, _ interface{}) bool { + c.perms.pcache.Range(func(k, _ any) bool { c.perms.pcache.Delete(k) if r++; (r > pruneSize && atomic.LoadInt32(&c.perms.pcsz) < int32(maxPermCacheSize)) || (r > maxPruneAtOnce) { @@ -4413,7 +4413,7 @@ func (c *client) processServiceImport(si *serviceImport, acc *Account, msg []byt // if the message is routed, it does not initialize tracing in the // remote. positions := disableTraceHeaders(c, msg) - defer enableTraceHeaders(c, msg, positions) + defer enableTraceHeaders(msg, positions) } } } @@ -5985,32 +5985,32 @@ func (c *client) Error(err error) { c.srv.Errors(c, err) } -func (c *client) Errorf(format string, v ...interface{}) { +func (c *client) Errorf(format string, v ...any) { format = fmt.Sprintf("%s - %s", c, format) c.srv.Errorf(format, v...) } -func (c *client) Debugf(format string, v ...interface{}) { +func (c *client) Debugf(format string, v ...any) { format = fmt.Sprintf("%s - %s", c, format) c.srv.Debugf(format, v...) } -func (c *client) Noticef(format string, v ...interface{}) { +func (c *client) Noticef(format string, v ...any) { format = fmt.Sprintf("%s - %s", c, format) c.srv.Noticef(format, v...) } -func (c *client) Tracef(format string, v ...interface{}) { +func (c *client) Tracef(format string, v ...any) { format = fmt.Sprintf("%s - %s", c, format) c.srv.Tracef(format, v...) } -func (c *client) Warnf(format string, v ...interface{}) { +func (c *client) Warnf(format string, v ...any) { format = fmt.Sprintf("%s - %s", c, format) c.srv.Warnf(format, v...) } -func (c *client) RateLimitWarnf(format string, v ...interface{}) { +func (c *client) RateLimitWarnf(format string, v ...any) { // Do the check before adding the client info to the format... statement := fmt.Sprintf(format, v...) if _, loaded := c.srv.rateLimitLogging.LoadOrStore(statement, time.Now()); loaded { diff --git a/server/client_test.go b/server/client_test.go index a0a17799e67..663fca49ac6 100644 --- a/server/client_test.go +++ b/server/client_test.go @@ -1632,7 +1632,7 @@ type captureWarnLogger struct { warn chan string } -func (l *captureWarnLogger) Warnf(format string, v ...interface{}) { +func (l *captureWarnLogger) Warnf(format string, v ...any) { select { case l.warn <- fmt.Sprintf(format, v...): default: @@ -2193,7 +2193,7 @@ type captureNoticeLogger struct { notices []string } -func (l *captureNoticeLogger) Noticef(format string, v ...interface{}) { +func (l *captureNoticeLogger) Noticef(format string, v ...any) { l.Lock() l.notices = append(l.notices, fmt.Sprintf(format, v...)) l.Unlock() diff --git a/server/consumer.go b/server/consumer.go index e25b67dcd09..0c01da94f07 100644 --- a/server/consumer.go +++ b/server/consumer.go @@ -3027,7 +3027,7 @@ type waitingRequest struct { // sync.Pool for waiting requests. var wrPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(waitingRequest) }, } diff --git a/server/dirstore.go b/server/dirstore.go index b39ab9ae082..66ca52599e3 100644 --- a/server/dirstore.go +++ b/server/dirstore.go @@ -103,7 +103,7 @@ func newDir(dirPath string, create bool) (string, error) { } // future proofing in case new options will be added -type dirJWTStoreOption interface{} +type dirJWTStoreOption any // Creates a directory based jwt store. // Reads files only, does NOT watch directories and files. @@ -598,7 +598,7 @@ func (q *expirationTracker) Swap(i, j int) { pq[j].index = j } -func (q *expirationTracker) Push(x interface{}) { +func (q *expirationTracker) Push(x any) { n := len(q.heap) item := x.(*jwtItem) item.index = n @@ -606,7 +606,7 @@ func (q *expirationTracker) Push(x interface{}) { q.idx[item.publicKey] = q.lru.PushBack(item) } -func (q *expirationTracker) Pop() interface{} { +func (q *expirationTracker) Pop() any { old := q.heap n := len(old) item := old[n-1] diff --git a/server/errors.go b/server/errors.go index c73c5a54580..8efa7ac02ea 100644 --- a/server/errors.go +++ b/server/errors.go @@ -318,7 +318,7 @@ type errCtx struct { ctx string } -func NewErrorCtx(err error, format string, args ...interface{}) error { +func NewErrorCtx(err error, format string, args ...any) error { return &errCtx{err, fmt.Sprintf(format, args...)} } diff --git a/server/events.go b/server/events.go index cd81ee3975d..65b4654ed47 100644 --- a/server/events.go +++ b/server/events.go @@ -357,7 +357,7 @@ type pubMsg struct { rply string si *ServerInfo hdr map[string]string - msg interface{} + msg any oct compressionType echo bool last bool @@ -366,7 +366,7 @@ type pubMsg struct { var pubMsgPool sync.Pool func newPubMsg(c *client, sub, rply string, si *ServerInfo, hdr map[string]string, - msg interface{}, oct compressionType, echo, last bool) *pubMsg { + msg any, oct compressionType, echo, last bool) *pubMsg { var m *pubMsg pm := pubMsgPool.Get() @@ -624,12 +624,12 @@ func (s *Server) sendShutdownEvent() { } // Used to send an internal message to an arbitrary account. -func (s *Server) sendInternalAccountMsg(a *Account, subject string, msg interface{}) error { +func (s *Server) sendInternalAccountMsg(a *Account, subject string, msg any) error { return s.sendInternalAccountMsgWithReply(a, subject, _EMPTY_, nil, msg, false) } // Used to send an internal message with an optional reply to an arbitrary account. -func (s *Server) sendInternalAccountMsgWithReply(a *Account, subject, reply string, hdr map[string]string, msg interface{}, echo bool) error { +func (s *Server) sendInternalAccountMsgWithReply(a *Account, subject, reply string, hdr map[string]string, msg any, echo bool) error { s.mu.RLock() if s.sys == nil || s.sys.sendq == nil { s.mu.RUnlock() @@ -666,7 +666,7 @@ func (s *Server) sendInternalAccountSysMsg(a *Account, subj string, si *ServerIn // This will queue up a message to be sent. // Lock should not be held. -func (s *Server) sendInternalMsgLocked(subj, rply string, si *ServerInfo, msg interface{}) { +func (s *Server) sendInternalMsgLocked(subj, rply string, si *ServerInfo, msg any) { s.mu.RLock() s.sendInternalMsg(subj, rply, si, msg) s.mu.RUnlock() @@ -674,7 +674,7 @@ func (s *Server) sendInternalMsgLocked(subj, rply string, si *ServerInfo, msg in // This will queue up a message to be sent. // Assumes lock is held on entry. -func (s *Server) sendInternalMsg(subj, rply string, si *ServerInfo, msg interface{}) { +func (s *Server) sendInternalMsg(subj, rply string, si *ServerInfo, msg any) { if s.sys == nil || s.sys.sendq == nil { return } @@ -693,7 +693,7 @@ func (s *Server) sendInternalResponse(subj string, response *ServerAPIResponse) } // Used to send internal messages from other system clients to avoid no echo issues. -func (c *client) sendInternalMsg(subj, rply string, si *ServerInfo, msg interface{}) { +func (c *client) sendInternalMsg(subj, rply string, si *ServerInfo, msg any) { if c == nil { return } @@ -1083,43 +1083,43 @@ func (s *Server) initEventTracking() { "STATSZ": s.statszReq, "VARZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &VarzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.Varz(&optz.VarzOptions) }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Varz(&optz.VarzOptions) }) }, "SUBSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &SubszEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.Subsz(&optz.SubszOptions) }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Subsz(&optz.SubszOptions) }) }, "CONNZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &ConnzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.Connz(&optz.ConnzOptions) }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Connz(&optz.ConnzOptions) }) }, "ROUTEZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &RoutezEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.Routez(&optz.RoutezOptions) }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Routez(&optz.RoutezOptions) }) }, "GATEWAYZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &GatewayzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.Gatewayz(&optz.GatewayzOptions) }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Gatewayz(&optz.GatewayzOptions) }) }, "LEAFZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &LeafzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.Leafz(&optz.LeafzOptions) }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Leafz(&optz.LeafzOptions) }) }, "ACCOUNTZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &AccountzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.Accountz(&optz.AccountzOptions) }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Accountz(&optz.AccountzOptions) }) }, "JSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &JszEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.Jsz(&optz.JSzOptions) }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Jsz(&optz.JSzOptions) }) }, "HEALTHZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &HealthzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.healthz(&optz.HealthzOptions), nil }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.healthz(&optz.HealthzOptions), nil }) }, "PROFILEZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &ProfilezEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { return s.profilez(&optz.ProfilezOptions), nil }) + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.profilez(&optz.ProfilezOptions), nil }) }, } for name, req := range monSrvc { @@ -1132,7 +1132,7 @@ func (s *Server) initEventTracking() { s.Errorf("Error setting up internal tracking: %v", err) } } - extractAccount := func(c *client, subject string, msg []byte) (string, error) { + extractAccount := func(subject string) (string, error) { if tk := strings.Split(subject, tsep); len(tk) != accReqTokens { return _EMPTY_, fmt.Errorf("subject %q is malformed", subject) } else { @@ -1142,8 +1142,8 @@ func (s *Server) initEventTracking() { monAccSrvc := map[string]sysMsgHandler{ "SUBSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &SubszEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { - if acc, err := extractAccount(c, subject, msg); err != nil { + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { + if acc, err := extractAccount(subject); err != nil { return nil, err } else { optz.SubszOptions.Subscriptions = true @@ -1154,8 +1154,8 @@ func (s *Server) initEventTracking() { }, "CONNZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &ConnzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { - if acc, err := extractAccount(c, subject, msg); err != nil { + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { + if acc, err := extractAccount(subject); err != nil { return nil, err } else { optz.ConnzOptions.Account = acc @@ -1165,8 +1165,8 @@ func (s *Server) initEventTracking() { }, "LEAFZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &LeafzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { - if acc, err := extractAccount(c, subject, msg); err != nil { + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { + if acc, err := extractAccount(subject); err != nil { return nil, err } else { optz.LeafzOptions.Account = acc @@ -1176,8 +1176,8 @@ func (s *Server) initEventTracking() { }, "JSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &JszEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { - if acc, err := extractAccount(c, subject, msg); err != nil { + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { + if acc, err := extractAccount(subject); err != nil { return nil, err } else { optz.Account = acc @@ -1187,8 +1187,8 @@ func (s *Server) initEventTracking() { }, "INFO": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &AccInfoEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { - if acc, err := extractAccount(c, subject, msg); err != nil { + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { + if acc, err := extractAccount(subject); err != nil { return nil, err } else { return s.accountInfo(acc) @@ -1200,8 +1200,8 @@ func (s *Server) initEventTracking() { // STATZ is also less heavy weight than INFO "STATZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &AccountStatzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { - if acc, err := extractAccount(c, subject, msg); err != nil { + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { + if acc, err := extractAccount(subject); err != nil { return nil, err } else if acc == "PING" { // Filter PING subject. Happens for server as well. But wildcards are not used return nil, errSkipZreq @@ -1236,7 +1236,7 @@ func (s *Server) initEventTracking() { if _, err := s.sysSubscribe(fmt.Sprintf(accPingReqSubj, "STATZ"), s.noInlineCallback(func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { optz := &AccountStatzEventOptions{} - s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (interface{}, error) { + s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { if stz, err := s.AccountStatz(&optz.AccountStatzOptions); err != nil { return nil, err } else if len(stz.Accounts) == 0 && !optz.IncludeUnused { @@ -1327,7 +1327,7 @@ func (s *Server) registerSystemImportsForExisting() { return } sacc := s.sys.account - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { a := v.(*Account) if a != sacc { accounts = append(accounts, a) @@ -1429,12 +1429,12 @@ func (s *Server) accountClaimUpdate(sub *subscription, c *client, _ *Account, su // Will update the remote count for clients. // Lock assume held. func (s *Server) processRemoteServerShutdown(sid string) { - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { v.(*Account).removeRemoteServer(sid) return true }) // Update any state in nodeInfo. - s.nodeToInfo.Range(func(k, v interface{}) bool { + s.nodeToInfo.Range(func(k, v any) bool { ni := v.(nodeInfo) if ni.id == sid { ni.offline = true @@ -1631,7 +1631,7 @@ func (s *Server) shutdownEventing() { defer s.mu.Unlock() // Whip through all accounts. - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { v.(*Account).clearEventing() return true }) @@ -1830,7 +1830,7 @@ const ( // ServerAPIResponse is the response type for the server API like varz, connz etc. type ServerAPIResponse struct { Server *ServerInfo `json:"server"` - Data interface{} `json:"data,omitempty"` + Data any `json:"data,omitempty"` Error *ApiError `json:"error,omitempty"` // Private to indicate compression if any. @@ -1908,7 +1908,7 @@ func getAcceptEncoding(hdr []byte) compressionType { return unsupportedCompression } -func (s *Server) zReq(c *client, reply string, hdr, msg []byte, fOpts *EventFilterOptions, optz interface{}, respf func() (interface{}, error)) { +func (s *Server) zReq(_ *client, reply string, hdr, msg []byte, fOpts *EventFilterOptions, optz any, respf func() (any, error)) { if !s.EventsEnabled() || reply == _EMPTY_ { return } @@ -2766,7 +2766,7 @@ func (s *Server) reloadConfig(sub *subscription, c *client, _ *Account, subject, } optz := &EventFilterOptions{} - s.zReq(c, reply, hdr, msg, optz, optz, func() (interface{}, error) { + s.zReq(c, reply, hdr, msg, optz, optz, func() (any, error) { // Reload the server config, as requested. return nil, s.Reload() }) @@ -2792,7 +2792,7 @@ func (s *Server) kickClient(_ *subscription, c *client, _ *Account, subject, rep } optz := &EventFilterOptions{} - s.zReq(c, reply, hdr, msg, optz, optz, func() (interface{}, error) { + s.zReq(c, reply, hdr, msg, optz, optz, func() (any, error) { return nil, s.DisconnectClientByID(req.CID) }) @@ -2810,7 +2810,7 @@ func (s *Server) ldmClient(_ *subscription, c *client, _ *Account, subject, repl } optz := &EventFilterOptions{} - s.zReq(c, reply, hdr, msg, optz, optz, func() (interface{}, error) { + s.zReq(c, reply, hdr, msg, optz, optz, func() (any, error) { return nil, s.LDMClientByID(req.CID) }) } diff --git a/server/events_test.go b/server/events_test.go index 4918e79aa78..400b9d035f2 100644 --- a/server/events_test.go +++ b/server/events_test.go @@ -68,7 +68,7 @@ func createUserCredsEx(t *testing.T, nuc *jwt.UserClaims, akp nkeys.KeyPair) nat return nats.UserJWT(userCB, sigCB) } -func createUserCreds(t *testing.T, s *Server, akp nkeys.KeyPair) nats.Option { +func createUserCreds(t *testing.T, _ *Server, akp nkeys.KeyPair) nats.Option { return createUserCredsEx(t, jwt.NewUserClaims("test"), akp) } @@ -2903,7 +2903,7 @@ func TestServerEventsPingStatsZFailFilter(t *testing.T) { if msg, err := nc.Request(serverStatsPingReqSubj, []byte(`{MALFORMEDJSON`), time.Second/4); err != nil { t.Fatalf("Error: %v", err) } else { - resp := make(map[string]map[string]interface{}) + resp := make(map[string]map[string]any) if err := json.Unmarshal(msg.Data, &resp); err != nil { t.Fatalf("Error unmarshalling the response json: %v", err) } @@ -2929,8 +2929,8 @@ func TestServerEventsPingMonitorz(t *testing.T) { tests := []struct { endpoint string - opt interface{} - resp interface{} + opt any + resp any respField []string }{ {"VARZ", nil, &Varz{}, @@ -3017,7 +3017,7 @@ func TestServerEventsPingMonitorz(t *testing.T) { if err != nil { t.Fatalf("Error receiving msg: %v", err) } - response1 := make(map[string]map[string]interface{}) + response1 := make(map[string]map[string]any) if err := json.Unmarshal(msg.Data, &response1); err != nil { t.Fatalf("Error unmarshalling response1 json: %v", err) @@ -3046,7 +3046,7 @@ func TestServerEventsPingMonitorz(t *testing.T) { if err != nil { t.Fatalf("Error receiving msg: %v", err) } - response2 := make(map[string]map[string]interface{}) + response2 := make(map[string]map[string]any) if err := json.Unmarshal(msg.Data, &response2); err != nil { t.Fatalf("Error unmarshalling the response2 json: %v", err) } diff --git a/server/filestore.go b/server/filestore.go index 517ab1016de..73eee4ac7f6 100644 --- a/server/filestore.go +++ b/server/filestore.go @@ -7817,7 +7817,7 @@ func (fs *fileStore) stop(writeState bool) error { const errFile = "errors.txt" // Stream our snapshot through S2 compression and tar. -func (fs *fileStore) streamSnapshot(w io.WriteCloser, state *StreamState, includeConsumers bool) { +func (fs *fileStore) streamSnapshot(w io.WriteCloser, includeConsumers bool) { defer w.Close() enc := s2.NewWriter(w) @@ -8030,7 +8030,7 @@ func (fs *fileStore) Snapshot(deadline time.Duration, checkMsgs, includeConsumer fs.FastState(&state) // Stream in separate Go routine. - go fs.streamSnapshot(pw, &state, includeConsumers) + go fs.streamSnapshot(pw, includeConsumers) return &SnapshotResult{pr, state}, nil } diff --git a/server/filestore_test.go b/server/filestore_test.go index 8f906ff3bab..45370cf7bb6 100644 --- a/server/filestore_test.go +++ b/server/filestore_test.go @@ -11,6 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build !skip_store_tests +// +build !skip_store_tests + package server import ( @@ -3011,7 +3014,7 @@ func TestFileStoreExpireMsgsOnStart(t *testing.T) { fs.mu.RUnlock() } - lastSeqForBlk := func(index int) uint64 { + lastSeqForBlk := func() uint64 { t.Helper() fs.mu.RLock() defer fs.mu.RUnlock() @@ -3066,7 +3069,7 @@ func TestFileStoreExpireMsgsOnStart(t *testing.T) { // Now delete 10 messages from the end of the first block which we will expire on restart. // We will expire up to seq 100, so delete 91-100. - lseq := lastSeqForBlk(0) + lseq := lastSeqForBlk() for seq := lseq; seq > lseq-10; seq-- { removed, err := fs.RemoveMsg(seq) if err != nil || !removed { diff --git a/server/gateway.go b/server/gateway.go index 1aab4e82d1f..ac9472d2b46 100644 --- a/server/gateway.go +++ b/server/gateway.go @@ -1203,7 +1203,7 @@ func (c *client) processGatewayInfo(info *Info) { // Starting 2.9.0, we are phasing out the optimistic mode, so change // all accounts to interest-only mode, unless instructed not to do so // in some tests. - s.accounts.Range(func(_, v interface{}) bool { + s.accounts.Range(func(_, v any) bool { acc := v.(*Account) s.switchAccountToInterestMode(acc.GetName()) return true @@ -1356,7 +1356,7 @@ func (s *Server) sendSubsToGateway(c *client, accountName string) { // This function will then execute appropriate function based on the command // contained in the protocol. // -func (s *Server) processGatewayInfoFromRoute(info *Info, routeSrvID string, route *client) { +func (s *Server) processGatewayInfoFromRoute(info *Info, routeSrvID string) { switch info.GatewayCmd { case gatewayCmdGossip: s.processImplicitGateway(info) @@ -2489,7 +2489,7 @@ func (g *srvGateway) shouldMapReplyForGatewaySend(acc *Account, reply []byte) bo } var subPool = &sync.Pool{ - New: func() interface{} { + New: func() any { return &subscription{} }, } @@ -3304,7 +3304,7 @@ func (s *Server) startGWReplyMapExpiration() { } now := time.Now().UnixNano() mapEmpty := true - s.gwrm.m.Range(func(k, v interface{}) bool { + s.gwrm.m.Range(func(k, v any) bool { g := k.(*gwReplyMapping) l := v.(sync.Locker) l.Lock() diff --git a/server/gateway_test.go b/server/gateway_test.go index 97d2f25aae2..52222f652f1 100644 --- a/server/gateway_test.go +++ b/server/gateway_test.go @@ -1378,7 +1378,7 @@ type gwReconnAttemptLogger struct { errCh chan string } -func (l *gwReconnAttemptLogger) Errorf(format string, v ...interface{}) { +func (l *gwReconnAttemptLogger) Errorf(format string, v ...any) { msg := fmt.Sprintf(format, v...) if strings.Contains(msg, `Error connecting to implicit gateway "A"`) { select { @@ -3023,7 +3023,7 @@ type checkErrorLogger struct { gotError bool } -func (l *checkErrorLogger) Errorf(format string, args ...interface{}) { +func (l *checkErrorLogger) Errorf(format string, args ...any) { l.DummyLogger.Errorf(format, args...) l.Lock() if strings.Contains(l.Msg, l.checkErrorStr) { @@ -3354,8 +3354,13 @@ func getInboundGatewayConnection(s *Server, name string) *client { var gwsa [4]*client var gws = gwsa[:0] s.getInboundGatewayConnections(&gws) - if len(gws) > 0 { - return gws[0] + for _, gw := range gws { + gw.mu.Lock() + ok := gw.gw.name == name + gw.mu.Unlock() + if ok { + return gw + } } return nil } @@ -3555,7 +3560,7 @@ func TestGatewaySendAllSubsBadProtocol(t *testing.T) { // For this test, make sure to use inbound from A so // A will reconnect when we send bad proto that // causes connection to be closed. - c := getInboundGatewayConnection(sa, "A") + c := getInboundGatewayConnection(sa, "B") // Mock an invalid protocol (account name missing) info := &Info{ Gateway: "B", @@ -3568,7 +3573,7 @@ func TestGatewaySendAllSubsBadProtocol(t *testing.T) { orgConn := c checkFor(t, 3*time.Second, 100*time.Millisecond, func() error { - curConn := getInboundGatewayConnection(sa, "A") + curConn := getInboundGatewayConnection(sa, "B") if orgConn == curConn { return fmt.Errorf("Not reconnected") } @@ -3581,7 +3586,7 @@ func TestGatewaySendAllSubsBadProtocol(t *testing.T) { // Refresh c = nil checkFor(t, 3*time.Second, 15*time.Millisecond, func() error { - c = getInboundGatewayConnection(sa, "A") + c = getInboundGatewayConnection(sa, "B") if c == nil { return fmt.Errorf("Did not reconnect") } @@ -3603,7 +3608,7 @@ func TestGatewaySendAllSubsBadProtocol(t *testing.T) { orgConn = c checkFor(t, 3*time.Second, 100*time.Millisecond, func() error { - curConn := getInboundGatewayConnection(sa, "A") + curConn := getInboundGatewayConnection(sa, "B") if orgConn == curConn { return fmt.Errorf("Not reconnected") } @@ -4352,7 +4357,7 @@ func TestGatewayServiceImportComplexSetup(t *testing.T) { if c == nil || c.opts.Name != sb2.ID() { t.Fatalf("A2 does not have outbound to B2") } - c = getInboundGatewayConnection(sa2, "A") + c = getInboundGatewayConnection(sa2, "B") if c != nil { t.Fatalf("Bad setup") } @@ -4360,7 +4365,7 @@ func TestGatewayServiceImportComplexSetup(t *testing.T) { if c == nil || c.opts.Name != sa1.ID() { t.Fatalf("B2 does not have outbound to A1") } - c = getInboundGatewayConnection(sb2, "B") + c = getInboundGatewayConnection(sb2, "A") if c == nil || c.opts.Name != sa2.ID() { t.Fatalf("Bad setup") } @@ -4694,7 +4699,7 @@ func TestGatewayServiceExportWithWildcards(t *testing.T) { if c == nil || c.opts.Name != sb2.ID() { t.Fatalf("A2 does not have outbound to B2") } - c = getInboundGatewayConnection(sa2, "A") + c = getInboundGatewayConnection(sa2, "B") if c != nil { t.Fatalf("Bad setup") } @@ -4702,7 +4707,7 @@ func TestGatewayServiceExportWithWildcards(t *testing.T) { if c == nil || c.opts.Name != sa1.ID() { t.Fatalf("B2 does not have outbound to A1") } - c = getInboundGatewayConnection(sb2, "B") + c = getInboundGatewayConnection(sb2, "A") if c == nil || c.opts.Name != sa2.ID() { t.Fatalf("Bad setup") } @@ -5764,7 +5769,7 @@ type captureGWInterestSwitchLogger struct { imss []string } -func (l *captureGWInterestSwitchLogger) Debugf(format string, args ...interface{}) { +func (l *captureGWInterestSwitchLogger) Debugf(format string, args ...any) { l.Lock() msg := fmt.Sprintf(format, args...) if strings.Contains(msg, fmt.Sprintf("switching account %q to %s mode", globalAccountName, InterestOnly)) || @@ -6020,7 +6025,7 @@ func TestGatewayReplyMapTracking(t *testing.T) { t.Fatalf("Client map should have %v entries, got %v", expectLenMap, lenMap) } srvMapEmpty := true - sb.gwrm.m.Range(func(_, _ interface{}) bool { + sb.gwrm.m.Range(func(_, _ any) bool { srvMapEmpty = false return false }) @@ -6973,7 +6978,7 @@ type testMissingOCSPStapleLogger struct { ch chan string } -func (l *testMissingOCSPStapleLogger) Errorf(format string, v ...interface{}) { +func (l *testMissingOCSPStapleLogger) Errorf(format string, v ...any) { msg := fmt.Sprintf(format, v...) if strings.Contains(msg, "peer missing OCSP Staple") { select { diff --git a/server/ipqueue_test.go b/server/ipqueue_test.go index 1800f2a136d..5034a246663 100644 --- a/server/ipqueue_test.go +++ b/server/ipqueue_test.go @@ -50,7 +50,7 @@ func TestIPQueueBasic(t *testing.T) { // Check that those 2 queues are registered var gotFirst bool var gotSecond bool - s.ipQueues.Range(func(k, v interface{}) bool { + s.ipQueues.Range(func(k, v any) bool { switch k.(string) { case "test": gotFirst = true @@ -71,7 +71,7 @@ func TestIPQueueBasic(t *testing.T) { q.unregister() q2.unregister() // They should have been removed from the map - s.ipQueues.Range(func(k, v interface{}) bool { + s.ipQueues.Range(func(k, v any) bool { t.Fatalf("Got queue %q", k.(string)) return false }) diff --git a/server/jetstream.go b/server/jetstream.go index 7b26ccf19ff..ab6debdacbc 100644 --- a/server/jetstream.go +++ b/server/jetstream.go @@ -842,7 +842,7 @@ func (s *Server) JetStreamEnabledForDomain() bool { var jsFound bool // If we are here we do not have JetStream enabled for ourselves, but we need to check all connected servers. // TODO(dlc) - Could optimize and memoize this. - s.nodeToInfo.Range(func(k, v interface{}) bool { + s.nodeToInfo.Range(func(k, v any) bool { // This should not be dependent on online status, so only check js. if v.(nodeInfo).js { jsFound = true diff --git a/server/jetstream_api.go b/server/jetstream_api.go index c2701c36958..0b5d5634469 100644 --- a/server/jetstream_api.go +++ b/server/jetstream_api.go @@ -1342,7 +1342,7 @@ func (s *Server) jsTemplateDeleteRequest(sub *subscription, c *client, _ *Accoun s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) } -func (s *Server) jsonResponse(v interface{}) string { +func (s *Server) jsonResponse(v any) string { b, err := json.Marshal(v) if err != nil { s.Warnf("Problem marshaling JSON for JetStream API:", err) @@ -2550,7 +2550,7 @@ func (s *Server) jsLeaderServerStreamMoveRequest(sub *subscription, c *client, _ peers = nil clusters := map[string]struct{}{} - s.nodeToInfo.Range(func(_, ni interface{}) bool { + s.nodeToInfo.Range(func(_, ni any) bool { if currCluster != ni.(nodeInfo).cluster { clusters[ni.(nodeInfo).cluster] = struct{}{} } @@ -2856,11 +2856,11 @@ func isEmptyRequest(req []byte) bool { return true } // If we are here we didn't get our simple match, but still could be valid. - var v interface{} + var v any if err := json.Unmarshal(req, &v); err != nil { return false } - vm, ok := v.(map[string]interface{}) + vm, ok := v.(map[string]any) if !ok { return false } @@ -3379,7 +3379,7 @@ func (s *Server) jsStreamRestoreRequest(sub *subscription, c *client, _ *Account } if s.JetStreamIsClustered() { - s.jsClusteredStreamRestoreRequest(ci, acc, &req, stream, subject, reply, rmsg) + s.jsClusteredStreamRestoreRequest(ci, acc, &req, subject, reply, rmsg) return } @@ -3709,7 +3709,7 @@ func (s *Server) jsStreamSnapshotRequest(sub *subscription, c *client, _ *Accoun }) // Now do the real streaming. - s.streamSnapshot(ci, acc, mset, sr, &req) + s.streamSnapshot(acc, mset, sr, &req) end := time.Now().UTC() @@ -3739,7 +3739,7 @@ const defaultSnapshotChunkSize = 128 * 1024 const defaultSnapshotWindowSize = 8 * 1024 * 1024 // 8MB // streamSnapshot will stream out our snapshot to the reply subject. -func (s *Server) streamSnapshot(ci *ClientInfo, acc *Account, mset *stream, sr *SnapshotResult, req *JSApiStreamSnapshotRequest) { +func (s *Server) streamSnapshot(acc *Account, mset *stream, sr *SnapshotResult, req *JSApiStreamSnapshotRequest) { chunkSize := req.ChunkSize if chunkSize == 0 { chunkSize = defaultSnapshotChunkSize diff --git a/server/jetstream_benchmark_test.go b/server/jetstream_benchmark_test.go index b939420a21b..348299d45eb 100644 --- a/server/jetstream_benchmark_test.go +++ b/server/jetstream_benchmark_test.go @@ -39,13 +39,13 @@ func BenchmarkJetStreamConsume(b *testing.B) { PublishBatchSize = 10000 ) - runSyncPushConsumer := func(b *testing.B, js nats.JetStreamContext, streamName, subject string) (int, int, int) { + runSyncPushConsumer := func(b *testing.B, js nats.JetStreamContext, streamName string) (int, int, int) { const nextMsgTimeout = 3 * time.Second subOpts := []nats.SubOpt{ nats.BindStream(streamName), } - sub, err := js.SubscribeSync("", subOpts...) + sub, err := js.SubscribeSync(_EMPTY_, subOpts...) if err != nil { b.Fatalf("Failed to subscribe: %v", err) } @@ -95,7 +95,7 @@ func BenchmarkJetStreamConsume(b *testing.B) { return uniqueConsumed, duplicates, errors } - runAsyncPushConsumer := func(b *testing.B, js nats.JetStreamContext, streamName, subject string, ordered, durable bool) (int, int, int) { + runAsyncPushConsumer := func(b *testing.B, js nats.JetStreamContext, streamName string, ordered, durable bool) (int, int, int) { const timeout = 3 * time.Minute bitset := NewBitset(uint64(b.N)) doneCh := make(chan bool, 1) @@ -151,7 +151,7 @@ func BenchmarkJetStreamConsume(b *testing.B) { subOpts = append(subOpts, nats.Durable("c")) } - sub, err := js.Subscribe("", handleMsg, subOpts...) + sub, err := js.Subscribe(_EMPTY_, handleMsg, subOpts...) if err != nil { b.Fatalf("Failed to subscribe: %v", err) } @@ -169,7 +169,7 @@ func BenchmarkJetStreamConsume(b *testing.B) { return uniqueConsumed, duplicates, errors } - runPullConsumer := func(b *testing.B, js nats.JetStreamContext, streamName, subject string, durable bool) (int, int, int) { + runPullConsumer := func(b *testing.B, js nats.JetStreamContext, streamName string, durable bool) (int, int, int) { const fetchMaxWait = nats.MaxWait(3 * time.Second) const fetchMaxMessages = 1000 @@ -180,7 +180,7 @@ func BenchmarkJetStreamConsume(b *testing.B) { nats.BindStream(streamName), } - consumerName := "" // Default ephemeral + consumerName := _EMPTY_ // Default ephemeral if durable { consumerName = "c" // Durable } @@ -372,17 +372,17 @@ func BenchmarkJetStreamConsume(b *testing.B) { switch ct { case PushSync: - consumed, duplicates, errors = runSyncPushConsumer(b, js, streamName, subject) + consumed, duplicates, errors = runSyncPushConsumer(b, js, streamName) case PushAsync: - consumed, duplicates, errors = runAsyncPushConsumer(b, js, streamName, subject, unordered, ephemeral) + consumed, duplicates, errors = runAsyncPushConsumer(b, js, streamName, unordered, ephemeral) case PushAsyncOrdered: - consumed, duplicates, errors = runAsyncPushConsumer(b, js, streamName, subject, ordered, ephemeral) + consumed, duplicates, errors = runAsyncPushConsumer(b, js, streamName, ordered, ephemeral) case PushAsyncDurable: - consumed, duplicates, errors = runAsyncPushConsumer(b, js, streamName, subject, unordered, durable) + consumed, duplicates, errors = runAsyncPushConsumer(b, js, streamName, unordered, durable) case PullDurable: - consumed, duplicates, errors = runPullConsumer(b, js, streamName, subject, durable) + consumed, duplicates, errors = runPullConsumer(b, js, streamName, durable) case PullEphemeral: - consumed, duplicates, errors = runPullConsumer(b, js, streamName, subject, ephemeral) + consumed, duplicates, errors = runPullConsumer(b, js, streamName, ephemeral) default: b.Fatalf("Unknown consumer type: %v", ct) } diff --git a/server/jetstream_cluster.go b/server/jetstream_cluster.go index c6ad6f5b0f9..e76bda67430 100644 --- a/server/jetstream_cluster.go +++ b/server/jetstream_cluster.go @@ -188,7 +188,7 @@ func (s *Server) trackedJetStreamServers() (js, total int) { if !s.isRunning() || !s.eventsEnabled() { return -1, -1 } - s.nodeToInfo.Range(func(k, v interface{}) bool { + s.nodeToInfo.Range(func(k, v any) bool { si := v.(nodeInfo) if si.js { js++ @@ -537,7 +537,7 @@ func (js *jetStream) isStreamHealthy(acc *Account, sa *streamAssignment) bool { if !mset.isCatchingUp() { return true } - } else if node != nil { + } else { // node != nil if node != mset.raftNode() { s.Warnf("Detected stream cluster node skew '%s > %s'", acc.GetName(), streamName) node.Delete() @@ -4157,7 +4157,6 @@ func (js *jetStream) processConsumerRemoval(ca *consumerAssignment) { js.mu.Unlock() return } - isMember := ca.Group.isMember(cc.meta.ID()) wasLeader := cc.isConsumerLeader(ca.Client.serviceAccount(), ca.Stream, ca.Name) // Delete from our state. @@ -4176,7 +4175,7 @@ func (js *jetStream) processConsumerRemoval(ca *consumerAssignment) { js.mu.Unlock() if needDelete { - js.processClusterDeleteConsumer(ca, isMember, wasLeader) + js.processClusterDeleteConsumer(ca, wasLeader) } } @@ -4434,7 +4433,7 @@ func (js *jetStream) processClusterCreateConsumer(ca *consumerAssignment, state } } -func (js *jetStream) processClusterDeleteConsumer(ca *consumerAssignment, isMember, wasLeader bool) { +func (js *jetStream) processClusterDeleteConsumer(ca *consumerAssignment, wasLeader bool) { if ca == nil { return } @@ -5235,7 +5234,8 @@ func (js *jetStream) processStreamAssignmentResults(sub *subscription, c *client // If cluster is defined we can not retry. if cfg.Placement == nil || cfg.Placement.Cluster == _EMPTY_ { // If we have additional clusters to try we can retry. - if ci != nil && len(ci.Alternates) > 0 { + // We have already verified that ci != nil. + if len(ci.Alternates) > 0 { if rg, err := js.createGroupForStream(ci, cfg); err != nil { s.Warnf("Retrying cluster placement for stream '%s > %s' failed due to placement error: %+v", result.Account, result.Stream, err) } else { @@ -6036,7 +6036,7 @@ var ( // blocking utility call to perform requests on the system account // returns (synchronized) v or error -func sysRequest[T any](s *Server, subjFormat string, args ...interface{}) (*T, error) { +func sysRequest[T any](s *Server, subjFormat string, args ...any) (*T, error) { isubj := fmt.Sprintf(subjFormat, args...) s.mu.Lock() @@ -6459,7 +6459,7 @@ func (s *Server) jsClusteredStreamRestoreRequest( ci *ClientInfo, acc *Account, req *JSApiStreamRestoreRequest, - stream, subject, reply string, rmsg []byte) { + subject, reply string, rmsg []byte) { js, cc := s.getJetStreamCluster() if js == nil || cc == nil { diff --git a/server/jetstream_cluster_1_test.go b/server/jetstream_cluster_1_test.go index 98cfed81b49..31353741d55 100644 --- a/server/jetstream_cluster_1_test.go +++ b/server/jetstream_cluster_1_test.go @@ -3876,7 +3876,7 @@ func TestJetStreamClusterAccountPurge(t *testing.T) { require_NoError(t, err) sysDirs += len(files) - 1 // sub 1 for _meta_ files, err = os.ReadDir(filepath.Join(s.getOpts().StoreDir, "jetstream", accpub, "streams")) - if err == nil || (err != nil && err.(*os.PathError).Error() == "no such file or directory") { + if err == nil || err.(*os.PathError).Error() == "no such file or directory" { accDirs += len(files) } } @@ -4149,7 +4149,7 @@ func TestJetStreamClusterPeerOffline(t *testing.T) { } var ok bool - ml.nodeToInfo.Range(func(k, v interface{}) bool { + ml.nodeToInfo.Range(func(k, v any) bool { if si := v.(nodeInfo); si.name == rs.Name() { if shouldBeOffline && si.offline || !shouldBeOffline && !si.offline { ok = true diff --git a/server/jetstream_cluster_2_test.go b/server/jetstream_cluster_2_test.go index d005d0c6521..1d51431339f 100644 --- a/server/jetstream_cluster_2_test.go +++ b/server/jetstream_cluster_2_test.go @@ -577,7 +577,7 @@ func TestJetStreamClusterSingleLeafNodeWithoutSharedSystemAccount(t *testing.T) // Check behavior of the account without JS. // Normally this should fail since our local account is not enabled. However, since we are bridging // via the leafnode we expect this to work here. - nc, js := jsClientConnectEx(t, ln, "CORE", nats.UserInfo("n", "p")) + nc, js := jsClientConnectEx(t, ln, []nats.JSOpt{nats.Domain("CORE")}, nats.UserInfo("n", "p")) defer nc.Close() si, err := js.AddStream(&nats.StreamConfig{ @@ -6767,7 +6767,7 @@ type captureCatchupWarnLogger struct { ch chan string } -func (l *captureCatchupWarnLogger) Warnf(format string, args ...interface{}) { +func (l *captureCatchupWarnLogger) Warnf(format string, args ...any) { msg := fmt.Sprintf(format, args...) if strings.Contains(msg, "simulate error") { select { diff --git a/server/jetstream_cluster_3_test.go b/server/jetstream_cluster_3_test.go index 90428c058b2..92492a58e8d 100644 --- a/server/jetstream_cluster_3_test.go +++ b/server/jetstream_cluster_3_test.go @@ -856,7 +856,7 @@ type testStreamLagWarnLogger struct { ch chan string } -func (l *testStreamLagWarnLogger) Warnf(format string, v ...interface{}) { +func (l *testStreamLagWarnLogger) Warnf(format string, v ...any) { msg := fmt.Sprintf(format, v...) if strings.Contains(msg, "has high message lag") { select { diff --git a/server/jetstream_consumer_test.go b/server/jetstream_consumer_test.go index a7de3a2e2fb..8e4f0338b27 100644 --- a/server/jetstream_consumer_test.go +++ b/server/jetstream_consumer_test.go @@ -100,12 +100,21 @@ func TestJetStreamConsumerMultipleFiltersRace(t *testing.T) { var seqs []uint64 var mu sync.Mutex - for i := 0; i < 10_000; i++ { - sendStreamMsg(t, nc, "one", "data") - sendStreamMsg(t, nc, "two", "data") - sendStreamMsg(t, nc, "three", "data") - sendStreamMsg(t, nc, "four", "data") + total := 10_000 + var wg sync.WaitGroup + + send := func(subj string) { + defer wg.Done() + for i := 0; i < total; i++ { + sendStreamMsg(t, nc, subj, "data") + } } + wg.Add(4) + go send("one") + go send("two") + go send("three") + go send("four") + wg.Wait() mset.addConsumer(&ConsumerConfig{ Durable: "consumer", @@ -114,10 +123,12 @@ func TestJetStreamConsumerMultipleFiltersRace(t *testing.T) { }) done := make(chan struct{}) + wg.Add(10) for i := 0; i < 10; i++ { go func(t *testing.T) { + defer wg.Done() - c, err := js.PullSubscribe("", "consumer", nats.Bind("TEST", "consumer")) + c, err := js.PullSubscribe(_EMPTY_, "consumer", nats.Bind("TEST", "consumer")) require_NoError(t, err) for { @@ -126,7 +137,7 @@ func TestJetStreamConsumerMultipleFiltersRace(t *testing.T) { return default: } - msgs, err := c.Fetch(10) + msgs, err := c.Fetch(10, nats.MaxWait(2*time.Second)) // We don't want to stop before at expected number of messages, as we want // to also test against getting to many messages. // Because of that, we ignore timeout and connection closed errors. @@ -146,11 +157,11 @@ func TestJetStreamConsumerMultipleFiltersRace(t *testing.T) { }(t) } - checkFor(t, time.Second*30, time.Second*1, func() error { + checkFor(t, 30*time.Second, 100*time.Millisecond, func() error { mu.Lock() defer mu.Unlock() - if len(seqs) != 30_000 { - return fmt.Errorf("found %d messages instead of %d", len(seqs), 30_000) + if len(seqs) != 3*total { + return fmt.Errorf("found %d messages instead of %d", len(seqs), 3*total) } sort.Slice(seqs, func(i, j int) bool { return seqs[i] < seqs[j] @@ -161,12 +172,10 @@ func TestJetStreamConsumerMultipleFiltersRace(t *testing.T) { return fmt.Errorf("sequence mismatch at %v", i) } } - return nil }) - close(done) - + wg.Wait() } func TestJetStreamConsumerMultipleConsumersSingleFilter(t *testing.T) { diff --git a/server/jetstream_errors.go b/server/jetstream_errors.go index 781f9856811..5a81aa67821 100644 --- a/server/jetstream_errors.go +++ b/server/jetstream_errors.go @@ -76,7 +76,7 @@ func (e *ApiError) Error() string { return fmt.Sprintf("%s (%d)", e.Description, e.ErrCode) } -func (e *ApiError) toReplacerArgs(replacements []interface{}) []string { +func (e *ApiError) toReplacerArgs(replacements []any) []string { var ( ra []string key string diff --git a/server/jetstream_helpers_test.go b/server/jetstream_helpers_test.go index f2c02dadf4e..bb907eaa028 100644 --- a/server/jetstream_helpers_test.go +++ b/server/jetstream_helpers_test.go @@ -1184,13 +1184,17 @@ func jsClientConnect(t testing.TB, s *Server, opts ...nats.Option) (*nats.Conn, return nc, js } -func jsClientConnectEx(t testing.TB, s *Server, domain string, opts ...nats.Option) (*nats.Conn, nats.JetStreamContext) { +func jsClientConnectEx(t testing.TB, s *Server, jsOpts []nats.JSOpt, opts ...nats.Option) (*nats.Conn, nats.JetStreamContext) { t.Helper() nc, err := nats.Connect(s.ClientURL(), opts...) if err != nil { t.Fatalf("Failed to create client: %v", err) } - js, err := nc.JetStream(nats.MaxWait(10*time.Second), nats.Domain(domain)) + jo := []nats.JSOpt{nats.MaxWait(10 * time.Second)} + if len(jsOpts) > 0 { + jo = append(jo, jsOpts...) + } + js, err := nc.JetStream(jo...) if err != nil { t.Fatalf("Unexpected error getting JetStream context: %v", err) } diff --git a/server/jetstream_jwt_test.go b/server/jetstream_jwt_test.go index e487053be79..4e261f41e45 100644 --- a/server/jetstream_jwt_test.go +++ b/server/jetstream_jwt_test.go @@ -40,7 +40,7 @@ func TestJetStreamJWTLimits(t *testing.T) { if msg, err := c.Request(fmt.Sprintf(accUpdateEventSubjNew, pubKey), []byte(jwt), time.Second); err != nil { t.Fatal("error not expected in this test", err) } else { - content := make(map[string]interface{}) + content := make(map[string]any) if err := json.Unmarshal(msg.Data, &content); err != nil { t.Fatalf("%v", err) } else if _, ok := content["data"]; !ok { diff --git a/server/jetstream_leafnode_test.go b/server/jetstream_leafnode_test.go index 5098275723b..bb2337d7f47 100644 --- a/server/jetstream_leafnode_test.go +++ b/server/jetstream_leafnode_test.go @@ -54,7 +54,7 @@ func TestJetStreamLeafNodeUniqueServerNameCrossJSDomain(t *testing.T) { } } cnt := 0 - s.nodeToInfo.Range(func(key, value interface{}) bool { + s.nodeToInfo.Range(func(key, value any) bool { cnt++ require_Equal(t, value.(nodeInfo).name, name) require_Equal(t, value.(nodeInfo).id, sIdExpected) diff --git a/server/jetstream_super_cluster_test.go b/server/jetstream_super_cluster_test.go index a000f959aa3..f37f2c23e67 100644 --- a/server/jetstream_super_cluster_test.go +++ b/server/jetstream_super_cluster_test.go @@ -916,7 +916,7 @@ func TestJetStreamSuperClusterGetNextRewrite(t *testing.T) { defer ln.Shutdown() c2 := sc.clusterForName("C2") - nc, js := jsClientConnectEx(t, c2.randomServer(), "C", nats.UserInfo("nojs", "p")) + nc, js := jsClientConnectEx(t, c2.randomServer(), []nats.JSOpt{nats.Domain("C")}, nats.UserInfo("nojs", "p")) defer nc.Close() // Create a stream and add messages. @@ -1079,7 +1079,7 @@ func TestJetStreamSuperClusterGetNextSubRace(t *testing.T) { t.Fatalf("Both servers in C2 had an inbound GW connection!") } - nc, js := jsClientConnectEx(t, c2Srv, "C", nats.UserInfo("nojs", "p")) + nc, js := jsClientConnectEx(t, c2Srv, []nats.JSOpt{nats.Domain("C")}, nats.UserInfo("nojs", "p")) defer nc.Close() _, err := js.AddStream(&nats.StreamConfig{Name: "foo"}) @@ -3767,7 +3767,7 @@ type captureGWRewriteLogger struct { ch chan string } -func (l *captureGWRewriteLogger) Tracef(format string, args ...interface{}) { +func (l *captureGWRewriteLogger) Tracef(format string, args ...any) { msg := fmt.Sprintf(format, args...) if strings.Contains(msg, "$JS.SNAPSHOT.ACK.TEST") && strings.Contains(msg, gwReplyPrefix) { select { diff --git a/server/jetstream_test.go b/server/jetstream_test.go index bb985f1ed73..419e584bd0b 100644 --- a/server/jetstream_test.go +++ b/server/jetstream_test.go @@ -13450,7 +13450,7 @@ func TestJetStreamDisabledLimitsEnforcementJWT(t *testing.T) { if msg, err := c.Request(fmt.Sprintf(accUpdateEventSubjNew, pubKey), []byte(jwt), time.Second); err != nil { t.Fatal("error not expected in this test", err) } else { - content := make(map[string]interface{}) + content := make(map[string]any) if err := json.Unmarshal(msg.Data, &content); err != nil { t.Fatalf("%v", err) } else if _, ok := content["data"]; !ok { diff --git a/server/jwt_test.go b/server/jwt_test.go index 28314150f6f..1dc228cc308 100644 --- a/server/jwt_test.go +++ b/server/jwt_test.go @@ -1900,7 +1900,7 @@ type captureDebugLogger struct { dbgCh chan string } -func (l *captureDebugLogger) Debugf(format string, v ...interface{}) { +func (l *captureDebugLogger) Debugf(format string, v ...any) { select { case l.dbgCh <- fmt.Sprintf(format, v...): default: @@ -3254,7 +3254,7 @@ func updateJwt(t *testing.T, url string, creds string, jwt string, respCnt int) require_NextMsg := func(sub *nats.Subscription) bool { t.Helper() msg := natsNexMsg(t, sub, time.Second) - content := make(map[string]interface{}) + content := make(map[string]any) json.Unmarshal(msg.Data, &content) if _, ok := content["data"]; ok { return true @@ -4889,7 +4889,7 @@ func createKey(t *testing.T) (nkeys.KeyPair, string) { return kp, syspub } -func encodeClaim(t *testing.T, claim *jwt.AccountClaims, pub string) string { +func encodeClaim(t *testing.T, claim *jwt.AccountClaims, _ string) string { t.Helper() theJWT, err := claim.Encode(oKp) require_NoError(t, err) @@ -4992,11 +4992,11 @@ func TestJWTHeader(t *testing.T) { case <-time.After(time.Second): t.Fatalf("should have received a response") case m := <-resChan: - obj := map[string]interface{}{} + obj := map[string]any{} err = json.Unmarshal(m.Data, &obj) require_NoError(t, err) // test if shared is honored - reqInfo := obj["requestor"].(map[string]interface{}) + reqInfo := obj["requestor"].(map[string]any) // fields always set require_True(t, reqInfo["acc"] != nil) require_True(t, reqInfo["rtt"] != nil) @@ -5189,7 +5189,6 @@ func TestJWTAccountTokenImportMisuse(t *testing.T) { TokenReq: true, }) aExpJwt := encodeClaim(t, aExpClaim, aExpPub) - aExpCreds := newUser(t, aExpKp) createImportingAccountClaim := func(aImpKp nkeys.KeyPair, aExpPub string, ac *jwt.ActivationClaims) (string, string) { t.Helper() @@ -5211,7 +5210,7 @@ func TestJWTAccountTokenImportMisuse(t *testing.T) { return aImpJwt, aImpCreds } - testConnect := func(aExpPub, aExpJwt, aExpCreds, aImpPub, aImpJwt, aImpCreds string) { + testConnect := func(aExpPub, aExpJwt, aImpPub, aImpJwt, aImpCreds string) { t.Helper() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/A/" { @@ -5269,7 +5268,7 @@ func TestJWTAccountTokenImportMisuse(t *testing.T) { ac.ImportType = jwt.Stream aImpJwt, aImpCreds := createImportingAccountClaim(aImpKp, aExpPub, ac) - testConnect(aExpPub, aExpJwt, aExpCreds, aImpPub, aImpJwt, aImpCreds) + testConnect(aExpPub, aExpJwt, aImpPub, aImpJwt, aImpCreds) testNatsResolver(aImpJwt) }) @@ -5281,7 +5280,7 @@ func TestJWTAccountTokenImportMisuse(t *testing.T) { ac.ImportType = jwt.Stream aImpJwt, aImpCreds := createImportingAccountClaim(aImpKp, aExpPub, ac) - testConnect(aExpPub, aExpJwt, aExpCreds, aImpPub, aImpJwt, aImpCreds) + testConnect(aExpPub, aExpJwt, aImpPub, aImpJwt, aImpCreds) testNatsResolver(aImpJwt) }) @@ -5293,7 +5292,7 @@ func TestJWTAccountTokenImportMisuse(t *testing.T) { ac.ImportType = jwt.Stream aImpJwt, aImpCreds := createImportingAccountClaim(aImpKp, aExpPub, ac) - testConnect(aExpPub, aExpJwt, aExpCreds, aImpPub, aImpJwt, aImpCreds) + testConnect(aExpPub, aExpJwt, aImpPub, aImpJwt, aImpCreds) testNatsResolver(aImpJwt) }) } @@ -6678,7 +6677,7 @@ func TestJWTAccountNATSResolverWrongCreds(t *testing.T) { nc.Close() require_NoLocalOrRemoteConnections(acc, srvs...) } - createAccountAndUser := func(limit bool, done chan struct{}, pubKey, jwt1, jwt2, creds *string) { + createAccountAndUser := func(pubKey, jwt1, jwt2, creds *string) { t.Helper() kp, _ := nkeys.CreateAccount() *pubKey, _ = kp.PublicKey() @@ -6696,26 +6695,20 @@ func TestJWTAccountNATSResolverWrongCreds(t *testing.T) { ujwt, err := uclaim.Encode(kp) require_NoError(t, err) *creds = genCredsFile(t, ujwt, seed) - done <- struct{}{} } // Create Accounts and corresponding user creds. - doneChan := make(chan struct{}, 4) - defer close(doneChan) var syspub, sysjwt, dummy1, sysCreds string - createAccountAndUser(false, doneChan, &syspub, &sysjwt, &dummy1, &sysCreds) + createAccountAndUser(&syspub, &sysjwt, &dummy1, &sysCreds) var apub, ajwt1, ajwt2, aCreds string - createAccountAndUser(true, doneChan, &apub, &ajwt1, &ajwt2, &aCreds) + createAccountAndUser(&apub, &ajwt1, &ajwt2, &aCreds) var bpub, bjwt1, bjwt2, bCreds string - createAccountAndUser(true, doneChan, &bpub, &bjwt1, &bjwt2, &bCreds) + createAccountAndUser(&bpub, &bjwt1, &bjwt2, &bCreds) // The one that is going to be missing. var cpub, cjwt1, cjwt2, cCreds string - createAccountAndUser(true, doneChan, &cpub, &cjwt1, &cjwt2, &cCreds) - for i := 0; i < cap(doneChan); i++ { - <-doneChan - } + createAccountAndUser(&cpub, &cjwt1, &cjwt2, &cCreds) // Create one directory for each server dirA := t.TempDir() dirB := t.TempDir() diff --git a/server/leafnode_test.go b/server/leafnode_test.go index 6c8f9bb10fb..aaabb988ef4 100644 --- a/server/leafnode_test.go +++ b/server/leafnode_test.go @@ -46,7 +46,7 @@ type captureLeafNodeRandomIPLogger struct { ips [3]int } -func (c *captureLeafNodeRandomIPLogger) Debugf(format string, v ...interface{}) { +func (c *captureLeafNodeRandomIPLogger) Debugf(format string, v ...any) { msg := fmt.Sprintf(format, v...) if strings.Contains(msg, "hostname_to_resolve") { ippos := strings.Index(msg, "127.0.0.") @@ -340,7 +340,7 @@ type captureErrorLogger struct { errCh chan string } -func (l *captureErrorLogger) Errorf(format string, v ...interface{}) { +func (l *captureErrorLogger) Errorf(format string, v ...any) { select { case l.errCh <- fmt.Sprintf(format, v...): default: @@ -822,7 +822,7 @@ type loopDetectedLogger struct { ch chan string } -func (l *loopDetectedLogger) Errorf(format string, v ...interface{}) { +func (l *loopDetectedLogger) Errorf(format string, v ...any) { msg := fmt.Sprintf(format, v...) if strings.Contains(msg, "Loop") { select { @@ -1804,11 +1804,11 @@ type chanLogger struct { triggerChan chan string } -func (l *chanLogger) Warnf(format string, v ...interface{}) { +func (l *chanLogger) Warnf(format string, v ...any) { l.triggerChan <- fmt.Sprintf(format, v...) } -func (l *chanLogger) Errorf(format string, v ...interface{}) { +func (l *chanLogger) Errorf(format string, v ...any) { l.triggerChan <- fmt.Sprintf(format, v...) } @@ -2124,14 +2124,14 @@ type oldConnReplacedLogger struct { warnCh chan string } -func (l *oldConnReplacedLogger) Errorf(format string, v ...interface{}) { +func (l *oldConnReplacedLogger) Errorf(format string, v ...any) { select { case l.errCh <- fmt.Sprintf(format, v...): default: } } -func (l *oldConnReplacedLogger) Warnf(format string, v ...interface{}) { +func (l *oldConnReplacedLogger) Warnf(format string, v ...any) { select { case l.warnCh <- fmt.Sprintf(format, v...): default: @@ -2461,7 +2461,7 @@ type parseRouteLSUnsubLogger struct { gotErr chan error } -func (l *parseRouteLSUnsubLogger) Errorf(format string, v ...interface{}) { +func (l *parseRouteLSUnsubLogger) Errorf(format string, v ...any) { err := fmt.Errorf(format, v...) select { case l.gotErr <- err: @@ -2469,7 +2469,7 @@ func (l *parseRouteLSUnsubLogger) Errorf(format string, v ...interface{}) { } } -func (l *parseRouteLSUnsubLogger) Tracef(format string, v ...interface{}) { +func (l *parseRouteLSUnsubLogger) Tracef(format string, v ...any) { trace := fmt.Sprintf(format, v...) if strings.Contains(trace, "LS- $G foo bar") { l.gotTrace <- struct{}{} @@ -4247,7 +4247,7 @@ type checkLeafMinVersionLogger struct { connCh chan string } -func (l *checkLeafMinVersionLogger) Errorf(format string, args ...interface{}) { +func (l *checkLeafMinVersionLogger) Errorf(format string, args ...any) { msg := fmt.Sprintf(format, args...) if strings.Contains(msg, "minimum version") { select { @@ -4257,7 +4257,7 @@ func (l *checkLeafMinVersionLogger) Errorf(format string, args ...interface{}) { } } -func (l *checkLeafMinVersionLogger) Noticef(format string, args ...interface{}) { +func (l *checkLeafMinVersionLogger) Noticef(format string, args ...any) { msg := fmt.Sprintf(format, args...) if strings.Contains(msg, "Leafnode connection created") { select { @@ -4621,7 +4621,7 @@ type testLeafTraceLogger struct { ch chan string } -func (l *testLeafTraceLogger) Tracef(format string, v ...interface{}) { +func (l *testLeafTraceLogger) Tracef(format string, v ...any) { msg := fmt.Sprintf(format, v...) // We will sub to 'baz' and to 'bar', so filter on 'ba' prefix. if strings.Contains(msg, "[LS+ ba") { diff --git a/server/log.go b/server/log.go index fdd8d85c2b7..e1b9078a5e2 100644 --- a/server/log.go +++ b/server/log.go @@ -27,22 +27,22 @@ import ( type Logger interface { // Log a notice statement - Noticef(format string, v ...interface{}) + Noticef(format string, v ...any) // Log a warning statement - Warnf(format string, v ...interface{}) + Warnf(format string, v ...any) // Log a fatal error - Fatalf(format string, v ...interface{}) + Fatalf(format string, v ...any) // Log an error - Errorf(format string, v ...interface{}) + Errorf(format string, v ...any) // Log a debug statement - Debugf(format string, v ...interface{}) + Debugf(format string, v ...any) // Log a trace statement - Tracef(format string, v ...interface{}) + Tracef(format string, v ...any) } // ConfigureLogger configures and sets the logger for the server. @@ -178,48 +178,48 @@ func (s *Server) ReOpenLogFile() { } // Noticef logs a notice statement -func (s *Server) Noticef(format string, v ...interface{}) { - s.executeLogCall(func(logger Logger, format string, v ...interface{}) { +func (s *Server) Noticef(format string, v ...any) { + s.executeLogCall(func(logger Logger, format string, v ...any) { logger.Noticef(format, v...) }, format, v...) } // Errorf logs an error -func (s *Server) Errorf(format string, v ...interface{}) { - s.executeLogCall(func(logger Logger, format string, v ...interface{}) { +func (s *Server) Errorf(format string, v ...any) { + s.executeLogCall(func(logger Logger, format string, v ...any) { logger.Errorf(format, v...) }, format, v...) } // Error logs an error with a scope -func (s *Server) Errors(scope interface{}, e error) { - s.executeLogCall(func(logger Logger, format string, v ...interface{}) { +func (s *Server) Errors(scope any, e error) { + s.executeLogCall(func(logger Logger, format string, v ...any) { logger.Errorf(format, v...) }, "%s - %s", scope, UnpackIfErrorCtx(e)) } // Error logs an error with a context func (s *Server) Errorc(ctx string, e error) { - s.executeLogCall(func(logger Logger, format string, v ...interface{}) { + s.executeLogCall(func(logger Logger, format string, v ...any) { logger.Errorf(format, v...) }, "%s: %s", ctx, UnpackIfErrorCtx(e)) } // Error logs an error with a scope and context -func (s *Server) Errorsc(scope interface{}, ctx string, e error) { - s.executeLogCall(func(logger Logger, format string, v ...interface{}) { +func (s *Server) Errorsc(scope any, ctx string, e error) { + s.executeLogCall(func(logger Logger, format string, v ...any) { logger.Errorf(format, v...) }, "%s - %s: %s", scope, ctx, UnpackIfErrorCtx(e)) } // Warnf logs a warning error -func (s *Server) Warnf(format string, v ...interface{}) { - s.executeLogCall(func(logger Logger, format string, v ...interface{}) { +func (s *Server) Warnf(format string, v ...any) { + s.executeLogCall(func(logger Logger, format string, v ...any) { logger.Warnf(format, v...) }, format, v...) } -func (s *Server) RateLimitWarnf(format string, v ...interface{}) { +func (s *Server) RateLimitWarnf(format string, v ...any) { statement := fmt.Sprintf(format, v...) if _, loaded := s.rateLimitLogging.LoadOrStore(statement, time.Now()); loaded { return @@ -227,7 +227,7 @@ func (s *Server) RateLimitWarnf(format string, v ...interface{}) { s.Warnf("%s", statement) } -func (s *Server) RateLimitDebugf(format string, v ...interface{}) { +func (s *Server) RateLimitDebugf(format string, v ...any) { statement := fmt.Sprintf(format, v...) if _, loaded := s.rateLimitLogging.LoadOrStore(statement, time.Now()); loaded { return @@ -236,35 +236,35 @@ func (s *Server) RateLimitDebugf(format string, v ...interface{}) { } // Fatalf logs a fatal error -func (s *Server) Fatalf(format string, v ...interface{}) { - s.executeLogCall(func(logger Logger, format string, v ...interface{}) { +func (s *Server) Fatalf(format string, v ...any) { + s.executeLogCall(func(logger Logger, format string, v ...any) { logger.Fatalf(format, v...) }, format, v...) } // Debugf logs a debug statement -func (s *Server) Debugf(format string, v ...interface{}) { +func (s *Server) Debugf(format string, v ...any) { if atomic.LoadInt32(&s.logging.debug) == 0 { return } - s.executeLogCall(func(logger Logger, format string, v ...interface{}) { + s.executeLogCall(func(logger Logger, format string, v ...any) { logger.Debugf(format, v...) }, format, v...) } // Tracef logs a trace statement -func (s *Server) Tracef(format string, v ...interface{}) { +func (s *Server) Tracef(format string, v ...any) { if atomic.LoadInt32(&s.logging.trace) == 0 { return } - s.executeLogCall(func(logger Logger, format string, v ...interface{}) { + s.executeLogCall(func(logger Logger, format string, v ...any) { logger.Tracef(format, v...) }, format, v...) } -func (s *Server) executeLogCall(f func(logger Logger, format string, v ...interface{}), format string, args ...interface{}) { +func (s *Server) executeLogCall(f func(logger Logger, format string, v ...any), format string, args ...any) { s.logging.RLock() defer s.logging.RUnlock() if s.logging.logger == nil { diff --git a/server/memstore_test.go b/server/memstore_test.go index e6e6e1d38f5..143c38b0e4c 100644 --- a/server/memstore_test.go +++ b/server/memstore_test.go @@ -11,6 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build !skip_store_tests +// +build !skip_store_tests + package server import ( diff --git a/server/monitor.go b/server/monitor.go index a5721956292..3da0930de20 100644 --- a/server/monitor.go +++ b/server/monitor.go @@ -993,7 +993,7 @@ func (s *Server) Subsz(opts *SubszOptions) (*Subsz, error) { if subdetail { var raw [4096]*subscription subs := raw[:0] - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) if filterAcc != _EMPTY_ && acc.GetName() != filterAcc { return true @@ -1034,7 +1034,7 @@ func (s *Server) Subsz(opts *SubszOptions) (*Subsz, error) { sz.Subs = details[minoff:maxoff] sz.Total = len(sz.Subs) } else { - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) if filterAcc != _EMPTY_ && acc.GetName() != filterAcc { return true @@ -1714,7 +1714,7 @@ func (s *Server) updateVarzRuntimeFields(v *Varz, forceUpdate bool, pcpu float64 // Make sure to reset in case we are re-using. v.Subscriptions = 0 - s.accounts.Range(func(k, val interface{}) bool { + s.accounts.Range(func(k, val any) bool { acc := val.(*Account) v.Subscriptions += acc.sl.Count() return true @@ -2006,7 +2006,7 @@ func createOutboundAccountsGatewayz(opts *GatewayzOptions, gw *gateway) []*Accou } accs := make([]*AccountGatewayz, 0, 4) - gw.outsim.Range(func(k, v interface{}) bool { + gw.outsim.Range(func(k, v any) bool { name := k.(string) a := createAccountOutboundGatewayz(name, v) accs = append(accs, a) @@ -2016,7 +2016,7 @@ func createOutboundAccountsGatewayz(opts *GatewayzOptions, gw *gateway) []*Accou } // Returns an AccountGatewayz for this gateway outbound connection -func createAccountOutboundGatewayz(name string, ei interface{}) *AccountGatewayz { +func createAccountOutboundGatewayz(name string, ei any) *AccountGatewayz { a := &AccountGatewayz{ Name: name, InterestOnlyThreshold: gatewayMaxRUnsubBeforeSwitch, @@ -2285,7 +2285,7 @@ func (s *Server) AccountStatz(opts *AccountStatzOptions) (*AccountStatz, error) Accounts: []*AccountStat{}, } if opts == nil || len(opts.Accounts) == 0 { - s.accounts.Range(func(key, a interface{}) bool { + s.accounts.Range(func(key, a any) bool { acc := a.(*Account) acc.mu.RLock() if opts.IncludeUnused || acc.numLocalConnections() != 0 { @@ -2535,7 +2535,7 @@ func (s *Server) Accountz(optz *AccountzOptions) (*Accountz, error) { } if optz == nil || optz.Account == _EMPTY_ { a.Accounts = []string{} - s.accounts.Range(func(key, value interface{}) bool { + s.accounts.Range(func(key, value any) bool { a.Accounts = append(a.Accounts, key.(string)) return true }) diff --git a/server/monitor_test.go b/server/monitor_test.go index 307923a01c0..718ff146511 100644 --- a/server/monitor_test.go +++ b/server/monitor_test.go @@ -544,7 +544,7 @@ func TestConnzWithCID(t *testing.T) { } // Helper to map to connection name -func createConnMap(t *testing.T, cz *Connz) map[string]*ConnInfo { +func createConnMap(cz *Connz) map[string]*ConnInfo { cm := make(map[string]*ConnInfo) for _, c := range cz.Conns { cm[c.Name] = c @@ -552,7 +552,7 @@ func createConnMap(t *testing.T, cz *Connz) map[string]*ConnInfo { return cm } -func getFooAndBar(t *testing.T, cm map[string]*ConnInfo) (*ConnInfo, *ConnInfo) { +func getFooAndBar(cm map[string]*ConnInfo) (*ConnInfo, *ConnInfo) { return cm["foo"], cm["bar"] } @@ -640,7 +640,7 @@ func TestConnzLastActivity(t *testing.T) { defer ncBar.Close() // Test inside details of each connection - ciFoo, ciBar := getFooAndBar(t, createConnMap(t, pollConz(t, s, mode, url, opts))) + ciFoo, ciBar := getFooAndBar(createConnMap(pollConz(t, s, mode, url, opts))) // Test that LastActivity is non-zero if ciFoo.LastActivity.IsZero() { @@ -666,7 +666,7 @@ func TestConnzLastActivity(t *testing.T) { sub, _ := ncFoo.Subscribe("hello.world", func(m *nats.Msg) {}) ensureServerActivityRecorded(t, ncFoo) - ciFoo, _ = getFooAndBar(t, createConnMap(t, pollConz(t, s, mode, url, opts))) + ciFoo, _ = getFooAndBar(createConnMap(pollConz(t, s, mode, url, opts))) nextLA := ciFoo.LastActivity if fooLA.Equal(nextLA) { t.Fatalf("Subscribe should have triggered update to LastActivity %+v\n", ciFoo) @@ -682,7 +682,7 @@ func TestConnzLastActivity(t *testing.T) { ensureServerActivityRecorded(t, ncFoo) ensureServerActivityRecorded(t, ncBar) - ciFoo, ciBar = getFooAndBar(t, createConnMap(t, pollConz(t, s, mode, url, opts))) + ciFoo, ciBar = getFooAndBar(createConnMap(pollConz(t, s, mode, url, opts))) nextLA = ciBar.LastActivity if barLA.Equal(nextLA) { t.Fatalf("Publish should have triggered update to LastActivity\n") @@ -701,7 +701,7 @@ func TestConnzLastActivity(t *testing.T) { sub.Unsubscribe() ensureServerActivityRecorded(t, ncFoo) - ciFoo, _ = getFooAndBar(t, createConnMap(t, pollConz(t, s, mode, url, opts))) + ciFoo, _ = getFooAndBar(createConnMap(pollConz(t, s, mode, url, opts))) nextLA = ciFoo.LastActivity if fooLA.Equal(nextLA) { t.Fatalf("Message delivery should have triggered update to LastActivity\n") @@ -2391,7 +2391,7 @@ func TestClusterEmptyWhenNotDefined(t *testing.T) { defer s.Shutdown() body := readBody(t, fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)) - var v map[string]interface{} + var v map[string]any if err := json.Unmarshal(body, &v); err != nil { t.Fatalf("Got an error unmarshalling the body: %v\n", err) } @@ -2400,7 +2400,7 @@ func TestClusterEmptyWhenNotDefined(t *testing.T) { if !ok { return } - if len(c.(map[string]interface{})) != 0 { + if len(c.(map[string]any)) != 0 { t.Fatalf("Expected an empty cluster definition, instead got %+v\n", c) } } @@ -5306,7 +5306,7 @@ func TestHealthzStatusUnavailable(t *testing.T) { } // When we converted ipq to use generics we still were using sync.Map. Currently you can not convert -// interface{} or any to a generic parameterized type. So this stopped working and panics. +// any or any to a generic parameterized type. So this stopped working and panics. func TestIpqzWithGenerics(t *testing.T) { opts := DefaultMonitorOptions() opts.JetStream = true diff --git a/server/mqtt.go b/server/mqtt.go index 4a4cea38699..df054d1b7f4 100644 --- a/server/mqtt.go +++ b/server/mqtt.go @@ -770,7 +770,7 @@ func (c *client) mqttParse(buf []byte) error { // PUBREC, PUBCOMP. case mqttPacketPubAck: var pi uint16 - pi, err = mqttParsePIPacket(r, pl) + pi, err = mqttParsePIPacket(r) if trace { c.traceInOp("PUBACK", errOrTrace(err, fmt.Sprintf("pi=%v", pi))) } @@ -780,7 +780,7 @@ func (c *client) mqttParse(buf []byte) error { case mqttPacketPubRec: var pi uint16 - pi, err = mqttParsePIPacket(r, pl) + pi, err = mqttParsePIPacket(r) if trace { c.traceInOp("PUBREC", errOrTrace(err, fmt.Sprintf("pi=%v", pi))) } @@ -790,7 +790,7 @@ func (c *client) mqttParse(buf []byte) error { case mqttPacketPubComp: var pi uint16 - pi, err = mqttParsePIPacket(r, pl) + pi, err = mqttParsePIPacket(r) if trace { c.traceInOp("PUBCOMP", errOrTrace(err, fmt.Sprintf("pi=%v", pi))) } @@ -815,7 +815,7 @@ func (c *client) mqttParse(buf []byte) error { case mqttPacketPubRel: var pi uint16 - pi, err = mqttParsePIPacket(r, pl) + pi, err = mqttParsePIPacket(r) if trace { c.traceInOp("PUBREL", errOrTrace(err, fmt.Sprintf("pi=%v", pi))) } @@ -878,7 +878,7 @@ func (c *client) mqttParse(buf []byte) error { var rc byte var cp *mqttConnectProto var sessp bool - rc, cp, err = c.mqttParseConnect(r, pl, hasMappings) + rc, cp, err = c.mqttParseConnect(r, hasMappings) // Add the client id to the client's string, regardless of error. // We may still get the client_id if the call above fails somewhere // after parsing the client ID itself. @@ -995,7 +995,7 @@ func (s *Server) mqttHandleClosedClient(c *client) { // No lock held on entry. func (s *Server) mqttUpdateMaxAckPending(newmaxp uint16) { msm := &s.mqtt.sessmgr - s.accounts.Range(func(k, _ interface{}) bool { + s.accounts.Range(func(k, _ any) bool { accName := k.(string) msm.mu.RLock() asm := msm.sessions[accName] @@ -1079,7 +1079,7 @@ func mqttParsePubRelNATSHeader(headerBytes []byte) uint16 { // Returns the MQTT sessions manager for a given account. // If new, creates the required JetStream streams/consumers // for handling of sessions and messages. -func (s *Server) getOrCreateMQTTAccountSessionManager(clientID string, c *client) (*mqttAccountSessionManager, error) { +func (s *Server) getOrCreateMQTTAccountSessionManager(c *client) (*mqttAccountSessionManager, error) { sm := &s.mqtt.sessmgr c.mu.Lock() @@ -1522,7 +1522,7 @@ func (s *Server) mqttDetermineReplicas() int { // ////////////////////////////////////////////////////////////////////////////// -func (jsa *mqttJSA) newRequest(kind, subject string, hdr int, msg []byte) (interface{}, error) { +func (jsa *mqttJSA) newRequest(kind, subject string, hdr int, msg []byte) (any, error) { return jsa.newRequestEx(kind, subject, _EMPTY_, hdr, msg, mqttJSAPITimeout) } @@ -2116,7 +2116,7 @@ func (as *mqttAccountSessionManager) cleanupRetainedMessageCache(s *Server, clos // should eventually clean up everything. i, maxScan := 0, 10*1000 now := time.Now() - as.rmsCache.Range(func(key, value interface{}) bool { + as.rmsCache.Range(func(key, value any) bool { rm := value.(*mqttRetainedMsg) if now.After(rm.expiresFromCache) { as.rmsCache.Delete(key) @@ -2378,14 +2378,13 @@ func (sess *mqttSession) processQOS12Sub( c *client, // subscribing client. subject, sid []byte, isReserved bool, qos byte, jsDurName string, h msgHandler, // subscription parameters. ) (*subscription, error) { - return sess.processSub(c, subject, sid, isReserved, qos, jsDurName, h, false, false, nil, false, nil) + return sess.processSub(c, subject, sid, isReserved, qos, jsDurName, h, false, nil, false, nil) } func (sess *mqttSession) processSub( c *client, // subscribing client. subject, sid []byte, isReserved bool, qos byte, jsDurName string, h msgHandler, // subscription parameters. initShadow bool, // do we need to scan for shadow subscriptions? (not for QOS1+) - serializeRMS bool, // do we need to serialize RMS? rms map[string]*mqttRetainedMsg, // preloaded rms (can be empty, or missing items if errors) trace bool, // trace serialized retained messages in the log? as *mqttAccountSessionManager, // needed only for rms serialization. @@ -2582,7 +2581,7 @@ func (as *mqttAccountSessionManager) processSubs(sess *mqttSession, c *client, bsubject, bsid, isReserved, f.qos, // main subject _EMPTY_, mqttDeliverMsgCbQoS0, // no jsDur for QOS0 processShadowSubs, - serializeRMS, rms, trace, as) + rms, trace, as) sess.mu.Unlock() as.mu.Unlock() @@ -2616,7 +2615,7 @@ func (as *mqttAccountSessionManager) processSubs(sess *mqttSession, c *client, []byte(fwcsubject), []byte(fwcsid), isReserved, f.qos, // FWC (top-level wildcard) subject _EMPTY_, mqttDeliverMsgCbQoS0, // no jsDur for QOS0 processShadowSubs, - serializeRMS, rms, trace, as) + rms, trace, as) sess.mu.Unlock() as.mu.Unlock() if err != nil { @@ -3471,7 +3470,7 @@ func (sess *mqttSession) deleteConsumer(cc *ConsumerConfig) { ////////////////////////////////////////////////////////////////////////////// // Parse the MQTT connect protocol -func (c *client) mqttParseConnect(r *mqttReader, pl int, hasMappings bool) (byte, *mqttConnectProto, error) { +func (c *client) mqttParseConnect(r *mqttReader, hasMappings bool) (byte, *mqttConnectProto, error) { // Protocol name proto, err := r.readBytes("protocol name", false) if err != nil { @@ -3710,7 +3709,7 @@ func (s *Server) mqttProcessConnect(c *client, cp *mqttConnectProto, trace bool) // Get the account's level MQTT sessions manager. If it does not exists yet, // this will create it along with the streams where sessions and messages // are stored. - asm, err := s.getOrCreateMQTTAccountSessionManager(cid, c) + asm, err := s.getOrCreateMQTTAccountSessionManager(c) if err != nil { return err } @@ -4463,7 +4462,7 @@ func (c *client) mqttEnqueuePubResponse(packetType byte, pi uint16, trace bool) } } -func mqttParsePIPacket(r *mqttReader, pl int) (uint16, error) { +func mqttParsePIPacket(r *mqttReader) (uint16, error) { pi, err := r.readUint16("packet identifier") if err != nil { return 0, err diff --git a/server/mqtt_test.go b/server/mqtt_test.go index 4358826eec6..3c70ec1b51d 100644 --- a/server/mqtt_test.go +++ b/server/mqtt_test.go @@ -1642,41 +1642,40 @@ func TestMQTTParseConnect(t *testing.T) { for _, test := range []struct { name string proto []byte - pl int err string }{ - {"packet in buffer error", []byte{0}, 10, io.ErrUnexpectedEOF.Error()}, - {"bad proto name", []byte{0, 4, 'B', 'A', 'D'}, 5, "protocol name"}, - {"invalid proto name", []byte{0, 3, 'B', 'A', 'D'}, 5, "expected connect packet with protocol name"}, - {"old proto not supported", []byte{0, 6, 'M', 'Q', 'I', 's', 'd', 'p'}, 8, "older protocol"}, - {"error on protocol level", []byte{0, 4, 'M', 'Q', 'T', 'T'}, 6, "protocol level"}, - {"unacceptable protocol version", []byte{0, 4, 'M', 'Q', 'T', 'T', 10}, 7, "unacceptable protocol version"}, - {"error on flags", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel}, 7, "flags"}, - {"reserved flag", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 1}, 8, errMQTTConnFlagReserved.Error()}, - {"will qos without will flag", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 1 << 3}, 8, "if Will flag is set to 0, Will QoS must be 0 too"}, - {"will retain without will flag", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 1 << 5}, 8, errMQTTWillAndRetainFlag.Error()}, - {"will qos", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 3<<3 | 1<<2}, 8, "if Will flag is set to 1, Will QoS can be 0, 1 or 2"}, - {"no user but password", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagPasswordFlag}, 8, errMQTTPasswordFlagAndNoUser.Error()}, - {"missing keep alive", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0}, 8, "keep alive"}, - {"missing client ID", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1}, 10, "client ID"}, - {"empty client ID", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1, 0, 0}, 12, errMQTTCIDEmptyNeedsCleanFlag.Error()}, - {"invalid utf8 client ID", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1, 0, 1, 241}, 13, "invalid utf8 for client ID"}, - {"missing will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0}, 12, "Will topic"}, - {"empty will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 0}, 14, errMQTTEmptyWillTopic.Error()}, - {"invalid utf8 will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 241}, 15, "invalid utf8 for Will topic"}, - {"invalid wildcard will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, '#'}, 15, "wildcards not allowed"}, - {"error on will message", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 'a', 0, 3}, 17, "Will message"}, - {"error on username", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0}, 12, "user name"}, - {"empty username", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 0}, 14, errMQTTEmptyUsername.Error()}, - {"invalid utf8 username", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 241}, 15, "invalid utf8 for user name"}, - {"error on password", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagPasswordFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 'a'}, 15, "password"}, + {"packet in buffer error", []byte{0}, io.ErrUnexpectedEOF.Error()}, + {"bad proto name", []byte{0, 4, 'B', 'A', 'D'}, "protocol name"}, + {"invalid proto name", []byte{0, 3, 'B', 'A', 'D'}, "expected connect packet with protocol name"}, + {"old proto not supported", []byte{0, 6, 'M', 'Q', 'I', 's', 'd', 'p'}, "older protocol"}, + {"error on protocol level", []byte{0, 4, 'M', 'Q', 'T', 'T'}, "protocol level"}, + {"unacceptable protocol version", []byte{0, 4, 'M', 'Q', 'T', 'T', 10}, "unacceptable protocol version"}, + {"error on flags", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel}, "flags"}, + {"reserved flag", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 1}, errMQTTConnFlagReserved.Error()}, + {"will qos without will flag", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 1 << 3}, "if Will flag is set to 0, Will QoS must be 0 too"}, + {"will retain without will flag", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 1 << 5}, errMQTTWillAndRetainFlag.Error()}, + {"will qos", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 3<<3 | 1<<2}, "if Will flag is set to 1, Will QoS can be 0, 1 or 2"}, + {"no user but password", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagPasswordFlag}, errMQTTPasswordFlagAndNoUser.Error()}, + {"missing keep alive", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0}, "keep alive"}, + {"missing client ID", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1}, "client ID"}, + {"empty client ID", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1, 0, 0}, errMQTTCIDEmptyNeedsCleanFlag.Error()}, + {"invalid utf8 client ID", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1, 0, 1, 241}, "invalid utf8 for client ID"}, + {"missing will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0}, "Will topic"}, + {"empty will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 0}, errMQTTEmptyWillTopic.Error()}, + {"invalid utf8 will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 241}, "invalid utf8 for Will topic"}, + {"invalid wildcard will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, '#'}, "wildcards not allowed"}, + {"error on will message", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 'a', 0, 3}, "Will message"}, + {"error on username", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0}, "user name"}, + {"empty username", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 0}, errMQTTEmptyUsername.Error()}, + {"invalid utf8 username", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 241}, "invalid utf8 for user name"}, + {"error on password", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagPasswordFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 'a'}, "password"}, } { t.Run(test.name, func(t *testing.T) { r := &mqttReader{} r.reset(test.proto) mqtt := &mqtt{r: r} c := &client{mqtt: mqtt} - if _, _, err := c.mqttParseConnect(r, test.pl, false); err == nil || !strings.Contains(err.Error(), test.err) { + if _, _, err := c.mqttParseConnect(r, false); err == nil || !strings.Contains(err.Error(), test.err) { t.Fatalf("Expected error %q, got %v", test.err, err) } }) @@ -2226,17 +2225,16 @@ func TestMQTTParsePIMsg(t *testing.T) { for _, test := range []struct { name string proto []byte - pl int err string }{ - {"packet in buffer error", nil, 10, io.ErrUnexpectedEOF.Error()}, - {"error reading packet identifier", []byte{0}, 1, "packet identifier"}, - {"invalid packet identifier", []byte{0, 0}, 2, errMQTTPacketIdentifierIsZero.Error()}, + {"packet in buffer error", nil, io.ErrUnexpectedEOF.Error()}, + {"error reading packet identifier", []byte{0}, "packet identifier"}, + {"invalid packet identifier", []byte{0, 0}, errMQTTPacketIdentifierIsZero.Error()}, } { t.Run(test.name, func(t *testing.T) { r := &mqttReader{} r.reset(test.proto) - if _, err := mqttParsePIPacket(r, test.pl); err == nil || !strings.Contains(err.Error(), test.err) { + if _, err := mqttParsePIPacket(r); err == nil || !strings.Contains(err.Error(), test.err) { t.Fatalf("Expected error %q, got %v", test.err, err) } }) @@ -3763,7 +3761,7 @@ type remoteConnSameClientIDLogger struct { warn chan string } -func (l *remoteConnSameClientIDLogger) Warnf(format string, args ...interface{}) { +func (l *remoteConnSameClientIDLogger) Warnf(format string, args ...any) { msg := fmt.Sprintf(format, args...) if strings.Contains(msg, "remote connection has started with the same client ID") { l.warn <- msg @@ -6408,7 +6406,7 @@ func TestMQTTConnectAndDisconnectEvent(t *testing.T) { // Test system events now for _, test := range []struct { - opt interface{} + opt any cid string }{ {&ConnzOptions{MQTTClient: "conn1"}, "conn1"}, @@ -6796,7 +6794,7 @@ type unableToDeleteConsLogger struct { errCh chan string } -func (l *unableToDeleteConsLogger) Errorf(format string, args ...interface{}) { +func (l *unableToDeleteConsLogger) Errorf(format string, args ...any) { msg := fmt.Sprintf(format, args...) if strings.Contains(msg, "unable to delete consumer") { l.errCh <- msg diff --git a/server/msgtrace.go b/server/msgtrace.go index d5382129470..b7e229bab8f 100644 --- a/server/msgtrace.go +++ b/server/msgtrace.go @@ -690,7 +690,7 @@ func disableTraceHeaders(c *client, msg []byte) []int { // Changes back the character at the given position `pos` in the `msg` // byte slice to the first character of the MsgTraceSendTo header. -func enableTraceHeaders(c *client, msg []byte, positions []int) { +func enableTraceHeaders(msg []byte, positions []int) { firstChar := [2]byte{MsgTraceDest[0], traceParentHdr[0]} for i, pos := range positions { if pos == -1 { diff --git a/server/msgtrace_test.go b/server/msgtrace_test.go index a5dc0beab63..9a935801cd5 100644 --- a/server/msgtrace_test.go +++ b/server/msgtrace_test.go @@ -11,6 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build !skip_msgtrace_tests +// +build !skip_msgtrace_tests + package server import ( diff --git a/server/norace_test.go b/server/norace_test.go index bf3cc35a0ca..800ccb27606 100644 --- a/server/norace_test.go +++ b/server/norace_test.go @@ -832,7 +832,7 @@ func TestNoRaceFetchAccountDoesNotRegisterAccountTwice(t *testing.T) { checkTmpAccounts := func(t *testing.T, s *Server) { t.Helper() empty := true - s.tmpAccounts.Range(func(_, _ interface{}) bool { + s.tmpAccounts.Range(func(_, _ any) bool { empty = false return false }) @@ -1676,7 +1676,7 @@ func TestNoRaceJetStreamSuperClusterMixedModeMirrors(t *testing.T) { // Connect our client to a non JS server c := sc.randomCluster() var s *Server - for s == nil { + for { if as := c.randomServer(); !as.JetStreamEnabled() { s = as break @@ -1685,23 +1685,37 @@ func TestNoRaceJetStreamSuperClusterMixedModeMirrors(t *testing.T) { nc, js := jsClientConnect(t, s) defer nc.Close() + numStreams := 10 toSend := 1000 + errCh := make(chan error, numStreams) + wg := sync.WaitGroup{} + wg.Add(numStreams) // Create 10 origin streams for i := 0; i < 10; i++ { - name := fmt.Sprintf("S%d", i+1) - if _, err := js.AddStream(&nats.StreamConfig{Name: name}); err != nil { - t.Fatalf("Unexpected error: %v", err) - } - c.waitOnStreamLeader(globalAccountName, name) - // Load them up with a bunch of messages. - for n := 0; n < toSend; n++ { - m := nats.NewMsg(name) - m.Header.Set("stream", name) - m.Header.Set("idx", strconv.FormatInt(int64(n+1), 10)) - if err := nc.PublishMsg(m); err != nil { - t.Fatalf("Unexpected publish error: %v", err) + go func(idx int) { + defer wg.Done() + name := fmt.Sprintf("S%d", idx+1) + if _, err := js.AddStream(&nats.StreamConfig{Name: name}); err != nil { + errCh <- fmt.Errorf("unexpected error: %v", err) + return } - } + c.waitOnStreamLeader(globalAccountName, name) + // Load them up with a bunch of messages. + for n := 0; n < toSend; n++ { + m := nats.NewMsg(name) + m.Header.Set("stream", name) + m.Header.Set("idx", strconv.FormatInt(int64(n+1), 10)) + if err := nc.PublishMsg(m); err != nil { + errCh <- fmt.Errorf("unexpected publish error: %v", err) + } + } + }(i) + } + wg.Wait() + select { + case err := <-errCh: + t.Fatal(err) + default: } for i := 0; i < 3; i++ { @@ -1979,11 +1993,10 @@ func TestNoRaceJetStreamSuperClusterMixedModeSources(t *testing.T) { return conf }, nil) defer sc.shutdown() - // Connect our client to a non JS server c := sc.randomCluster() var s *Server - for s == nil { + for { if as := c.randomServer(); !as.JetStreamEnabled() { s = as break @@ -1992,25 +2005,45 @@ func TestNoRaceJetStreamSuperClusterMixedModeSources(t *testing.T) { nc, js := jsClientConnect(t, s) defer nc.Close() + numStreams := 100 toSend := 1000 var sources []*nats.StreamSource + errCh := make(chan error, numStreams) + srcCh := make(chan *nats.StreamSource, numStreams) + wg := sync.WaitGroup{} + wg.Add(numStreams) // Create 100 origin streams. - for i := 1; i <= 100; i++ { - name := fmt.Sprintf("O-%d", i) - if _, err := js.AddStream(&nats.StreamConfig{Name: name}); err != nil { - t.Fatalf("Unexpected error: %v", err) - } - c.waitOnStreamLeader(globalAccountName, name) - // Load them up with a bunch of messages. - for n := 0; n < toSend; n++ { - m := nats.NewMsg(name) - m.Header.Set("stream", name) - m.Header.Set("idx", strconv.FormatInt(int64(n+1), 10)) - if err := nc.PublishMsg(m); err != nil { - t.Fatalf("Unexpected publish error: %v", err) + for i := 1; i <= numStreams; i++ { + go func(idx int) { + defer wg.Done() + + name := fmt.Sprintf("O-%d", idx) + if _, err := js.AddStream(&nats.StreamConfig{Name: name}); err != nil { + errCh <- fmt.Errorf("unexpected error: %v", err) + return } - } - sources = append(sources, &nats.StreamSource{Name: name}) + c.waitOnStreamLeader(globalAccountName, name) + // Load them up with a bunch of messages. + for n := 0; n < toSend; n++ { + m := nats.NewMsg(name) + m.Header.Set("stream", name) + m.Header.Set("idx", strconv.FormatInt(int64(n+1), 10)) + if err := nc.PublishMsg(m); err != nil { + errCh <- fmt.Errorf("unexpected publish error: %v", err) + return + } + } + srcCh <- &nats.StreamSource{Name: name} + }(i) + } + wg.Wait() + select { + case err := <-errCh: + t.Fatal(err) + default: + } + for i := 0; i < numStreams; i++ { + sources = append(sources, <-srcCh) } for i := 0; i < 3; i++ { @@ -2024,8 +2057,8 @@ func TestNoRaceJetStreamSuperClusterMixedModeSources(t *testing.T) { if err != nil { t.Fatalf("Could not retrieve stream info") } - if si.State.Msgs != uint64(100*toSend) { - return fmt.Errorf("Expected %d msgs, got state: %+v", toSend*100, si.State) + if si.State.Msgs != uint64(numStreams*toSend) { + return fmt.Errorf("Expected %d msgs, got state: %+v", numStreams*toSend, si.State) } return nil }) @@ -8985,7 +9018,7 @@ func TestNoRaceJetStreamClusterKVWithServerKill(t *testing.T) { work := func(ctx context.Context, wg *sync.WaitGroup, id int) { defer wg.Done() - nc, js := jsClientConnect(t, c.servers[id]) + nc, js := jsClientConnectEx(t, c.servers[id], []nats.JSOpt{nats.Context(ctx)}) defer nc.Close() kv, err := js.KeyValue("TEST") @@ -9032,14 +9065,14 @@ func TestNoRaceJetStreamClusterKVWithServerKill(t *testing.T) { time.Sleep(time.Second) // Simulate server stop and restart. - for i := 0; i < 10; i++ { + for i := 0; i < 7; i++ { s := c.randomServer() s.Shutdown() c.waitOnLeader() c.waitOnStreamLeader(globalAccountName, "KV_TEST") // Wait for a bit and then start the server again. - time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond) + time.Sleep(time.Duration(rand.Intn(1250)) * time.Millisecond) s = c.restartServer(s) c.waitOnServerCurrent(s) c.waitOnLeader() @@ -9245,7 +9278,6 @@ func TestNoRaceJetStreamMirrorAndSourceConsumerFailBackoff(t *testing.T) { c := createJetStreamClusterExplicit(t, "R3S", 3) defer c.shutdown() - // Setup the KV bucket and use for making assertions. nc, js := jsClientConnect(t, c.randomServer()) defer nc.Close() @@ -9268,12 +9300,22 @@ func TestNoRaceJetStreamMirrorAndSourceConsumerFailBackoff(t *testing.T) { require_NoError(t, err) ml = c.streamLeader(globalAccountName, "MIRROR") } + // Create a source. + srcl := sl + for srcl == sl { + js.DeleteStream("SOURCE") + _, err = js.AddStream(&nats.StreamConfig{ + Name: "SOURCE", + Sources: []*nats.StreamSource{{Name: "TEST"}}, + }) + require_NoError(t, err) + srcl = c.streamLeader(globalAccountName, "MIRROR") + } // Create sub to watch for the consumer create requests. nc, _ = jsClientConnect(t, ml) defer nc.Close() - sub, err := nc.SubscribeSync("$JS.API.CONSUMER.CREATE.>") - require_NoError(t, err) + sub := natsSubSync(t, nc, "$JS.API.CONSUMER.CREATE.>") // Kill the server where the source is.. sldr := c.streamLeader(globalAccountName, "TEST") @@ -9281,32 +9323,30 @@ func TestNoRaceJetStreamMirrorAndSourceConsumerFailBackoff(t *testing.T) { // Wait for just greater than 10s. We should only see 1 request during this time. time.Sleep(11 * time.Second) + // There should have been 2 requests, one for mirror, one for source n, _, _ := sub.Pending() - require_Equal(t, n, 1) + require_Equal(t, n, 2) + var mreq, sreq int + for i := 0; i < 2; i++ { + msg := natsNexMsg(t, sub, time.Second) + if bytes.Contains(msg.Data, []byte("$JS.M.")) { + mreq++ + } else if bytes.Contains(msg.Data, []byte("$JS.S.")) { + sreq++ + } + } + if mreq != 1 || sreq != 1 { + t.Fatalf("Consumer create captures invalid: mreq=%v sreq=%v", mreq, sreq) + } // Now make sure that the fails is set properly. - mset, err := ml.GlobalAccount().lookupStream("MIRROR") + mset, err := c.streamLeader(globalAccountName, "MIRROR").GlobalAccount().lookupStream("MIRROR") require_NoError(t, err) mset.mu.RLock() fails := mset.mirror.fails mset.mu.RUnlock() require_Equal(t, fails, 1) - js.DeleteStream("MIRROR") - // Clear sub - sub.NextMsg(time.Second) - // Make sure sources behave similarly. - _, err = js.AddStream(&nats.StreamConfig{ - Name: "SOURCE", - Sources: []*nats.StreamSource{{Name: "TEST"}}, - }) - require_NoError(t, err) - - // Wait for just greater than 10s. We should only see 1 request during this time. - time.Sleep(11 * time.Second) - n, _, _ = sub.Pending() - require_Equal(t, n, 1) - mset, err = c.streamLeader(globalAccountName, "SOURCE").GlobalAccount().lookupStream("SOURCE") require_NoError(t, err) mset.mu.RLock() @@ -9747,8 +9787,15 @@ func TestNoRaceJetStreamWQSkippedMsgsOnScaleUp(t *testing.T) { pdone := make(chan bool) cdone := make(chan bool) + // We will have 51 consumer apps and a producer app. Make sure to wait for + // all go routines to end at the end of the test. + wg := sync.WaitGroup{} + wg.Add(52) + // Publish routine go func() { + defer wg.Done() + publishSubjects := []string{ "CORE_ENT_DR_OTP_22.P.H.TC.10011.1010.918886682066", "CORE_ENT_DR_OTP_22.P.H.TC.10011.1010.918886682067", @@ -9782,7 +9829,9 @@ func TestNoRaceJetStreamWQSkippedMsgsOnScaleUp(t *testing.T) { } }() - consumerApp := func(i int) { + consumerApp := func() { + defer wg.Done() + nc, js := jsClientConnect(t, c.randomServer()) defer nc.Close() @@ -9821,22 +9870,22 @@ func TestNoRaceJetStreamWQSkippedMsgsOnScaleUp(t *testing.T) { } // Now consumer side single. - go consumerApp(0) + go consumerApp() - // Wait for 5s - time.Sleep(5 * time.Second) + // Wait for 2s + time.Sleep(2 * time.Second) // Now spin up 50 more. for i := 1; i <= 50; i++ { if i%5 == 0 { time.Sleep(200 * time.Millisecond) } - go consumerApp(i) + go consumerApp() } - timeout := time.Now().Add(1 * time.Minute) + timeout := time.Now().Add(8 * time.Second) for time.Now().Before(timeout) { - time.Sleep(5 * time.Second) + time.Sleep(750 * time.Millisecond) if s := c.consumerLeader(globalAccountName, "TEST", "dlc"); s != nil { s.JetStreamStepdownConsumer(globalAccountName, "TEST", "dlc") } @@ -9844,9 +9893,12 @@ func TestNoRaceJetStreamWQSkippedMsgsOnScaleUp(t *testing.T) { // Close publishers and defer closing consumers. close(pdone) - defer close(cdone) + defer func() { + close(cdone) + wg.Wait() + }() - checkFor(t, 30*time.Second, time.Second, func() error { + checkFor(t, 30*time.Second, 50*time.Millisecond, func() error { si, err := js.StreamInfo("TEST") require_NoError(t, err) if si.State.NumDeleted > 0 || si.State.Msgs > 0 { diff --git a/server/ocsp.go b/server/ocsp.go index 50021cf75f6..0f8efeb51ae 100644 --- a/server/ocsp.go +++ b/server/ocsp.go @@ -450,7 +450,7 @@ func (srv *Server) NewOCSPMonitor(config *tlsConfigKind) (*tls.Config, *OCSPMoni // Get the certificate status from the memory, then remote OCSP responder. if _, resp, err := mon.getStatus(); err != nil { return nil, nil, fmt.Errorf("bad OCSP status update for certificate at '%s': %s", certFile, err) - } else if err == nil && resp != nil && resp.Status != ocsp.Good && shutdownOnRevoke { + } else if resp != nil && resp.Status != ocsp.Good && shutdownOnRevoke { return nil, nil, fmt.Errorf("found existing OCSP status for certificate at '%s': %s", certFile, ocspStatusString(resp.Status)) } diff --git a/server/ocsp_peer.go b/server/ocsp_peer.go index 0e424a4a9cd..44b822f560f 100644 --- a/server/ocsp_peer.go +++ b/server/ocsp_peer.go @@ -26,11 +26,11 @@ import ( "github.com/nats-io/nats-server/v2/server/certidp" ) -func parseOCSPPeer(v interface{}) (pcfg *certidp.OCSPPeerConfig, retError error) { +func parseOCSPPeer(v any) (pcfg *certidp.OCSPPeerConfig, retError error) { var lt token defer convertPanicToError(<, &retError) tk, v := unwrapValue(v, <) - cm, ok := v.(map[string]interface{}) + cm, ok := v.(map[string]any) if !ok { return nil, &configErr{tk, fmt.Sprintf(certidp.ErrIllegalPeerOptsConfig, v)} } diff --git a/server/ocsp_responsecache.go b/server/ocsp_responsecache.go index b64c7fad44f..455fdd3a270 100644 --- a/server/ocsp_responsecache.go +++ b/server/ocsp_responsecache.go @@ -571,11 +571,11 @@ func (s *Server) stopOCSPResponseCache() { s.ocsprc.Stop(s) } -func parseOCSPResponseCache(v interface{}) (pcfg *OCSPResponseCacheConfig, retError error) { +func parseOCSPResponseCache(v any) (pcfg *OCSPResponseCacheConfig, retError error) { var lt token defer convertPanicToError(<, &retError) tk, v := unwrapValue(v, <) - cm, ok := v.(map[string]interface{}) + cm, ok := v.(map[string]any) if !ok { return nil, &configErr{tk, fmt.Sprintf(certidp.ErrIllegalCacheOptsConfig, v)} } diff --git a/server/opts.go b/server/opts.go index 2ca6f846610..5f157b77ed8 100644 --- a/server/opts.go +++ b/server/opts.go @@ -760,7 +760,7 @@ func ProcessConfigFile(configFile string) (*Options, error) { // token is an item parsed from the configuration. type token interface { - Value() interface{} + Value() any Line() int IsUsedVariable() bool SourceFile() string @@ -771,7 +771,7 @@ type token interface { // to be able to report the line number in case of an incorrect // configuration. // also stores the token in lastToken for use in convertPanicToError -func unwrapValue(v interface{}, lastToken *token) (token, interface{}) { +func unwrapValue(v any, lastToken *token) (token, any) { switch tk := v.(type) { case token: if lastToken != nil { @@ -813,10 +813,10 @@ func convertPanicToError(lastToken *token, e *error) { // configureSystemAccount configures a system account // if present in the configuration. -func configureSystemAccount(o *Options, m map[string]interface{}) (retErr error) { +func configureSystemAccount(o *Options, m map[string]any) (retErr error) { var lt token defer convertPanicToError(<, &retErr) - configure := func(v interface{}) error { + configure := func(v any) error { tk, v := unwrapValue(v, <) sa, ok := v.(string) if !ok { @@ -885,7 +885,7 @@ func (o *Options) ProcessConfigFile(configFile string) error { return nil } -func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error, warnings *[]error) { +func (o *Options) processConfigFileLine(k string, v any, errors *[]error, warnings *[]error) { var lt token defer convertPanicToErrorList(<, errors) @@ -909,25 +909,25 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error o.Host = v.(string) case "debug": o.Debug = v.(bool) - trackExplicitVal(o, &o.inConfig, "Debug", o.Debug) + trackExplicitVal(&o.inConfig, "Debug", o.Debug) case "trace": o.Trace = v.(bool) - trackExplicitVal(o, &o.inConfig, "Trace", o.Trace) + trackExplicitVal(&o.inConfig, "Trace", o.Trace) case "trace_verbose": o.TraceVerbose = v.(bool) o.Trace = v.(bool) - trackExplicitVal(o, &o.inConfig, "TraceVerbose", o.TraceVerbose) - trackExplicitVal(o, &o.inConfig, "Trace", o.Trace) + trackExplicitVal(&o.inConfig, "TraceVerbose", o.TraceVerbose) + trackExplicitVal(&o.inConfig, "Trace", o.Trace) case "logtime": o.Logtime = v.(bool) - trackExplicitVal(o, &o.inConfig, "Logtime", o.Logtime) + trackExplicitVal(&o.inConfig, "Logtime", o.Logtime) case "logtime_utc": o.LogtimeUTC = v.(bool) - trackExplicitVal(o, &o.inConfig, "LogtimeUTC", o.LogtimeUTC) + trackExplicitVal(&o.inConfig, "LogtimeUTC", o.LogtimeUTC) case "mappings", "maps": gacc := NewAccount(globalAccountName) o.Accounts = append(o.Accounts, gacc) - err := parseAccountMappings(tk, gacc, errors, warnings) + err := parseAccountMappings(tk, gacc, errors) if err != nil { *errors = append(*errors, err) return @@ -941,7 +941,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error return } case "authorization": - auth, err := parseAuthorization(tk, o, errors, warnings) + auth, err := parseAuthorization(tk, errors) if err != nil { *errors = append(*errors, err) return @@ -1066,7 +1066,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error o.LogMaxFiles = v.(int64) case "syslog": o.Syslog = v.(bool) - trackExplicitVal(o, &o.inConfig, "Syslog", o.Syslog) + trackExplicitVal(&o.inConfig, "Syslog", o.Syslog) case "remote_syslog": o.RemoteSyslog = v.(string) case "pidfile", "pid_file": @@ -1147,7 +1147,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error } else { o.OCSPConfig = &OCSPConfig{Mode: OCSPModeNever} } - case map[string]interface{}: + case map[string]any: ocsp := &OCSPConfig{Mode: OCSPModeAuto} for kk, kv := range vv { @@ -1274,7 +1274,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error o.AccountResolver = ur } } - case map[string]interface{}: + case map[string]any: del := false hdel := false hdel_set := false @@ -1403,7 +1403,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error // be used as a client connection, we need to set RootCAs. o.AccountResolverTLSConfig.RootCAs = tlsConfig.ClientCAs case "resolver_preload": - mp, ok := v.(map[string]interface{}) + mp, ok := v.(map[string]any) if !ok { err := &configErr{tk, "preload should be a map of account_public_key:account_jwt"} *errors = append(*errors, err) @@ -1435,7 +1435,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error for _, mv := range v { o.resolverPinnedAccounts[mv] = struct{}{} } - case []interface{}: + case []any: o.resolverPinnedAccounts = make(map[string]struct{}) for _, mv := range v { tk, mv = unwrapValue(mv, <) @@ -1469,7 +1469,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error o.TrustedKeys = []string{v} case []string: o.TrustedKeys = v - case []interface{}: + case []any: keys := make([]string, 0, len(v)) for _, mv := range v { tk, mv = unwrapValue(mv, <) @@ -1498,7 +1498,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error case "reconnect_error_reports": o.ReconnectErrorReports = int(v.(int64)) case "websocket", "ws": - if err := parseWebsocket(tk, o, errors, warnings); err != nil { + if err := parseWebsocket(tk, o, errors); err != nil { *errors = append(*errors, err) return } @@ -1514,7 +1514,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error o.Tags.Add(v) case []string: o.Tags.Add(v...) - case []interface{}: + case []any: for _, t := range v { if token, ok := t.(token); ok { if ts, ok := token.Value().(string); ok { @@ -1536,7 +1536,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error return } case "default_js_domain": - vv, ok := v.(map[string]interface{}) + vv, ok := v.(map[string]any) if !ok { *errors = append(*errors, &configErr{tk, fmt.Sprintf("error default_js_domain config: unsupported type %T", v)}) return @@ -1561,7 +1561,7 @@ func (o *Options) processConfigFileLine(k string, v interface{}, errors *[]error pc.Type = NONE o.OCSPCacheConfig = pc } - case map[string]interface{}: + case map[string]any: pc, err := parseOCSPResponseCache(v) if err != nil { *errors = append(*errors, err) @@ -1599,7 +1599,7 @@ func setupUsersAndNKeysDuplicateCheckMap(o *Options) map[string]struct{} { return unames } -func parseDuration(field string, tk token, v interface{}, errors *[]error, warnings *[]error) time.Duration { +func parseDuration(field string, tk token, v any, errors *[]error, warnings *[]error) time.Duration { if wd, ok := v.(string); ok { if dur, err := time.ParseDuration(wd); err != nil { err := &configErr{tk, fmt.Sprintf("error parsing %s: %v", field, err)} @@ -1623,7 +1623,7 @@ func parseDuration(field string, tk token, v interface{}, errors *[]error, warni } } -func trackExplicitVal(opts *Options, pm *map[string]bool, name string, val bool) { +func trackExplicitVal(pm *map[string]bool, name string, val bool) { m := *pm if m == nil { m = make(map[string]bool) @@ -1639,7 +1639,7 @@ type hostPort struct { } // parseListen will parse listen option which is replacing host/net and port -func parseListen(v interface{}) (*hostPort, error) { +func parseListen(v any) (*hostPort, error) { hp := &hostPort{} switch vv := v.(type) { // Only a port @@ -1662,12 +1662,12 @@ func parseListen(v interface{}) (*hostPort, error) { } // parseCluster will parse the cluster config. -func parseCluster(v interface{}, opts *Options, errors *[]error, warnings *[]error) error { +func parseCluster(v any, opts *Options, errors *[]error, warnings *[]error) error { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) - cm, ok := v.(map[string]interface{}) + cm, ok := v.(map[string]any) if !ok { return &configErr{tk, fmt.Sprintf("Expected map to define cluster, got %T", v)} } @@ -1692,7 +1692,7 @@ func parseCluster(v interface{}, opts *Options, errors *[]error, warnings *[]err case "host", "net": opts.Cluster.Host = mv.(string) case "authorization": - auth, err := parseAuthorization(tk, opts, errors, warnings) + auth, err := parseAuthorization(tk, errors) if err != nil { *errors = append(*errors, err) continue @@ -1733,7 +1733,7 @@ func parseCluster(v interface{}, opts *Options, errors *[]error, warnings *[]err } } case "routes": - ra := mv.([]interface{}) + ra := mv.([]any) routes, errs := parseURLs(ra, "route", warnings) if errs != nil { *errors = append(*errors, errs...) @@ -1756,11 +1756,11 @@ func parseCluster(v interface{}, opts *Options, errors *[]error, warnings *[]err opts.Cluster.Advertise = mv.(string) case "no_advertise": opts.Cluster.NoAdvertise = mv.(bool) - trackExplicitVal(opts, &opts.inConfig, "Cluster.NoAdvertise", opts.Cluster.NoAdvertise) + trackExplicitVal(&opts.inConfig, "Cluster.NoAdvertise", opts.Cluster.NoAdvertise) case "connect_retries": opts.Cluster.ConnectRetries = int(mv.(int64)) case "permissions": - perms, err := parseUserPermissions(mv, errors, warnings) + perms, err := parseUserPermissions(mv, errors) if err != nil { *errors = append(*errors, err) continue @@ -1776,7 +1776,7 @@ func parseCluster(v interface{}, opts *Options, errors *[]error, warnings *[]err case "pool_size": opts.Cluster.PoolSize = int(mv.(int64)) case "accounts": - opts.Cluster.PinnedAccounts, _ = parseStringArray("accounts", tk, <, mv, errors, warnings) + opts.Cluster.PinnedAccounts, _ = parseStringArray("accounts", tk, <, mv, errors) case "compression": if err := parseCompression(&opts.Cluster.Compression, CompressionS2Fast, tk, mk, mv); err != nil { *errors = append(*errors, err) @@ -1808,7 +1808,7 @@ func parseCluster(v interface{}, opts *Options, errors *[]error, warnings *[]err // The parameter `chosenModeForOn` indicates which compression mode to use // when the user selects "on" (or enabled, true, etc..). This is because // we may have different defaults depending on where the compression is used. -func parseCompression(c *CompressionOpts, chosenModeForOn string, tk token, mk string, mv interface{}) (retErr error) { +func parseCompression(c *CompressionOpts, chosenModeForOn string, tk token, mk string, mv any) (retErr error) { var lt token defer convertPanicToError(<, &retErr) @@ -1822,14 +1822,14 @@ func parseCompression(c *CompressionOpts, chosenModeForOn string, tk token, mk s } else { c.Mode = CompressionOff } - case map[string]interface{}: + case map[string]any: for mk, mv := range mv { tk, mv = unwrapValue(mv, <) switch strings.ToLower(mk) { case "mode": c.Mode = mv.(string) case "rtt_thresholds", "thresholds", "rtts", "rtt": - for _, iv := range mv.([]interface{}) { + for _, iv := range mv.([]any) { _, mv := unwrapValue(iv, <) dur, err := time.ParseDuration(mv.(string)) if err != nil { @@ -1849,7 +1849,7 @@ func parseCompression(c *CompressionOpts, chosenModeForOn string, tk token, mk s return nil } -func parseURLs(a []interface{}, typ string, warnings *[]error) (urls []*url.URL, errors []error) { +func parseURLs(a []any, typ string, warnings *[]error) (urls []*url.URL, errors []error) { urls = make([]*url.URL, 0, len(a)) var lt token defer convertPanicToErrorList(<, &errors) @@ -1893,12 +1893,12 @@ func parseURL(u string, typ string) (*url.URL, error) { return url, nil } -func parseGateway(v interface{}, o *Options, errors *[]error, warnings *[]error) error { +func parseGateway(v any, o *Options, errors *[]error, warnings *[]error) error { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) - gm, ok := v.(map[string]interface{}) + gm, ok := v.(map[string]any) if !ok { return &configErr{tk, fmt.Sprintf("Expected gateway to be a map, got %T", v)} } @@ -1922,7 +1922,7 @@ func parseGateway(v interface{}, o *Options, errors *[]error, warnings *[]error) case "host", "net": o.Gateway.Host = mv.(string) case "authorization": - auth, err := parseAuthorization(tk, o, errors, warnings) + auth, err := parseAuthorization(tk, errors) if err != nil { *errors = append(*errors, err) continue @@ -1990,7 +1990,7 @@ var defaultJSAccountTiers = map[string]JetStreamAccountLimits{_EMPTY_: dynamicJS // Parses jetstream account limits for an account. Simple setup with boolen is allowed, and we will // use dynamic account limits. -func parseJetStreamForAccount(v interface{}, acc *Account, errors *[]error, warnings *[]error) error { +func parseJetStreamForAccount(v any, acc *Account, errors *[]error) error { var lt token tk, v := unwrapValue(v, <) @@ -2010,7 +2010,7 @@ func parseJetStreamForAccount(v interface{}, acc *Account, errors *[]error, warn default: return &configErr{tk, fmt.Sprintf("Expected 'enabled' or 'disabled' for string value, got '%s'", vv)} } - case map[string]interface{}: + case map[string]any: jsLimits := JetStreamAccountLimits{-1, -1, -1, -1, -1, -1, -1, false} for mk, mv := range vv { tk, mv = unwrapValue(mv, <) @@ -2084,7 +2084,7 @@ func parseJetStreamForAccount(v interface{}, acc *Account, errors *[]error, warn } // takes in a storage size as either an int or a string and returns an int64 value based on the input. -func getStorageSize(v interface{}) (int64, error) { +func getStorageSize(v any) (int64, error) { _, ok := v.(int64) if ok { return v.(int64), nil @@ -2118,13 +2118,13 @@ func getStorageSize(v interface{}) (int64, error) { } // Parse enablement of jetstream for a server. -func parseJetStreamLimits(v interface{}, opts *Options, errors *[]error, warnings *[]error) error { +func parseJetStreamLimits(v any, opts *Options, errors *[]error) error { var lt token tk, v := unwrapValue(v, <) lim := JSLimitOpts{} - vv, ok := v.(map[string]interface{}) + vv, ok := v.(map[string]any) if !ok { return &configErr{tk, fmt.Sprintf("Expected a map to define JetStreamLimits, got %T", v)} } @@ -2161,7 +2161,7 @@ func parseJetStreamLimits(v interface{}, opts *Options, errors *[]error, warning } // Parse enablement of jetstream for a server. -func parseJetStream(v interface{}, opts *Options, errors *[]error, warnings *[]error) error { +func parseJetStream(v any, opts *Options, errors *[]error, warnings *[]error) error { var lt token tk, v := unwrapValue(v, <) @@ -2179,7 +2179,7 @@ func parseJetStream(v interface{}, opts *Options, errors *[]error, warnings *[]e default: return &configErr{tk, fmt.Sprintf("Expected 'enabled' or 'disabled' for string value, got '%s'", vv)} } - case map[string]interface{}: + case map[string]any: doEnable := true for mk, mv := range vv { tk, mv = unwrapValue(mv, <) @@ -2232,7 +2232,7 @@ func parseJetStream(v interface{}, opts *Options, errors *[]error, warnings *[]e case "extension_hint": opts.JetStreamExtHint = mv.(string) case "limits": - if err := parseJetStreamLimits(tk, opts, errors, warnings); err != nil { + if err := parseJetStreamLimits(tk, opts, errors); err != nil { return err } case "unique_tag": @@ -2265,12 +2265,12 @@ func parseJetStream(v interface{}, opts *Options, errors *[]error, warnings *[]e } // parseLeafNodes will parse the leaf node config. -func parseLeafNodes(v interface{}, opts *Options, errors *[]error, warnings *[]error) error { +func parseLeafNodes(v any, opts *Options, errors *[]error, warnings *[]error) error { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) - cm, ok := v.(map[string]interface{}) + cm, ok := v.(map[string]any) if !ok { return &configErr{tk, fmt.Sprintf("Expected map to define a leafnode, got %T", v)} } @@ -2293,7 +2293,7 @@ func parseLeafNodes(v interface{}, opts *Options, errors *[]error, warnings *[]e case "host", "net": opts.LeafNode.Host = mv.(string) case "authorization": - auth, err := parseLeafAuthorization(tk, errors, warnings) + auth, err := parseLeafAuthorization(tk, errors) if err != nil { *errors = append(*errors, err) continue @@ -2339,7 +2339,7 @@ func parseLeafNodes(v interface{}, opts *Options, errors *[]error, warnings *[]e opts.LeafNode.Advertise = mv.(string) case "no_advertise": opts.LeafNode.NoAdvertise = mv.(bool) - trackExplicitVal(opts, &opts.inConfig, "LeafNode.NoAdvertise", opts.LeafNode.NoAdvertise) + trackExplicitVal(&opts.inConfig, "LeafNode.NoAdvertise", opts.LeafNode.NoAdvertise) case "min_version", "minimum_version": version := mv.(string) if err := checkLeafMinVersionConfig(version); err != nil { @@ -2371,9 +2371,9 @@ func parseLeafNodes(v interface{}, opts *Options, errors *[]error, warnings *[]e // This is the authorization parser adapter for the leafnode's // authorization config. -func parseLeafAuthorization(v interface{}, errors *[]error, warnings *[]error) (*authorization, error) { +func parseLeafAuthorization(v any, errors *[]error) (*authorization, error) { var ( - am map[string]interface{} + am map[string]any tk token lt token auth = &authorization{} @@ -2381,7 +2381,7 @@ func parseLeafAuthorization(v interface{}, errors *[]error, warnings *[]error) ( defer convertPanicToErrorList(<, errors) _, v = unwrapValue(v, <) - am = v.(map[string]interface{}) + am = v.(map[string]any) for mk, mv := range am { tk, mv = unwrapValue(mv, <) switch strings.ToLower(mk) { @@ -2405,7 +2405,7 @@ func parseLeafAuthorization(v interface{}, errors *[]error, warnings *[]error) ( } auth.timeout = at case "users": - users, err := parseLeafUsers(tk, errors, warnings) + users, err := parseLeafUsers(tk, errors) if err != nil { *errors = append(*errors, err) continue @@ -2432,7 +2432,7 @@ func parseLeafAuthorization(v interface{}, errors *[]error, warnings *[]error) ( // This is a trimmed down version of parseUsers that is adapted // for the users possibly defined in the authorization{} section // of leafnodes {}. -func parseLeafUsers(mv interface{}, errors *[]error, warnings *[]error) ([]*User, error) { +func parseLeafUsers(mv any, errors *[]error) ([]*User, error) { var ( tk token lt token @@ -2442,14 +2442,14 @@ func parseLeafUsers(mv interface{}, errors *[]error, warnings *[]error) ([]*User tk, mv = unwrapValue(mv, <) // Make sure we have an array - uv, ok := mv.([]interface{}) + uv, ok := mv.([]any) if !ok { return nil, &configErr{tk, fmt.Sprintf("Expected users field to be an array, got %v", mv)} } for _, u := range uv { tk, u = unwrapValue(u, <) // Check its a map/struct - um, ok := u.(map[string]interface{}) + um, ok := u.(map[string]any) if !ok { err := &configErr{tk, fmt.Sprintf("Expected user entry to be a map/struct, got %v", u)} *errors = append(*errors, err) @@ -2489,11 +2489,11 @@ func parseLeafUsers(mv interface{}, errors *[]error, warnings *[]error) ([]*User return users, nil } -func parseRemoteLeafNodes(v interface{}, errors *[]error, warnings *[]error) ([]*RemoteLeafOpts, error) { +func parseRemoteLeafNodes(v any, errors *[]error, warnings *[]error) ([]*RemoteLeafOpts, error) { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) - ra, ok := v.([]interface{}) + ra, ok := v.([]any) if !ok { return nil, &configErr{tk, fmt.Sprintf("Expected remotes field to be an array, got %T", v)} } @@ -2501,7 +2501,7 @@ func parseRemoteLeafNodes(v interface{}, errors *[]error, warnings *[]error) ([] for _, r := range ra { tk, r = unwrapValue(r, <) // Check its a map/struct - rm, ok := r.(map[string]interface{}) + rm, ok := r.(map[string]any) if !ok { *errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected remote leafnode entry to be a map/struct, got %v", r)}) continue @@ -2514,8 +2514,8 @@ func parseRemoteLeafNodes(v interface{}, errors *[]error, warnings *[]error) ([] remote.NoRandomize = v.(bool) case "url", "urls": switch v := v.(type) { - case []interface{}, []string: - urls, errs := parseURLs(v.([]interface{}), "leafnode", warnings) + case []any, []string: + urls, errs := parseURLs(v.([]any), "leafnode", warnings) if errs != nil { *errors = append(*errors, errs...) continue @@ -2582,14 +2582,14 @@ func parseRemoteLeafNodes(v interface{}, errors *[]error, warnings *[]error) ([] case "hub": remote.Hub = v.(bool) case "deny_imports", "deny_import": - subjects, err := parsePermSubjects(tk, errors, warnings) + subjects, err := parsePermSubjects(tk, errors) if err != nil { *errors = append(*errors, err) continue } remote.DenyImports = subjects case "deny_exports", "deny_export": - subjects, err := parsePermSubjects(tk, errors, warnings) + subjects, err := parsePermSubjects(tk, errors) if err != nil { *errors = append(*errors, err) continue @@ -2644,13 +2644,13 @@ func getTLSConfig(tk token) (*tls.Config, *TLSConfigOpts, error) { return config, tc, nil } -func parseGateways(v interface{}, errors *[]error, warnings *[]error) ([]*RemoteGatewayOpts, error) { +func parseGateways(v any, errors *[]error, warnings *[]error) ([]*RemoteGatewayOpts, error) { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) // Make sure we have an array - ga, ok := v.([]interface{}) + ga, ok := v.([]any) if !ok { return nil, &configErr{tk, fmt.Sprintf("Expected gateways field to be an array, got %T", v)} } @@ -2658,7 +2658,7 @@ func parseGateways(v interface{}, errors *[]error, warnings *[]error) ([]*Remote for _, g := range ga { tk, g = unwrapValue(g, <) // Check its a map/struct - gm, ok := g.(map[string]interface{}) + gm, ok := g.(map[string]any) if !ok { *errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected gateway entry to be a map/struct, got %v", g)}) continue @@ -2686,7 +2686,7 @@ func parseGateways(v interface{}, errors *[]error, warnings *[]error) ([]*Remote } gateway.URLs = append(gateway.URLs, url) case "urls": - urls, errs := parseURLs(v.([]interface{}), "gateway", warnings) + urls, errs := parseURLs(v.([]any), "gateway", warnings) if errs != nil { *errors = append(*errors, errs...) continue @@ -2759,9 +2759,9 @@ func isReservedAccount(name string) bool { return name == globalAccountName } -func parseAccountMapDest(v interface{}, tk token, errors *[]error, warnings *[]error) (*MapDest, *configErr) { +func parseAccountMapDest(v any, tk token, errors *[]error) (*MapDest, *configErr) { // These should be maps. - mv, ok := v.(map[string]interface{}) + mv, ok := v.(map[string]any) if !ok { err := &configErr{tk, "Expected an entry for the mapping destination"} *errors = append(*errors, err) @@ -2828,12 +2828,12 @@ func parseAccountMapDest(v interface{}, tk token, errors *[]error, warnings *[]e } // parseAccountMappings is called to parse account mappings. -func parseAccountMappings(v interface{}, acc *Account, errors *[]error, warnings *[]error) error { +func parseAccountMappings(v any, acc *Account, errors *[]error) error { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) - am := v.(map[string]interface{}) + am := v.(map[string]any) for subj, mv := range am { if !IsValidSubject(subj) { err := &configErr{tk, fmt.Sprintf("Subject %q is not a valid subject", subj)} @@ -2849,11 +2849,11 @@ func parseAccountMappings(v interface{}, acc *Account, errors *[]error, warnings *errors = append(*errors, err) continue } - case []interface{}: + case []any: var mappings []*MapDest - for _, mv := range v.([]interface{}) { + for _, mv := range v.([]any) { tk, amv := unwrapValue(mv, <) - mdest, err := parseAccountMapDest(amv, tk, errors, warnings) + mdest, err := parseAccountMapDest(amv, tk, errors) if err != nil { continue } @@ -2866,9 +2866,9 @@ func parseAccountMappings(v interface{}, acc *Account, errors *[]error, warnings *errors = append(*errors, err) continue } - case interface{}: + case any: tk, amv := unwrapValue(mv, <) - mdest, err := parseAccountMapDest(amv, tk, errors, warnings) + mdest, err := parseAccountMapDest(amv, tk, errors) if err != nil { continue } @@ -2889,12 +2889,12 @@ func parseAccountMappings(v interface{}, acc *Account, errors *[]error, warnings } // parseAccountLimits is called to parse account limits in a server config. -func parseAccountLimits(mv interface{}, acc *Account, errors *[]error, warnings *[]error) error { +func parseAccountLimits(mv any, acc *Account, errors *[]error) error { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(mv, <) - am, ok := v.(map[string]interface{}) + am, ok := v.(map[string]any) if !ok { return &configErr{tk, fmt.Sprintf("Expected account limits to be a map/struct, got %+v", v)} } @@ -2985,7 +2985,7 @@ func parseAccountMsgTrace(mv any, topKey string, acc *Account) error { } // parseAccounts will parse the different accounts syntax. -func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]error) error { +func parseAccounts(v any, opts *Options, errors *[]error, warnings *[]error) error { var ( importStreams []*importStream importServices []*importService @@ -2998,9 +2998,9 @@ func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]er tk, v := unwrapValue(v, <) switch vv := v.(type) { // Simple array of account names. - case []interface{}, []string: - m := make(map[string]struct{}, len(v.([]interface{}))) - for _, n := range v.([]interface{}) { + case []any, []string: + m := make(map[string]struct{}, len(v.([]any))) + for _, n := range v.([]any) { tk, name := unwrapValue(n, <) ns := name.(string) // Check for reserved names. @@ -3018,7 +3018,7 @@ func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]er m[ns] = struct{}{} } // More common map entry - case map[string]interface{}: + case map[string]any: // Track users across accounts, must be unique across // accounts and nkeys vs users. // We also want to check for users that may have been added in @@ -3034,7 +3034,7 @@ func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]er } // These should be maps. - mv, ok := amv.(map[string]interface{}) + mv, ok := amv.(map[string]any) if !ok { err := &configErr{tk, "Expected map entries for accounts"} *errors = append(*errors, err) @@ -3065,7 +3065,7 @@ func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]er } acc.Nkey = nk case "imports": - streams, services, err := parseAccountImports(tk, acc, errors, warnings) + streams, services, err := parseAccountImports(tk, acc, errors) if err != nil { *errors = append(*errors, err) continue @@ -3073,7 +3073,7 @@ func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]er importStreams = append(importStreams, streams...) importServices = append(importServices, services...) case "exports": - streams, services, err := parseAccountExports(tk, acc, errors, warnings) + streams, services, err := parseAccountExports(tk, acc, errors) if err != nil { *errors = append(*errors, err) continue @@ -3081,7 +3081,7 @@ func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]er exportStreams = append(exportStreams, streams...) exportServices = append(exportServices, services...) case "jetstream": - err := parseJetStreamForAccount(mv, acc, errors, warnings) + err := parseJetStreamForAccount(mv, acc, errors) if err != nil { *errors = append(*errors, err) continue @@ -3089,26 +3089,26 @@ func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]er case "users": var err error usersTk = tk - nkeyUsr, users, err = parseUsers(mv, opts, errors, warnings) + nkeyUsr, users, err = parseUsers(mv, errors) if err != nil { *errors = append(*errors, err) continue } case "default_permissions": - permissions, err := parseUserPermissions(tk, errors, warnings) + permissions, err := parseUserPermissions(tk, errors) if err != nil { *errors = append(*errors, err) continue } acc.defaultPerms = permissions case "mappings", "maps": - err := parseAccountMappings(tk, acc, errors, warnings) + err := parseAccountMappings(tk, acc, errors) if err != nil { *errors = append(*errors, err) continue } case "limits": - err := parseAccountLimits(tk, acc, errors, warnings) + err := parseAccountLimits(tk, acc, errors) if err != nil { *errors = append(*errors, err) continue @@ -3310,13 +3310,13 @@ func parseAccounts(v interface{}, opts *Options, errors *[]error, warnings *[]er } // Parse the account exports -func parseAccountExports(v interface{}, acc *Account, errors, warnings *[]error) ([]*export, []*export, error) { +func parseAccountExports(v any, acc *Account, errors *[]error) ([]*export, []*export, error) { var lt token defer convertPanicToErrorList(<, errors) // This should be an array of objects/maps. tk, v := unwrapValue(v, <) - ims, ok := v.([]interface{}) + ims, ok := v.([]any) if !ok { return nil, nil, &configErr{tk, fmt.Sprintf("Exports should be an array, got %T", v)} } @@ -3326,7 +3326,7 @@ func parseAccountExports(v interface{}, acc *Account, errors, warnings *[]error) for _, v := range ims { // Should have stream or service - stream, service, err := parseExportStreamOrService(v, errors, warnings) + stream, service, err := parseExportStreamOrService(v, errors) if err != nil { *errors = append(*errors, err) continue @@ -3344,13 +3344,13 @@ func parseAccountExports(v interface{}, acc *Account, errors, warnings *[]error) } // Parse the account imports -func parseAccountImports(v interface{}, acc *Account, errors, warnings *[]error) ([]*importStream, []*importService, error) { +func parseAccountImports(v any, acc *Account, errors *[]error) ([]*importStream, []*importService, error) { var lt token defer convertPanicToErrorList(<, errors) // This should be an array of objects/maps. tk, v := unwrapValue(v, <) - ims, ok := v.([]interface{}) + ims, ok := v.([]any) if !ok { return nil, nil, &configErr{tk, fmt.Sprintf("Imports should be an array, got %T", v)} } @@ -3361,7 +3361,7 @@ func parseAccountImports(v interface{}, acc *Account, errors, warnings *[]error) for _, v := range ims { // Should have stream or service - stream, service, err := parseImportStreamOrService(v, errors, warnings) + stream, service, err := parseImportStreamOrService(v, errors) if err != nil { *errors = append(*errors, err) continue @@ -3388,7 +3388,7 @@ func parseAccountImports(v interface{}, acc *Account, errors, warnings *[]error) } // Helper to parse an embedded account description for imported services or streams. -func parseAccount(v map[string]interface{}, errors, warnings *[]error) (string, string, error) { +func parseAccount(v map[string]any, errors *[]error) (string, string, error) { var lt token defer convertPanicToErrorList(<, errors) @@ -3421,7 +3421,7 @@ func parseAccount(v map[string]interface{}, errors, warnings *[]error) (string, // {stream: "synadia.private.>", accounts: [cncf, natsio]} // {service: "pub.request"} # No accounts means public. // {service: "pub.special.request", accounts: [nats.io]} -func parseExportStreamOrService(v interface{}, errors, warnings *[]error) (*export, *export, error) { +func parseExportStreamOrService(v any, errors *[]error) (*export, *export, error) { var ( curStream *export curService *export @@ -3442,7 +3442,7 @@ func parseExportStreamOrService(v interface{}, errors, warnings *[]error) (*expo defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) - vv, ok := v.(map[string]interface{}) + vv, ok := v.(map[string]any) if !ok { return nil, nil, &configErr{tk, fmt.Sprintf("Export Items should be a map with type entry, got %T", v)} } @@ -3569,7 +3569,7 @@ func parseExportStreamOrService(v interface{}, errors, warnings *[]error) (*expo *errors = append(*errors, err) } case "accounts": - for _, iv := range mv.([]interface{}) { + for _, iv := range mv.([]any) { _, mv := unwrapValue(iv, <) accounts = append(accounts, mv.(string)) } @@ -3630,7 +3630,7 @@ func parseExportStreamOrService(v interface{}, errors, warnings *[]error) (*expo } // parseServiceLatency returns a latency config block. -func parseServiceLatency(root token, v interface{}) (l *serviceLatency, retErr error) { +func parseServiceLatency(root token, v any) (l *serviceLatency, retErr error) { var lt token defer convertPanicToError(<, &retErr) @@ -3641,7 +3641,7 @@ func parseServiceLatency(root token, v interface{}) (l *serviceLatency, retErr e }, nil } - latency, ok := v.(map[string]interface{}) + latency, ok := v.(map[string]any) if !ok { return nil, &configErr{token: root, reason: fmt.Sprintf("Expected latency entry to be a map/struct or string, got %T", v)} @@ -3711,7 +3711,7 @@ func parseServiceLatency(root token, v interface{}) (l *serviceLatency, retErr e // {stream: {account: "synadia", subject:"public.synadia"}, prefix: "imports.synadia"} // {stream: {account: "synadia", subject:"synadia.private.*"}} // {service: {account: "synadia", subject: "pub.special.request"}, to: "synadia.request"} -func parseImportStreamOrService(v interface{}, errors, warnings *[]error) (*importStream, *importService, error) { +func parseImportStreamOrService(v any, errors *[]error) (*importStream, *importService, error) { var ( curStream *importStream curService *importService @@ -3725,7 +3725,7 @@ func parseImportStreamOrService(v interface{}, errors, warnings *[]error) (*impo defer convertPanicToErrorList(<, errors) tk, mv := unwrapValue(v, <) - vv, ok := mv.(map[string]interface{}) + vv, ok := mv.(map[string]any) if !ok { return nil, nil, &configErr{tk, fmt.Sprintf("Import Items should be a map with type entry, got %T", mv)} } @@ -3738,14 +3738,14 @@ func parseImportStreamOrService(v interface{}, errors, warnings *[]error) (*impo *errors = append(*errors, err) continue } - ac, ok := mv.(map[string]interface{}) + ac, ok := mv.(map[string]any) if !ok { err := &configErr{tk, fmt.Sprintf("Stream entry should be an account map, got %T", mv)} *errors = append(*errors, err) continue } // Make sure this is a map with account and subject - accountName, subject, err := parseAccount(ac, errors, warnings) + accountName, subject, err := parseAccount(ac, errors) if err != nil { *errors = append(*errors, err) continue @@ -3776,14 +3776,14 @@ func parseImportStreamOrService(v interface{}, errors, warnings *[]error) (*impo *errors = append(*errors, err) continue } - ac, ok := mv.(map[string]interface{}) + ac, ok := mv.(map[string]any) if !ok { err := &configErr{tk, fmt.Sprintf("Service entry should be an account map, got %T", mv)} *errors = append(*errors, err) continue } // Make sure this is a map with account and subject - accountName, subject, err := parseAccount(ac, errors, warnings) + accountName, subject, err := parseAccount(ac, errors) if err != nil { *errors = append(*errors, err) continue @@ -3869,9 +3869,9 @@ func applyDefaultPermissions(users []*User, nkeys []*NkeyUser, defaultP *Permiss } // Helper function to parse Authorization configs. -func parseAuthorization(v interface{}, opts *Options, errors *[]error, warnings *[]error) (*authorization, error) { +func parseAuthorization(v any, errors *[]error) (*authorization, error) { var ( - am map[string]interface{} + am map[string]any tk token lt token auth = &authorization{} @@ -3879,7 +3879,7 @@ func parseAuthorization(v interface{}, opts *Options, errors *[]error, warnings defer convertPanicToErrorList(<, errors) _, v = unwrapValue(v, <) - am = v.(map[string]interface{}) + am = v.(map[string]any) for mk, mv := range am { tk, mv = unwrapValue(mv, <) switch strings.ToLower(mk) { @@ -3899,7 +3899,7 @@ func parseAuthorization(v interface{}, opts *Options, errors *[]error, warnings } auth.timeout = at case "users": - nkeys, users, err := parseUsers(tk, opts, errors, warnings) + nkeys, users, err := parseUsers(tk, errors) if err != nil { *errors = append(*errors, err) continue @@ -3907,14 +3907,14 @@ func parseAuthorization(v interface{}, opts *Options, errors *[]error, warnings auth.users = users auth.nkeys = nkeys case "default_permission", "default_permissions", "permissions": - permissions, err := parseUserPermissions(tk, errors, warnings) + permissions, err := parseUserPermissions(tk, errors) if err != nil { *errors = append(*errors, err) continue } auth.defaultPermissions = permissions case "auth_callout", "auth_hook": - ac, err := parseAuthCallout(tk, errors, warnings) + ac, err := parseAuthCallout(tk, errors) if err != nil { *errors = append(*errors, err) continue @@ -3939,7 +3939,7 @@ func parseAuthorization(v interface{}, opts *Options, errors *[]error, warnings } // Helper function to parse multiple users array with optional permissions. -func parseUsers(mv interface{}, opts *Options, errors *[]error, warnings *[]error) ([]*NkeyUser, []*User, error) { +func parseUsers(mv any, errors *[]error) ([]*NkeyUser, []*User, error) { var ( tk token lt token @@ -3950,7 +3950,7 @@ func parseUsers(mv interface{}, opts *Options, errors *[]error, warnings *[]erro tk, mv = unwrapValue(mv, <) // Make sure we have an array - uv, ok := mv.([]interface{}) + uv, ok := mv.([]any) if !ok { return nil, nil, &configErr{tk, fmt.Sprintf("Expected users field to be an array, got %v", mv)} } @@ -3958,7 +3958,7 @@ func parseUsers(mv interface{}, opts *Options, errors *[]error, warnings *[]erro tk, u = unwrapValue(u, <) // Check its a map/struct - um, ok := u.(map[string]interface{}) + um, ok := u.(map[string]any) if !ok { err := &configErr{tk, fmt.Sprintf("Expected user entry to be a map/struct, got %v", u)} *errors = append(*errors, err) @@ -3983,13 +3983,13 @@ func parseUsers(mv interface{}, opts *Options, errors *[]error, warnings *[]erro case "pass", "password": user.Password = v.(string) case "permission", "permissions", "authorization": - perms, err = parseUserPermissions(tk, errors, warnings) + perms, err = parseUserPermissions(tk, errors) if err != nil { *errors = append(*errors, err) continue } case "allowed_connection_types", "connection_types", "clients": - cts := parseAllowedConnectionTypes(tk, <, v, errors, warnings) + cts := parseAllowedConnectionTypes(tk, <, v, errors) nkey.AllowedConnectionTypes = cts user.AllowedConnectionTypes = cts default: @@ -4035,8 +4035,8 @@ func parseUsers(mv interface{}, opts *Options, errors *[]error, warnings *[]erro return keys, users, nil } -func parseAllowedConnectionTypes(tk token, lt *token, mv interface{}, errors *[]error, warnings *[]error) map[string]struct{} { - cts, err := parseStringArray("allowed connection types", tk, lt, mv, errors, warnings) +func parseAllowedConnectionTypes(tk token, lt *token, mv any, errors *[]error) map[string]struct{} { + cts, err := parseStringArray("allowed connection types", tk, lt, mv, errors) // If error, it has already been added to the `errors` array, simply return if err != nil { return nil @@ -4049,7 +4049,7 @@ func parseAllowedConnectionTypes(tk token, lt *token, mv interface{}, errors *[] } // Helper function to parse auth callouts. -func parseAuthCallout(mv interface{}, errors, warnings *[]error) (*AuthCallout, error) { +func parseAuthCallout(mv any, errors *[]error) (*AuthCallout, error) { var ( tk token lt token @@ -4058,7 +4058,7 @@ func parseAuthCallout(mv interface{}, errors, warnings *[]error) (*AuthCallout, defer convertPanicToErrorList(<, errors) tk, mv = unwrapValue(mv, <) - pm, ok := mv.(map[string]interface{}) + pm, ok := mv.(map[string]any) if !ok { return nil, &configErr{tk, fmt.Sprintf("Expected authorization callout to be a map/struct, got %+v", mv)} } @@ -4074,7 +4074,7 @@ func parseAuthCallout(mv interface{}, errors, warnings *[]error) (*AuthCallout, case "account", "acc": ac.Account = mv.(string) case "auth_users", "users": - aua, ok := mv.([]interface{}) + aua, ok := mv.([]any) if !ok { return nil, &configErr{tk, fmt.Sprintf("Expected auth_users field to be an array, got %T", v)} } @@ -4109,7 +4109,7 @@ func parseAuthCallout(mv interface{}, errors, warnings *[]error) (*AuthCallout, } // Helper function to parse user/account permissions -func parseUserPermissions(mv interface{}, errors, warnings *[]error) (*Permissions, error) { +func parseUserPermissions(mv any, errors *[]error) (*Permissions, error) { var ( tk token lt token @@ -4118,7 +4118,7 @@ func parseUserPermissions(mv interface{}, errors, warnings *[]error) (*Permissio defer convertPanicToErrorList(<, errors) tk, mv = unwrapValue(mv, <) - pm, ok := mv.(map[string]interface{}) + pm, ok := mv.(map[string]any) if !ok { return nil, &configErr{tk, fmt.Sprintf("Expected permissions to be a map/struct, got %+v", mv)} } @@ -4130,14 +4130,14 @@ func parseUserPermissions(mv interface{}, errors, warnings *[]error) (*Permissio // Import is Publish // Export is Subscribe case "pub", "publish", "import": - perms, err := parseVariablePermissions(mv, errors, warnings) + perms, err := parseVariablePermissions(mv, errors) if err != nil { *errors = append(*errors, err) continue } p.Publish = perms case "sub", "subscribe", "export": - perms, err := parseVariablePermissions(mv, errors, warnings) + perms, err := parseVariablePermissions(mv, errors) if err != nil { *errors = append(*errors, err) continue @@ -4155,7 +4155,7 @@ func parseUserPermissions(mv interface{}, errors, warnings *[]error) (*Permissio p.Response = rp } } else { - p.Response = parseAllowResponses(v, errors, warnings) + p.Response = parseAllowResponses(v, errors) } if p.Response != nil { if p.Publish == nil { @@ -4177,19 +4177,19 @@ func parseUserPermissions(mv interface{}, errors, warnings *[]error) (*Permissio } // Top level parser for authorization configurations. -func parseVariablePermissions(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) { +func parseVariablePermissions(v any, errors *[]error) (*SubjectPermission, error) { switch vv := v.(type) { - case map[string]interface{}: + case map[string]any: // New style with allow and/or deny properties. - return parseSubjectPermission(vv, errors, warnings) + return parseSubjectPermission(vv, errors) default: // Old style - return parseOldPermissionStyle(v, errors, warnings) + return parseOldPermissionStyle(v, errors) } } // Helper function to parse subject singletons and/or arrays -func parsePermSubjects(v interface{}, errors, warnings *[]error) ([]string, error) { +func parsePermSubjects(v any, errors *[]error) ([]string, error) { var lt token defer convertPanicToErrorList(<, errors) @@ -4201,7 +4201,7 @@ func parsePermSubjects(v interface{}, errors, warnings *[]error) ([]string, erro subjects = append(subjects, vv) case []string: subjects = vv - case []interface{}: + case []any: for _, i := range vv { tk, i := unwrapValue(i, <) @@ -4221,13 +4221,13 @@ func parsePermSubjects(v interface{}, errors, warnings *[]error) ([]string, erro } // Helper function to parse a ResponsePermission. -func parseAllowResponses(v interface{}, errors, warnings *[]error) *ResponsePermission { +func parseAllowResponses(v any, errors *[]error) *ResponsePermission { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) // Check if this is a map. - pm, ok := v.(map[string]interface{}) + pm, ok := v.(map[string]any) if !ok { err := &configErr{tk, "error parsing response permissions, expected a boolean or a map"} *errors = append(*errors, err) @@ -4279,8 +4279,8 @@ func parseAllowResponses(v interface{}, errors, warnings *[]error) *ResponsePerm } // Helper function to parse old style authorization configs. -func parseOldPermissionStyle(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) { - subjects, err := parsePermSubjects(v, errors, warnings) +func parseOldPermissionStyle(v any, errors *[]error) (*SubjectPermission, error) { + subjects, err := parsePermSubjects(v, errors) if err != nil { return nil, err } @@ -4288,11 +4288,11 @@ func parseOldPermissionStyle(v interface{}, errors, warnings *[]error) (*Subject } // Helper function to parse new style authorization into a SubjectPermission with Allow and Deny. -func parseSubjectPermission(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) { +func parseSubjectPermission(v any, errors *[]error) (*SubjectPermission, error) { var lt token defer convertPanicToErrorList(<, errors) - m := v.(map[string]interface{}) + m := v.(map[string]any) if len(m) == 0 { return nil, nil } @@ -4301,14 +4301,14 @@ func parseSubjectPermission(v interface{}, errors, warnings *[]error) (*SubjectP tk, _ := unwrapValue(v, <) switch strings.ToLower(k) { case "allow": - subjects, err := parsePermSubjects(tk, errors, warnings) + subjects, err := parsePermSubjects(tk, errors) if err != nil { *errors = append(*errors, err) continue } p.Allow = subjects case "deny": - subjects, err := parsePermSubjects(tk, errors, warnings) + subjects, err := parsePermSubjects(tk, errors) if err != nil { *errors = append(*errors, err) continue @@ -4376,16 +4376,16 @@ func parseCurvePreferences(curveName string) (tls.CurveID, error) { } // Helper function to parse TLS configs. -func parseTLS(v interface{}, isClientCtx bool) (t *TLSConfigOpts, retErr error) { +func parseTLS(v any, isClientCtx bool) (t *TLSConfigOpts, retErr error) { var ( - tlsm map[string]interface{} + tlsm map[string]any tc = TLSConfigOpts{} lt token ) defer convertPanicToError(<, &retErr) tk, v := unwrapValue(v, <) - tlsm = v.(map[string]interface{}) + tlsm = v.(map[string]any) for mk, mv := range tlsm { tk, mv := unwrapValue(mv, <) switch strings.ToLower(mk) { @@ -4441,7 +4441,7 @@ func parseTLS(v interface{}, isClientCtx bool) (t *TLSConfigOpts, retErr error) } tc.TLSCheckKnownURLs = verify case "cipher_suites": - ra := mv.([]interface{}) + ra := mv.([]any) if len(ra) == 0 { return nil, &configErr{tk, "error parsing tls config, 'cipher_suites' cannot be empty"} } @@ -4455,7 +4455,7 @@ func parseTLS(v interface{}, isClientCtx bool) (t *TLSConfigOpts, retErr error) tc.Ciphers = append(tc.Ciphers, cipher) } case "curve_preferences": - ra := mv.([]interface{}) + ra := mv.([]any) if len(ra) == 0 { return nil, &configErr{tk, "error parsing tls config, 'curve_preferences' cannot be empty"} } @@ -4495,7 +4495,7 @@ func parseTLS(v interface{}, isClientCtx bool) (t *TLSConfigOpts, retErr error) } tc.RateLimit = at case "pinned_certs": - ra, ok := mv.([]interface{}) + ra, ok := mv.([]any) if !ok { return nil, &configErr{tk, "error parsing tls config, expected 'pinned_certs' to be a list of hex-encoded sha256 of DER encoded SubjectPublicKeyInfo"} } @@ -4545,7 +4545,7 @@ func parseTLS(v interface{}, isClientCtx bool) (t *TLSConfigOpts, retErr error) rv = append(rv, mv) case []string: rv = append(rv, mv...) - case []interface{}: + case []any: for _, t := range mv { if token, ok := t.(token); ok { if ts, ok := token.Value().(string); ok { @@ -4598,7 +4598,7 @@ func parseTLS(v interface{}, isClientCtx bool) (t *TLSConfigOpts, retErr error) pc.Verify = false tc.OCSPPeerConfig = pc } - case map[string]interface{}: + case map[string]any: pc, err := parseOCSPPeer(mv) if err != nil { return nil, &configErr{tk, err.Error()} @@ -4608,14 +4608,14 @@ func parseTLS(v interface{}, isClientCtx bool) (t *TLSConfigOpts, retErr error) return nil, &configErr{tk, fmt.Sprintf("error parsing ocsp peer config: unsupported type %T", v)} } case "certs", "certificates": - certs, ok := mv.([]interface{}) + certs, ok := mv.([]any) if !ok { return nil, &configErr{tk, fmt.Sprintf("error parsing certificates config: unsupported type %T", v)} } tc.Certificates = make([]*TLSCertPairOpt, len(certs)) for i, v := range certs { tk, vv := unwrapValue(v, <) - pair, ok := vv.(map[string]interface{}) + pair, ok := vv.(map[string]any) if !ok { return nil, &configErr{tk, fmt.Sprintf("error parsing certificates config: unsupported type %T", vv)} } @@ -4661,9 +4661,9 @@ func parseTLS(v interface{}, isClientCtx bool) (t *TLSConfigOpts, retErr error) return &tc, nil } -func parseSimpleAuth(v interface{}, errors *[]error, warnings *[]error) *authorization { +func parseSimpleAuth(v any, errors *[]error) *authorization { var ( - am map[string]interface{} + am map[string]any tk token lt token auth = &authorization{} @@ -4671,7 +4671,7 @@ func parseSimpleAuth(v interface{}, errors *[]error, warnings *[]error) *authori defer convertPanicToErrorList(<, errors) _, v = unwrapValue(v, <) - am = v.(map[string]interface{}) + am = v.(map[string]any) for mk, mv := range am { tk, mv = unwrapValue(mv, <) switch strings.ToLower(mk) { @@ -4706,11 +4706,11 @@ func parseSimpleAuth(v interface{}, errors *[]error, warnings *[]error) *authori return auth } -func parseStringArray(fieldName string, tk token, lt *token, mv interface{}, errors *[]error, warnings *[]error) ([]string, error) { +func parseStringArray(fieldName string, tk token, lt *token, mv any, errors *[]error) ([]string, error) { switch mv := mv.(type) { case string: return []string{mv}, nil - case []interface{}: + case []any: strs := make([]string, 0, len(mv)) for _, val := range mv { tk, val = unwrapValue(val, lt) @@ -4730,12 +4730,12 @@ func parseStringArray(fieldName string, tk token, lt *token, mv interface{}, err } } -func parseWebsocket(v interface{}, o *Options, errors *[]error, warnings *[]error) error { +func parseWebsocket(v any, o *Options, errors *[]error) error { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) - gm, ok := v.(map[string]interface{}) + gm, ok := v.(map[string]any) if !ok { return &configErr{tk, fmt.Sprintf("Expected websocket to be a map, got %T", v)} } @@ -4777,7 +4777,7 @@ func parseWebsocket(v interface{}, o *Options, errors *[]error, warnings *[]erro case "same_origin": o.Websocket.SameOrigin = mv.(bool) case "allowed_origins", "allowed_origin", "allow_origins", "allow_origin", "origins", "origin": - o.Websocket.AllowedOrigins, _ = parseStringArray("allowed origins", tk, <, mv, errors, warnings) + o.Websocket.AllowedOrigins, _ = parseStringArray("allowed origins", tk, <, mv, errors) case "handshake_timeout": ht := time.Duration(0) switch mv := mv.(type) { @@ -4799,7 +4799,7 @@ func parseWebsocket(v interface{}, o *Options, errors *[]error, warnings *[]erro case "compress", "compression": o.Websocket.Compression = mv.(bool) case "authorization", "authentication": - auth := parseSimpleAuth(tk, errors, warnings) + auth := parseSimpleAuth(tk, errors) o.Websocket.Username = auth.user o.Websocket.Password = auth.pass o.Websocket.Token = auth.token @@ -4815,7 +4815,7 @@ func parseWebsocket(v interface{}, o *Options, errors *[]error, warnings *[]erro case "no_auth_user": o.Websocket.NoAuthUser = mv.(string) case "headers": - m, ok := mv.(map[string]interface{}) + m, ok := mv.(map[string]any) if !ok { err := &configErr{tk, fmt.Sprintf("error parsing headers: unsupported type %T", mv)} *errors = append(*errors, err) @@ -4847,12 +4847,12 @@ func parseWebsocket(v interface{}, o *Options, errors *[]error, warnings *[]erro return nil } -func parseMQTT(v interface{}, o *Options, errors *[]error, warnings *[]error) error { +func parseMQTT(v any, o *Options, errors *[]error, warnings *[]error) error { var lt token defer convertPanicToErrorList(<, errors) tk, v := unwrapValue(v, <) - gm, ok := v.(map[string]interface{}) + gm, ok := v.(map[string]any) if !ok { return &configErr{tk, fmt.Sprintf("Expected mqtt to be a map, got %T", v)} } @@ -4889,7 +4889,7 @@ func parseMQTT(v interface{}, o *Options, errors *[]error, warnings *[]error) er o.MQTT.TLSPinnedCerts = tc.PinnedCerts o.MQTT.tlsConfigOpts = tc case "authorization", "authentication": - auth := parseSimpleAuth(tk, errors, warnings) + auth := parseSimpleAuth(tk, errors) o.MQTT.Username = auth.user o.MQTT.Password = auth.pass o.MQTT.Token = auth.token @@ -5525,33 +5525,33 @@ func ConfigureOptions(fs *flag.FlagSet, args []string, printVersion, printHelp, fs.Visit(func(f *flag.Flag) { switch f.Name { case "DVV": - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Debug", dbgAndTrcAndVerboseTrc) - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Trace", dbgAndTrcAndVerboseTrc) - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "TraceVerbose", dbgAndTrcAndVerboseTrc) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Debug", dbgAndTrcAndVerboseTrc) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", dbgAndTrcAndVerboseTrc) + trackExplicitVal(&FlagSnapshot.inCmdLine, "TraceVerbose", dbgAndTrcAndVerboseTrc) case "DV": - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Debug", dbgAndTrace) - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Trace", dbgAndTrace) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Debug", dbgAndTrace) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", dbgAndTrace) case "D": fallthrough case "debug": - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Debug", FlagSnapshot.Debug) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Debug", FlagSnapshot.Debug) case "VV": - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Trace", trcAndVerboseTrc) - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "TraceVerbose", trcAndVerboseTrc) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", trcAndVerboseTrc) + trackExplicitVal(&FlagSnapshot.inCmdLine, "TraceVerbose", trcAndVerboseTrc) case "V": fallthrough case "trace": - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Trace", FlagSnapshot.Trace) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", FlagSnapshot.Trace) case "T": fallthrough case "logtime": - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Logtime", FlagSnapshot.Logtime) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Logtime", FlagSnapshot.Logtime) case "s": fallthrough case "syslog": - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Syslog", FlagSnapshot.Syslog) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Syslog", FlagSnapshot.Syslog) case "no_advertise": - trackExplicitVal(FlagSnapshot, &FlagSnapshot.inCmdLine, "Cluster.NoAdvertise", FlagSnapshot.Cluster.NoAdvertise) + trackExplicitVal(&FlagSnapshot.inCmdLine, "Cluster.NoAdvertise", FlagSnapshot.Cluster.NoAdvertise) } }) diff --git a/server/opts_test.go b/server/opts_test.go index de9b21ff281..b42c8d9b855 100644 --- a/server/opts_test.go +++ b/server/opts_test.go @@ -2651,7 +2651,7 @@ func TestSublistNoCacheConfigOnAccounts(t *testing.T) { t.Fatalf("Expected to have a server with %d active accounts, got %v", ta, la) } - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) if acc == nil { t.Fatalf("Expected non-nil sublist for account") diff --git a/server/raft.go b/server/raft.go index f06561c982b..938a3b06567 100644 --- a/server/raft.go +++ b/server/raft.go @@ -1840,19 +1840,19 @@ func (n *raft) run() { } } -func (n *raft) debug(format string, args ...interface{}) { +func (n *raft) debug(format string, args ...any) { if n.dflag { nf := fmt.Sprintf("RAFT [%s - %s] %s", n.id, n.group, format) n.s.Debugf(nf, args...) } } -func (n *raft) warn(format string, args ...interface{}) { +func (n *raft) warn(format string, args ...any) { nf := fmt.Sprintf("RAFT [%s - %s] %s", n.id, n.group, format) n.s.RateLimitWarnf(nf, args...) } -func (n *raft) error(format string, args ...interface{}) { +func (n *raft) error(format string, args ...any) { nf := fmt.Sprintf("RAFT [%s - %s] %s", n.id, n.group, format) n.s.Errorf(nf, args...) } @@ -3761,22 +3761,20 @@ func (n *raft) setWriteErrLocked(err error) { return } // Ignore non-write errors. - if err != nil { - if err == ErrStoreClosed || - err == ErrStoreEOF || - err == ErrInvalidSequence || - err == ErrStoreMsgNotFound || - err == errNoPending || - err == errPartialCache { - return - } - // If this is a not found report but do not disable. - if os.IsNotExist(err) { - n.error("Resource not found: %v", err) - return - } - n.error("Critical write error: %v", err) + if err == ErrStoreClosed || + err == ErrStoreEOF || + err == ErrInvalidSequence || + err == ErrStoreMsgNotFound || + err == errNoPending || + err == errPartialCache { + return + } + // If this is a not found report but do not disable. + if os.IsNotExist(err) { + n.error("Resource not found: %v", err) + return } + n.error("Critical write error: %v", err) n.werr = err if isOutOfSpaceErr(err) { diff --git a/server/reload.go b/server/reload.go index 647203a2e69..edf6d06daf2 100644 --- a/server/reload.go +++ b/server/reload.go @@ -1126,7 +1126,7 @@ func (s *Server) reloadOptions(curOpts, newOpts *Options) error { } // For the purpose of comparing, impose a order on slice data types where order does not matter -func imposeOrder(value interface{}) error { +func imposeOrder(value any) error { switch value := value.(type) { case []*Account: sort.Slice(value, func(i, j int) bool { @@ -1876,7 +1876,7 @@ func (s *Server) reloadAuthorization() { } // Now range over existing accounts and keep track of the ones deleted // so some cleanup can be made after releasing the server lock. - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { an, acc := k.(string), v.(*Account) // Exclude default and system account from this test since those // may not actually be in opts.Accounts. @@ -1903,7 +1903,7 @@ func (s *Server) reloadAuthorization() { // With a memory resolver we want to do something similar to configured accounts. // We will walk the accounts and delete them if they are no longer present via fetch. // If they are present we will force a claim update to process changes. - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) // Skip global account. if acc == s.gacc { @@ -1955,7 +1955,7 @@ func (s *Server) reloadAuthorization() { s.accounts.Store(s.sys.account.Name, s.sys.account) } - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) acc.mu.RLock() // Check for sysclients accounting, ignore the system account. @@ -2151,7 +2151,7 @@ func (s *Server) reloadClusterPermissions(oldPerms *RoutePermissions) { // Then, go over all accounts and gather local subscriptions that need to be // sent over as SUB or removed as UNSUB, and routed subscriptions that need // to be dropped due to export permissions. - s.accounts.Range(func(_, v interface{}) bool { + s.accounts.Range(func(_, v any) bool { acc := v.(*Account) acc.mu.RLock() accName, sl, poolIdx := acc.Name, acc.sl, acc.routePoolIdx @@ -2366,7 +2366,7 @@ func (s *Server) reloadClusterPoolAndAccounts(co *clusterOption, opts *Options) // pool index. Note that the added/removed accounts will be reset there // too, but that's ok (we could use a map to exclude them, but not worth it). if co.poolSizeChanged { - s.accounts.Range(func(_, v interface{}) bool { + s.accounts.Range(func(_, v any) bool { acc := v.(*Account) acc.mu.Lock() s.setRouteInfo(acc) diff --git a/server/reload_test.go b/server/reload_test.go index 52e0fa87798..776f149346e 100644 --- a/server/reload_test.go +++ b/server/reload_test.go @@ -4598,7 +4598,7 @@ func TestConfigReloadDefaultSystemAccount(t *testing.T) { testInAccounts := func() { t.Helper() var found bool - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) if acc.GetName() == sname { found = true diff --git a/server/route.go b/server/route.go index b4b9a423760..af755fd3793 100644 --- a/server/route.go +++ b/server/route.go @@ -628,7 +628,7 @@ func (c *client) processRouteInfo(info *Info) { info.Gateway, remoteID) return } - s.processGatewayInfoFromRoute(info, remoteID, c) + s.processGatewayInfoFromRoute(info, remoteID) return } @@ -927,7 +927,7 @@ func (s *Server) updateRemoteRoutePerms(c *client, info *Info) { allSubs = _allSubs[:0] ) - s.accounts.Range(func(_, v interface{}) bool { + s.accounts.Range(func(_, v any) bool { acc := v.(*Account) acc.mu.RLock() accName, sl, accPoolIdx := acc.Name, acc.sl, acc.routePoolIdx @@ -1576,7 +1576,7 @@ func (s *Server) sendSubsToRoute(route *client, idx int, account string) { a.mu.RUnlock() } } else { - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { a := v.(*Account) a.mu.RLock() // We are here for regular or pooled routes (not per-account). diff --git a/server/routes_test.go b/server/routes_test.go index fbbddea7eb9..dac6210d11c 100644 --- a/server/routes_test.go +++ b/server/routes_test.go @@ -742,12 +742,12 @@ type checkDuplicateRouteLogger struct { gotDuplicate bool } -func (l *checkDuplicateRouteLogger) Noticef(format string, v ...interface{}) {} -func (l *checkDuplicateRouteLogger) Errorf(format string, v ...interface{}) {} -func (l *checkDuplicateRouteLogger) Warnf(format string, v ...interface{}) {} -func (l *checkDuplicateRouteLogger) Fatalf(format string, v ...interface{}) {} -func (l *checkDuplicateRouteLogger) Tracef(format string, v ...interface{}) {} -func (l *checkDuplicateRouteLogger) Debugf(format string, v ...interface{}) { +func (l *checkDuplicateRouteLogger) Noticef(format string, v ...any) {} +func (l *checkDuplicateRouteLogger) Errorf(format string, v ...any) {} +func (l *checkDuplicateRouteLogger) Warnf(format string, v ...any) {} +func (l *checkDuplicateRouteLogger) Fatalf(format string, v ...any) {} +func (l *checkDuplicateRouteLogger) Tracef(format string, v ...any) {} +func (l *checkDuplicateRouteLogger) Debugf(format string, v ...any) { l.Lock() defer l.Unlock() msg := fmt.Sprintf(format, v...) @@ -1242,7 +1242,7 @@ func TestRouteRTT(t *testing.T) { attempts := 0 timeout := time.Now().Add(2 * firstPingInterval) for time.Now().Before(timeout) { - if rtt := checkRTT(t, s); rtt != 0 { + if rtt := checkRTT(t, s); rtt != prev { return } attempts++ @@ -1399,7 +1399,7 @@ type routeHostLookupLogger struct { count int } -func (l *routeHostLookupLogger) Debugf(format string, v ...interface{}) { +func (l *routeHostLookupLogger) Debugf(format string, v ...any) { l.Lock() defer l.Unlock() msg := fmt.Sprintf(format, v...) @@ -1680,7 +1680,7 @@ type testRouteReconnectLogger struct { ch chan string } -func (l *testRouteReconnectLogger) Debugf(format string, v ...interface{}) { +func (l *testRouteReconnectLogger) Debugf(format string, v ...any) { msg := fmt.Sprintf(format, v...) if strings.Contains(msg, "Trying to connect to route") { select { @@ -2239,7 +2239,7 @@ type captureRMsgTrace struct { out []string } -func (l *captureRMsgTrace) Tracef(format string, args ...interface{}) { +func (l *captureRMsgTrace) Tracef(format string, args ...any) { l.Lock() defer l.Unlock() msg := fmt.Sprintf(format, args...) @@ -3360,7 +3360,7 @@ type testDuplicateRouteLogger struct { ch chan struct{} } -func (l *testDuplicateRouteLogger) Noticef(format string, args ...interface{}) { +func (l *testDuplicateRouteLogger) Noticef(format string, args ...any) { msg := fmt.Sprintf(format, args...) if !strings.Contains(msg, DuplicateRoute.String()) { return diff --git a/server/server.go b/server/server.go index 7c9926ccb36..e6f81d5fed2 100644 --- a/server/server.go +++ b/server/server.go @@ -1230,7 +1230,7 @@ func (s *Server) configureAccounts(reloading bool) (map[string]struct{}, error) } } var numAccounts int - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { numAccounts++ acc := v.(*Account) acc.mu.Lock() @@ -1419,7 +1419,7 @@ func (s *Server) globalAccountOnly() bool { } s.mu.RLock() - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) // Ignore global and system if acc == s.gacc || (s.sys != nil && acc == s.sys.account) { @@ -1445,7 +1445,7 @@ func (s *Server) configuredRoutes() int { // activePeers is used in bootstrapping raft groups like the JetStream meta controller. func (s *Server) ActivePeers() (peers []string) { - s.nodeToInfo.Range(func(k, v interface{}) bool { + s.nodeToInfo.Range(func(k, v any) bool { si := v.(nodeInfo) if !si.offline { peers = append(peers, k.(string)) @@ -1602,7 +1602,7 @@ func (s *Server) decActiveAccounts() { func (s *Server) numAccounts() int { count := 0 s.mu.RLock() - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { count++ return true }) @@ -1765,7 +1765,7 @@ func (s *Server) setSystemAccount(acc *Account) error { // If we have existing accounts make sure we enable account tracking. s.mu.Lock() - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) s.enableAccountTracking(acc) return true @@ -2322,7 +2322,7 @@ func (s *Server) Start() { var hasSys, hasGlobal bool var total int - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { total++ acc := v.(*Account) if acc == sa { @@ -3578,7 +3578,7 @@ func (s *Server) NumSubscriptions() uint32 { // Lock should be held. func (s *Server) numSubscriptions() uint32 { var subs int - s.accounts.Range(func(k, v interface{}) bool { + s.accounts.Range(func(k, v any) bool { acc := v.(*Account) subs += acc.TotalSubs() return true @@ -4415,7 +4415,7 @@ func (s *Server) startRateLimitLogExpiration() { case interval = <-s.rateLimitLoggingCh: ticker.Reset(interval) case <-ticker.C: - s.rateLimitLogging.Range(func(k, v interface{}) bool { + s.rateLimitLogging.Range(func(k, v any) bool { start := v.(time.Time) if time.Since(start) >= interval { s.rateLimitLogging.Delete(k) diff --git a/server/stream.go b/server/stream.go index db766654f71..f02b43d693c 100644 --- a/server/stream.go +++ b/server/stream.go @@ -2222,7 +2222,7 @@ func (mset *stream) processInboundMirrorMsg(m *inMsg) bool { var needsRetry bool // Flow controls have reply subjects. if m.rply != _EMPTY_ { - mset.handleFlowControl(mset.mirror, m) + mset.handleFlowControl(m) } else { // For idle heartbeats make sure we did not miss anything and check if we are considered stalled. if ldseq := parseInt64(getHeader(JSLastConsumerSeq, m.hdr)); ldseq > 0 && uint64(ldseq) != mset.mirror.dseq { @@ -3148,7 +3148,7 @@ func (mset *stream) sendFlowControlReply(reply string) { // handleFlowControl will properly handle flow control messages for both R==1 and R>1. // Lock should be held. -func (mset *stream) handleFlowControl(si *sourceInfo, m *inMsg) { +func (mset *stream) handleFlowControl(m *inMsg) { // If we are clustered we will send the flow control message through the replication stack. if mset.isClustered() { mset.node.Propose(encodeStreamMsg(_EMPTY_, m.rply, m.hdr, nil, 0, 0)) @@ -3184,7 +3184,7 @@ func (mset *stream) processInboundSourceMsg(si *sourceInfo, m *inMsg) bool { var needsRetry bool // Flow controls have reply subjects. if m.rply != _EMPTY_ { - mset.handleFlowControl(si, m) + mset.handleFlowControl(m) } else { // For idle heartbeats make sure we did not miss anything. if ldseq := parseInt64(getHeader(JSLastConsumerSeq, m.hdr)); ldseq > 0 && uint64(ldseq) != si.dseq { @@ -3994,7 +3994,7 @@ func (mset *stream) queueInbound(ib *ipQueue[*inMsg], subj, rply string, hdr, ms } var dgPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &directGetReq{} }, } diff --git a/server/sublist.go b/server/sublist.go index 0d70cb64f0b..ebd7e69def1 100644 --- a/server/sublist.go +++ b/server/sublist.go @@ -504,7 +504,7 @@ func (s *Sublist) addToCache(subject string, sub *subscription) { // removeFromCache will remove the sub from any active cache entries. // Assumes write lock is held. -func (s *Sublist) removeFromCache(subject string, sub *subscription) { +func (s *Sublist) removeFromCache(subject string) { if s.cache == nil { return } @@ -635,7 +635,7 @@ func (s *Sublist) UpdateRemoteQSub(sub *subscription) { // it unless we are thrashing the cache. Just remove from our L2 and update // the genid so L1 will be flushed. s.Lock() - s.removeFromCache(string(sub.subject), sub) + s.removeFromCache(string(sub.subject)) atomic.AddUint64(&s.genid, 1) s.Unlock() } @@ -798,7 +798,7 @@ func (s *Sublist) remove(sub *subscription, shouldLock bool, doCacheUpdates bool } } if doCacheUpdates { - s.removeFromCache(subject, sub) + s.removeFromCache(subject) atomic.AddUint64(&s.genid, 1) } diff --git a/server/sublist_test.go b/server/sublist_test.go index f2633039156..1e2e0288b3c 100644 --- a/server/sublist_test.go +++ b/server/sublist_test.go @@ -29,7 +29,7 @@ import ( "github.com/nats-io/nuid" ) -func stackFatalf(t *testing.T, f string, args ...interface{}) { +func stackFatalf(t *testing.T, f string, args ...any) { lines := make([]string, 0, 32) msg := fmt.Sprintf(f, args...) lines = append(lines, msg) @@ -1124,7 +1124,7 @@ func TestSublistRegisterInterestNotification(t *testing.T) { ch := make(chan bool, 1) expectErr := func(subject string) { - if err := s.RegisterNotification("foo.*", ch); err != ErrInvalidSubject { + if err := s.RegisterNotification(subject, ch); err != ErrInvalidSubject { t.Fatalf("Expected err, got %v", err) } } diff --git a/server/websocket_test.go b/server/websocket_test.go index a989abccd10..723e1a7df55 100644 --- a/server/websocket_test.go +++ b/server/websocket_test.go @@ -1817,7 +1817,7 @@ type captureFatalLogger struct { fatalCh chan string } -func (l *captureFatalLogger) Fatalf(format string, v ...interface{}) { +func (l *captureFatalLogger) Fatalf(format string, v ...any) { select { case l.fatalCh <- fmt.Sprintf(format, v...): default: @@ -1990,7 +1990,7 @@ func testNewWSClientWithError(t testing.TB, o testWSClientOptions) (net.Conn, *b type testClaimsOptions struct { nac *jwt.AccountClaims nuc *jwt.UserClaims - connectRequest interface{} + connectRequest any dontSign bool expectAnswer string } @@ -4121,7 +4121,7 @@ type captureClientConnectedLogger struct { ch chan string } -func (l *captureClientConnectedLogger) Debugf(format string, v ...interface{}) { +func (l *captureClientConnectedLogger) Debugf(format string, v ...any) { msg := fmt.Sprintf(format, v...) if !strings.Contains(msg, "Client connection created") { return diff --git a/test/cluster_test.go b/test/cluster_test.go index a7f0121b9ff..fb0c5f5c860 100644 --- a/test/cluster_test.go +++ b/test/cluster_test.go @@ -598,7 +598,7 @@ type captureErrLogger struct { ch chan string } -func (c *captureErrLogger) Errorf(format string, v ...interface{}) { +func (c *captureErrLogger) Errorf(format string, v ...any) { msg := fmt.Sprintf(format, v...) select { case c.ch <- msg: diff --git a/test/cluster_tls_test.go b/test/cluster_tls_test.go index 3238424c8ec..bd1ef73d508 100644 --- a/test/cluster_tls_test.go +++ b/test/cluster_tls_test.go @@ -72,7 +72,7 @@ type captureTLSError struct { ch chan struct{} } -func (c *captureTLSError) Errorf(format string, v ...interface{}) { +func (c *captureTLSError) Errorf(format string, v ...any) { msg := fmt.Sprintf(format, v...) if strings.Contains(msg, "handshake error") { select { @@ -87,7 +87,7 @@ type captureClusterTLSInsecureLogger struct { ch chan struct{} } -func (c *captureClusterTLSInsecureLogger) Warnf(format string, v ...interface{}) { +func (c *captureClusterTLSInsecureLogger) Warnf(format string, v ...any) { msg := fmt.Sprintf(format, v...) if strings.Contains(msg, "solicited routes will not be verified") { select { diff --git a/test/leafnode_test.go b/test/leafnode_test.go index 2d95119b4c1..b1bfb132bb1 100644 --- a/test/leafnode_test.go +++ b/test/leafnode_test.go @@ -1268,7 +1268,7 @@ type captureLeafNodeErrLogger struct { ch chan string } -func (c *captureLeafNodeErrLogger) Errorf(format string, v ...interface{}) { +func (c *captureLeafNodeErrLogger) Errorf(format string, v ...any) { msg := fmt.Sprintf(format, v...) select { case c.ch <- msg: diff --git a/test/routes_test.go b/test/routes_test.go index a9e8ccd821b..16254f06c83 100644 --- a/test/routes_test.go +++ b/test/routes_test.go @@ -528,8 +528,8 @@ func TestRouteResendsLocalSubsOnReconnect(t *testing.T) { type ignoreLogger struct{} -func (l *ignoreLogger) Fatalf(f string, args ...interface{}) {} -func (l *ignoreLogger) Errorf(f string, args ...interface{}) {} +func (l *ignoreLogger) Fatalf(f string, args ...any) {} +func (l *ignoreLogger) Errorf(f string, args ...any) {} func TestRouteConnectOnShutdownRace(t *testing.T) { s, opts := runRouteServer(t) diff --git a/test/test.go b/test/test.go index 623763b4cec..08ec926679d 100644 --- a/test/test.go +++ b/test/test.go @@ -33,8 +33,8 @@ import ( // So we can pass tests and benchmarks.. type tLogger interface { - Fatalf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) + Fatalf(format string, args ...any) + Errorf(format string, args ...any) } // DefaultTestOptions are default options for the unit tests. @@ -135,7 +135,7 @@ func RunServerWithConfigOverrides(configFile string, optsCallback func(*server.O return } -func stackFatalf(t tLogger, f string, args ...interface{}) { +func stackFatalf(t tLogger, f string, args ...any) { lines := make([]string, 0, 32) msg := fmt.Sprintf(f, args...) lines = append(lines, msg) diff --git a/test/test_test.go b/test/test_test.go index 43782e8e162..0c7e0bf26c6 100644 --- a/test/test_test.go +++ b/test/test_test.go @@ -131,25 +131,25 @@ type dummyLogger struct { msg string } -func (d *dummyLogger) Fatalf(format string, args ...interface{}) { +func (d *dummyLogger) Fatalf(format string, args ...any) { d.Lock() d.msg = fmt.Sprintf(format, args...) d.Unlock() } -func (d *dummyLogger) Errorf(format string, args ...interface{}) { +func (d *dummyLogger) Errorf(format string, args ...any) { } -func (d *dummyLogger) Debugf(format string, args ...interface{}) { +func (d *dummyLogger) Debugf(format string, args ...any) { } -func (d *dummyLogger) Tracef(format string, args ...interface{}) { +func (d *dummyLogger) Tracef(format string, args ...any) { } -func (d *dummyLogger) Noticef(format string, args ...interface{}) { +func (d *dummyLogger) Noticef(format string, args ...any) { } -func (d *dummyLogger) Warnf(format string, args ...interface{}) { +func (d *dummyLogger) Warnf(format string, args ...any) { } func TestStackFatal(t *testing.T) { diff --git a/test/tls_test.go b/test/tls_test.go index 0fc391cb831..2f56fc63e9f 100644 --- a/test/tls_test.go +++ b/test/tls_test.go @@ -1112,7 +1112,7 @@ type captureSlowConsumerLogger struct { gotIt bool } -func (l *captureSlowConsumerLogger) Noticef(format string, v ...interface{}) { +func (l *captureSlowConsumerLogger) Noticef(format string, v ...any) { msg := fmt.Sprintf(format, v...) if strings.Contains(msg, "Slow Consumer") { l.Lock() @@ -1880,7 +1880,7 @@ func newCaptureWarnLogger() *captureWarnLogger { } } -func (l *captureWarnLogger) Warnf(format string, v ...interface{}) { +func (l *captureWarnLogger) Warnf(format string, v ...any) { l.receive <- fmt.Sprintf(format, v...) }