diff --git a/charts/devtron/devtron-bom.yaml b/charts/devtron/devtron-bom.yaml index b6b280e960..3ea0399c00 100644 --- a/charts/devtron/devtron-bom.yaml +++ b/charts/devtron/devtron-bom.yaml @@ -150,15 +150,15 @@ components: # Change below values for nats nats: registry: "" - image: nats:2.9.3-alpine + image: nats:2.14.9-alpine reloader: - image: nats-server-config-reloader:0.6.2 + image: nats-server-config-reloader:0.25.0 imagePullPolicy: IfNotPresent metrics: - image: prometheus-nats-exporter:0.9.0 + image: prometheus-nats-exporter:0.20.3 imagePullPolicy: IfNotPresent natsBox: - image: nats-box + image: nats-box:0.20.1 serviceMonitor: enabled: false persistence: diff --git a/charts/devtron/values.yaml b/charts/devtron/values.yaml index 85c462ed14..d8b834c608 100644 --- a/charts/devtron/values.yaml +++ b/charts/devtron/values.yaml @@ -235,15 +235,15 @@ components: # Change below values for nats nats: registry: "" - image: nats:2.9.3-alpine + image: nats:2.14.9-alpine reloader: - image: nats-server-config-reloader:0.6.2 + image: nats-server-config-reloader:0.25.0 imagePullPolicy: IfNotPresent metrics: - image: prometheus-nats-exporter:0.9.0 + image: prometheus-nats-exporter:0.20.3 imagePullPolicy: IfNotPresent natsBox: - image: nats-box + image: nats-box:0.20.1 serviceMonitor: enabled: false persistence: diff --git a/devtron-images.txt.source b/devtron-images.txt.source index 73b6331a72..d680afd26d 100644 --- a/devtron-images.txt.source +++ b/devtron-images.txt.source @@ -31,14 +31,14 @@ quay.io/devtron/migrator:v4.16.2 quay.io/devtron/minideb:latest quay.io/devtron/minio-mc:RELEASE.2021-02-14T04-28-06Z quay.io/devtron/minio:RELEASE.2021-02-14T04-01-33Z -quay.io/devtron/nats-box -quay.io/devtron/nats-server-config-reloader:0.6.2 -quay.io/devtron/nats:2.9.3-alpine +quay.io/devtron/nats-box:0.20.1 +quay.io/devtron/nats-server-config-reloader:0.25.0 +quay.io/devtron/nats:2.14.9-alpine quay.io/devtron/notifier:9804331c-372-39294 quay.io/devtron/postgres:14.9 quay.io/devtron/postgres_exporter:v0.10.1 quay.io/devtron/postgres_exporter:v0.4.7 -quay.io/devtron/prometheus-nats-exporter:0.9.0 +quay.io/devtron/prometheus-nats-exporter:0.20.3 quay.io/devtron/ubuntu-k8s-utils:latest quay.io/devtron/cost-sync:46ed7c67-1159-38183 quay.io/devtron/timescaledb-ha:pg18 diff --git a/go.mod b/go.mod index b7c8010c30..49fffe886e 100644 --- a/go.mod +++ b/go.mod @@ -174,7 +174,7 @@ require ( github.com/json-iterator/go v1.1.12 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/kevinburke/ssh_config v1.2.0 // indirect - github.com/klauspost/compress v1.18.0 // indirect + github.com/klauspost/compress v1.18.5 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect github.com/mailru/easyjson v0.9.1 // indirect @@ -190,8 +190,8 @@ require ( github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect - github.com/nats-io/nats.go v1.43.0 // indirect - github.com/nats-io/nkeys v0.4.11 // indirect + github.com/nats-io/nats.go v1.53.1 // indirect + github.com/nats-io/nkeys v0.4.15 // indirect github.com/nats-io/nuid v1.0.1 // indirect github.com/opencontainers/go-digest v1.0.0 github.com/opencontainers/image-spec v1.1.1 // indirect diff --git a/go.sum b/go.sum index 35eaf954f1..14ae8f4022 100644 --- a/go.sum +++ b/go.sum @@ -604,6 +604,8 @@ github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47e github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= +github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= @@ -689,8 +691,12 @@ github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f h1:y5//uYreIhSUg3J github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= github.com/nats-io/nats.go v1.43.0 h1:uRFZ2FEoRvP64+UUhaTokyS18XBCR/xM2vQZKO4i8ug= github.com/nats-io/nats.go v1.43.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g= +github.com/nats-io/nats.go v1.53.1 h1:Otsq3uLc/kLdjmkNHkXH0jBqwUquwdKFoe3fq6/3/Xo= +github.com/nats-io/nats.go v1.53.1/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno= github.com/nats-io/nkeys v0.4.11 h1:q44qGV008kYd9W1b1nEBkNzvnWxtRSQ7A8BoqRrcfa0= github.com/nats-io/nkeys v0.4.11/go.mod h1:szDimtgmfOi9n25JpfIdGw12tZFYXqhGxjhVxsatHVE= +github.com/nats-io/nkeys v0.4.15 h1:JACV5jRVO9V856KOapQ7x+EY8Jo3qw1vJt/9Jpwzkk4= +github.com/nats-io/nkeys v0.4.15/go.mod h1:CpMchTXC9fxA5zrMo4KpySxNjiDVvr8ANOSZdiNfUrs= github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= diff --git a/manifests/yamls/nats-server.yaml b/manifests/yamls/nats-server.yaml index dcec1052e4..318a47efc6 100644 --- a/manifests/yamls/nats-server.yaml +++ b/manifests/yamls/nats-server.yaml @@ -131,7 +131,7 @@ spec: terminationGracePeriodSeconds: 120 containers: - name: nats - image: nats:2.9.3-alpine + image: nats:2.14.9-alpine imagePullPolicy: IfNotPresent resources: {} @@ -214,7 +214,7 @@ spec: ################################# - name: reloader - image: quay.io/devtron/nats-server-config-reloader:0.6.2 + image: quay.io/devtron/nats-server-config-reloader:0.25.0 imagePullPolicy: IfNotPresent resources: null @@ -238,7 +238,7 @@ spec: ############################## - name: metrics - image: quay.io/devtron/prometheus-nats-exporter:0.9.0 + image: quay.io/devtron/prometheus-nats-exporter:0.20.3 imagePullPolicy: IfNotPresent resources: {} @@ -282,7 +282,7 @@ metadata: spec: containers: - name: nats-box - image: quay.io/devtron/nats-box + image: quay.io/devtron/nats-box:0.20.1 env: - name: NATS_HOST value: devtron-nats diff --git a/tests/integrationTesting/nats-server.yaml b/tests/integrationTesting/nats-server.yaml index 662e428ac8..737259bd7f 100644 --- a/tests/integrationTesting/nats-server.yaml +++ b/tests/integrationTesting/nats-server.yaml @@ -136,7 +136,7 @@ spec: terminationGracePeriodSeconds: 120 containers: - name: nats - image: quay.io/devtron/nats:2.9.3-alpine + image: quay.io/devtron/nats:2.14.9-alpine imagePullPolicy: IfNotPresent resources: {} @@ -219,7 +219,7 @@ spec: ################################# - name: reloader - image: quay.io/devtron/nats-server-config-reloader:0.6.2 + image: quay.io/devtron/nats-server-config-reloader:0.25.0 imagePullPolicy: IfNotPresent resources: null @@ -243,7 +243,7 @@ spec: ############################## - name: metrics - image: quay.io/devtron/prometheus-nats-exporter:0.9.0 + image: quay.io/devtron/prometheus-nats-exporter:0.20.3 imagePullPolicy: IfNotPresent resources: {} diff --git a/vendor/github.com/klauspost/compress/flate/deflate.go b/vendor/github.com/klauspost/compress/flate/deflate.go index af53fb860c..57d17eeab9 100644 --- a/vendor/github.com/klauspost/compress/flate/deflate.go +++ b/vendor/github.com/klauspost/compress/flate/deflate.go @@ -6,11 +6,12 @@ package flate import ( - "encoding/binary" "errors" "fmt" "io" "math" + + "github.com/klauspost/compress/internal/le" ) const ( @@ -234,12 +235,9 @@ func (d *compressor) fillWindow(b []byte) { // Calculate 256 hashes at the time (more L1 cache hits) loops := (n + 256 - minMatchLength) / 256 - for j := 0; j < loops; j++ { + for j := range loops { startindex := j * 256 - end := startindex + 256 + minMatchLength - 1 - if end > n { - end = n - } + end := min(startindex+256+minMatchLength-1, n) tocheck := d.window[startindex:end] dstSize := len(tocheck) - minMatchLength + 1 @@ -269,18 +267,12 @@ func (d *compressor) fillWindow(b []byte) { // We only look at chainCount possibilities before giving up. // pos = s.index, prevHead = s.chainHead-s.hashOffset, prevLength=minMatchLength-1, lookahead func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, offset int, ok bool) { - minMatchLook := maxMatchLength - if lookahead < minMatchLook { - minMatchLook = lookahead - } + minMatchLook := min(lookahead, maxMatchLength) win := d.window[0 : pos+minMatchLook] // We quit when we get a match that's at least nice long - nice := len(win) - pos - if d.nice < nice { - nice = d.nice - } + nice := min(d.nice, len(win)-pos) // If we've got a match that's good enough, only look in 1/4 the chain. tries := d.chain @@ -288,10 +280,7 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of wEnd := win[pos+length] wPos := win[pos:] - minIndex := pos - windowSize - if minIndex < 0 { - minIndex = 0 - } + minIndex := max(pos-windowSize, 0) offset = 0 if d.chain < 100 { @@ -374,7 +363,7 @@ func (d *compressor) writeStoredBlock(buf []byte) error { // of the supplied slice. // The caller must ensure that len(b) >= 4. func hash4(b []byte) uint32 { - return hash4u(binary.LittleEndian.Uint32(b), hashBits) + return hash4u(le.Load32(b, 0), hashBits) } // hash4 returns the hash of u to fit in a hash table with h bits. @@ -389,7 +378,7 @@ func bulkHash4(b []byte, dst []uint32) { if len(b) < 4 { return } - hb := binary.LittleEndian.Uint32(b) + hb := le.Load32(b, 0) dst[0] = hash4u(hb, hashBits) end := len(b) - 4 + 1 @@ -432,7 +421,9 @@ func (d *compressor) deflateLazy() { d.h = newHuffmanEncoder(maxFlateBlockTokens) } var tmp [256]uint16 - for _, v := range d.window[s.index:d.windowEnd] { + toIndex := d.window[s.index:d.windowEnd] + toIndex = toIndex[:min(len(toIndex), maxFlateBlockTokens)] + for _, v := range toIndex { tmp[v]++ } d.h.generate(tmp[:], 15) @@ -480,10 +471,7 @@ func (d *compressor) deflateLazy() { prevOffset := s.offset s.length = minMatchLength - 1 s.offset = 0 - minIndex := s.index - windowSize - if minIndex < 0 { - minIndex = 0 - } + minIndex := max(s.index-windowSize, 0) if s.chainHead-s.hashOffset >= minIndex && lookahead > prevLength && prevLength < d.lazy { if newLength, newOffset, ok := d.findMatch(s.index, s.chainHead-s.hashOffset, lookahead); ok { @@ -503,10 +491,7 @@ func (d *compressor) deflateLazy() { if prevLength < maxMatchLength-checkOff { prevIndex := s.index - 1 if prevIndex+prevLength < s.maxInsertIndex { - end := lookahead - if lookahead > maxMatchLength+checkOff { - end = maxMatchLength + checkOff - } + end := min(lookahead, maxMatchLength+checkOff) end += prevIndex // Hash at match end. @@ -603,15 +588,9 @@ func (d *compressor) deflateLazy() { // table. newIndex := s.index + prevLength - 1 // Calculate missing hashes - end := newIndex - if end > s.maxInsertIndex { - end = s.maxInsertIndex - } + end := min(newIndex, s.maxInsertIndex) end += minMatchLength - 1 - startindex := s.index + 1 - if startindex > s.maxInsertIndex { - startindex = s.maxInsertIndex - } + startindex := min(s.index+1, s.maxInsertIndex) tocheck := d.window[startindex:end] dstSize := len(tocheck) - minMatchLength + 1 if dstSize > 0 { diff --git a/vendor/github.com/klauspost/compress/flate/dict_decoder.go b/vendor/github.com/klauspost/compress/flate/dict_decoder.go index bb36351a5a..cb855abc4b 100644 --- a/vendor/github.com/klauspost/compress/flate/dict_decoder.go +++ b/vendor/github.com/klauspost/compress/flate/dict_decoder.go @@ -104,10 +104,7 @@ func (dd *dictDecoder) writeCopy(dist, length int) int { dstBase := dd.wrPos dstPos := dstBase srcPos := dstPos - dist - endPos := dstPos + length - if endPos > len(dd.hist) { - endPos = len(dd.hist) - } + endPos := min(dstPos+length, len(dd.hist)) // Copy non-overlapping section after destination position. // diff --git a/vendor/github.com/klauspost/compress/flate/fast_encoder.go b/vendor/github.com/klauspost/compress/flate/fast_encoder.go index 0e8b1630c0..791c9dcbfd 100644 --- a/vendor/github.com/klauspost/compress/flate/fast_encoder.go +++ b/vendor/github.com/klauspost/compress/flate/fast_encoder.go @@ -7,7 +7,6 @@ package flate import ( "fmt" - "math/bits" "github.com/klauspost/compress/internal/le" ) @@ -151,29 +150,9 @@ func (e *fastGen) matchlen(s, t int, src []byte) int32 { panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) } } - s1 := min(s+maxMatchLength-4, len(src)) - left := s1 - s - n := int32(0) - for left >= 8 { - diff := le.Load64(src, s) ^ le.Load64(src, t) - if diff != 0 { - return n + int32(bits.TrailingZeros64(diff)>>3) - } - s += 8 - t += 8 - n += 8 - left -= 8 - } - - a := src[s:s1] + a := src[s:min(s+maxMatchLength-4, len(src))] b := src[t:] - for i := range a { - if a[i] != b[i] { - break - } - n++ - } - return n + return int32(matchLen(a, b)) } // matchlenLong will return the match length between offsets and t in src. @@ -193,29 +172,7 @@ func (e *fastGen) matchlenLong(s, t int, src []byte) int32 { panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) } } - // Extend the match to be as long as possible. - left := len(src) - s - n := int32(0) - for left >= 8 { - diff := le.Load64(src, s) ^ le.Load64(src, t) - if diff != 0 { - return n + int32(bits.TrailingZeros64(diff)>>3) - } - s += 8 - t += 8 - n += 8 - left -= 8 - } - - a := src[s:] - b := src[t:] - for i := range a { - if a[i] != b[i] { - break - } - n++ - } - return n + return int32(matchLen(src[s:], src[t:])) } // Reset the encoding table. diff --git a/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go b/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go index afdc8c053a..7151140ccd 100644 --- a/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go +++ b/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go @@ -211,7 +211,9 @@ func (w *huffmanBitWriter) flush() { n++ } w.bits = 0 - w.write(w.bytes[:n]) + if n > 0 { + w.write(w.bytes[:n]) + } w.nbytes = 0 } @@ -303,10 +305,7 @@ func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litE w.codegenFreq[size]++ count-- for count >= 3 { - n := 6 - if n > count { - n = count - } + n := min(6, count) codegen[outIndex] = 16 outIndex++ codegen[outIndex] = uint8(n - 3) @@ -316,10 +315,7 @@ func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litE } } else { for count >= 11 { - n := 138 - if n > count { - n = count - } + n := min(138, count) codegen[outIndex] = 18 outIndex++ codegen[outIndex] = uint8(n - 11) @@ -438,8 +434,8 @@ func (w *huffmanBitWriter) writeOutBits() { w.nbits -= 48 n := w.nbytes - // We over-write, but faster... - le.Store64(w.bytes[n:], bits) + // We overwrite, but faster... + le.Store64(w.bytes[:], n, bits) n += 6 if n >= bufferFlushSize { @@ -472,7 +468,7 @@ func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, n w.writeBits(int32(numOffsets-1), 5) w.writeBits(int32(numCodegens-4), 4) - for i := 0; i < numCodegens; i++ { + for i := range numCodegens { value := uint(w.codegenEncoding.codes[codegenOrder[i]].len()) w.writeBits(int32(value), 3) } @@ -650,7 +646,7 @@ func (w *huffmanBitWriter) writeBlockDynamic(tokens *tokens, eof bool, input []b w.lastHeader = 0 } - numLiterals, numOffsets := w.indexTokens(tokens, !sync) + numLiterals, numOffsets := w.indexTokens(tokens, true) extraBits := 0 ssize, storable := w.storedSize(input) @@ -785,7 +781,7 @@ func (w *huffmanBitWriter) fillTokens() { // literalFreq and offsetFreq, and generates literalEncoding // and offsetEncoding. // The number of literal and offset tokens is returned. -func (w *huffmanBitWriter) indexTokens(t *tokens, filled bool) (numLiterals, numOffsets int) { +func (w *huffmanBitWriter) indexTokens(t *tokens, alwaysEOB bool) (numLiterals, numOffsets int) { //copy(w.literalFreq[:], t.litHist[:]) *(*[256]uint16)(w.literalFreq[:]) = t.litHist //copy(w.literalFreq[256:], t.extraHist[:]) @@ -795,9 +791,10 @@ func (w *huffmanBitWriter) indexTokens(t *tokens, filled bool) (numLiterals, num if t.n == 0 { return } - if filled { - return maxNumLit, maxNumDist + if alwaysEOB { + w.literalFreq[endBlockMarker] = 1 } + // get the number of literals numLiterals = len(w.literalFreq) for w.literalFreq[numLiterals-1] == 0 { @@ -855,8 +852,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= c.code64() << (nbits & 63) nbits += c.len() if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -883,8 +879,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= c.code64() << (nbits & 63) nbits += c.len() if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -906,8 +901,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= uint64(extraLength) << (nbits & 63) nbits += extraLengthBits if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -932,8 +926,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= c.code64() << (nbits & 63) nbits += c.len() if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -954,8 +947,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= uint64((offset-(offsetComb>>8))&matchOffsetOnlyMask) << (nbits & 63) nbits += uint8(offsetComb) if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -1108,7 +1100,7 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) { // We must have at least 48 bits free. if nbits >= 8 { n := nbits >> 3 - le.Store64(w.bytes[nbytes:], bits) + le.Store64(w.bytes[:], nbytes, bits) bits >>= (n * 8) & 63 nbits -= n * 8 nbytes += n @@ -1137,8 +1129,7 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) { // Remaining... for _, t := range input { if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 diff --git a/vendor/github.com/klauspost/compress/flate/huffman_code.go b/vendor/github.com/klauspost/compress/flate/huffman_code.go index be7b58b473..4b312dea3e 100644 --- a/vendor/github.com/klauspost/compress/flate/huffman_code.go +++ b/vendor/github.com/klauspost/compress/flate/huffman_code.go @@ -91,7 +91,7 @@ func generateFixedLiteralEncoding() *huffmanEncoder { h := newHuffmanEncoder(literalCount) codes := h.codes var ch uint16 - for ch = 0; ch < literalCount; ch++ { + for ch = range uint16(literalCount) { var bits uint16 var size uint8 switch { @@ -407,8 +407,8 @@ func histogramSplit(b []byte, h []uint16) { for i, t := range x { v0 := &h[t] v1 := &h[y[i]] - v3 := &h[w[i]] v2 := &h[z[i]] + v3 := &h[w[i]] *v0++ *v1++ *v2++ diff --git a/vendor/github.com/klauspost/compress/flate/inflate.go b/vendor/github.com/klauspost/compress/flate/inflate.go index 0d7b437f1c..6e90126db0 100644 --- a/vendor/github.com/klauspost/compress/flate/inflate.go +++ b/vendor/github.com/klauspost/compress/flate/inflate.go @@ -485,7 +485,7 @@ func (f *decompressor) readHuffman() error { f.nb -= 5 + 5 + 4 // (HCLEN+4)*3 bits: code lengths in the magic codeOrder order. - for i := 0; i < nclen; i++ { + for i := range nclen { for f.nb < 3 { if err := f.moreBits(); err != nil { return err @@ -776,7 +776,7 @@ func fixedHuffmanDecoderInit() { fixedOnce.Do(func() { // These come from the RFC section 3.2.6. var bits [288]int - for i := 0; i < 144; i++ { + for i := range 144 { bits[i] = 8 } for i := 144; i < 256; i++ { diff --git a/vendor/github.com/klauspost/compress/flate/level5.go b/vendor/github.com/klauspost/compress/flate/level5.go index 6e5c21502f..a22ad7d125 100644 --- a/vendor/github.com/klauspost/compress/flate/level5.go +++ b/vendor/github.com/klauspost/compress/flate/level5.go @@ -677,10 +677,7 @@ func (e *fastEncL5Window) matchlen(s, t int32, src []byte) int32 { panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) } } - s1 := int(s) + maxMatchLength - 4 - if s1 > len(src) { - s1 = len(src) - } + s1 := min(int(s)+maxMatchLength-4, len(src)) // Extend the match to be as long as possible. return int32(matchLen(src[s:s1], src[t:])) diff --git a/vendor/github.com/klauspost/compress/flate/regmask_other.go b/vendor/github.com/klauspost/compress/flate/regmask_other.go index 1b7a2cbd79..e62caf711e 100644 --- a/vendor/github.com/klauspost/compress/flate/regmask_other.go +++ b/vendor/github.com/klauspost/compress/flate/regmask_other.go @@ -1,5 +1,4 @@ //go:build !amd64 -// +build !amd64 package flate diff --git a/vendor/github.com/klauspost/compress/flate/stateless.go b/vendor/github.com/klauspost/compress/flate/stateless.go index 13b9b100db..455ed3e2b5 100644 --- a/vendor/github.com/klauspost/compress/flate/stateless.go +++ b/vendor/github.com/klauspost/compress/flate/stateless.go @@ -56,18 +56,24 @@ func NewStatelessWriter(dst io.Writer) io.WriteCloser { // bitWriterPool contains bit writers that can be reused. var bitWriterPool = sync.Pool{ - New: func() interface{} { + New: func() any { return newHuffmanBitWriter(nil) }, } +// tokensPool contains tokens struct objects that can be reused +var tokensPool = sync.Pool{ + New: func() any { + return &tokens{} + }, +} + // StatelessDeflate allows compressing directly to a Writer without retaining state. // When returning everything will be flushed. // Up to 8KB of an optional dictionary can be given which is presumed to precede the block. // Longer dictionaries will be truncated and will still produce valid output. // Sending nil dictionary is perfectly fine. func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { - var dst tokens bw := bitWriterPool.Get().(*huffmanBitWriter) bw.reset(out) defer func() { @@ -91,6 +97,12 @@ func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { // For subsequent loops, keep shallow dict reference to avoid alloc+copy. var inDict []byte + dst := tokensPool.Get().(*tokens) + dst.Reset() + defer func() { + tokensPool.Put(dst) + }() + for len(in) > 0 { todo := in if len(inDict) > 0 { @@ -113,9 +125,9 @@ func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { } // Compress if len(inDict) == 0 { - statelessEnc(&dst, todo, int16(len(dict))) + statelessEnc(dst, todo, int16(len(dict))) } else { - statelessEnc(&dst, inDict[:maxStatelessDict+len(todo)], maxStatelessDict) + statelessEnc(dst, inDict[:maxStatelessDict+len(todo)], maxStatelessDict) } isEof := eof && len(in) == 0 @@ -129,7 +141,7 @@ func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { // If we removed less than 1/16th, huffman compress the block. bw.writeBlockHuff(isEof, uncompressed, len(in) == 0) } else { - bw.writeBlockDynamic(&dst, isEof, uncompressed, len(in) == 0) + bw.writeBlockDynamic(dst, isEof, uncompressed, len(in) == 0) } if len(in) > 0 { // Retain a dict if we have more @@ -184,7 +196,7 @@ func statelessEnc(dst *tokens, src []byte, startAt int16) { // Index until startAt if startAt > 0 { cv := load3232(src, 0) - for i := int16(0); i < startAt; i++ { + for i := range startAt { table[hashSL(cv)] = tableEntry{offset: i} cv = (cv >> 8) | (uint32(src[i+4]) << 24) } diff --git a/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go b/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go index 0cfb5c0e27..4f2a0d8c58 100644 --- a/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go +++ b/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go @@ -37,6 +37,6 @@ func Store32(b []byte, v uint32) { } // Store64 will store v at b. -func Store64(b []byte, v uint64) { - binary.LittleEndian.PutUint64(b, v) +func Store64[I Indexer](b []byte, i I, v uint64) { + binary.LittleEndian.PutUint64(b[i:], v) } diff --git a/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go b/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go index ada45cd909..218a38bc4a 100644 --- a/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go +++ b/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go @@ -38,18 +38,15 @@ func Load64[I Indexer](b []byte, i I) uint64 { // Store16 will store v at b. func Store16(b []byte, v uint16) { - //binary.LittleEndian.PutUint16(b, v) *(*uint16)(unsafe.Pointer(unsafe.SliceData(b))) = v } // Store32 will store v at b. func Store32(b []byte, v uint32) { - //binary.LittleEndian.PutUint32(b, v) *(*uint32)(unsafe.Pointer(unsafe.SliceData(b))) = v } -// Store64 will store v at b. -func Store64(b []byte, v uint64) { - //binary.LittleEndian.PutUint64(b, v) - *(*uint64)(unsafe.Pointer(unsafe.SliceData(b))) = v +// Store64 will store v at b[i:]. +func Store64[I Indexer](b []byte, i I, v uint64) { + *(*uint64)(unsafe.Add(unsafe.Pointer(unsafe.SliceData(b)), i)) = v } diff --git a/vendor/github.com/klauspost/compress/s2/README.md b/vendor/github.com/klauspost/compress/s2/README.md index 1d9220cbf5..b0bf59fbbd 100644 --- a/vendor/github.com/klauspost/compress/s2/README.md +++ b/vendor/github.com/klauspost/compress/s2/README.md @@ -1,3 +1,17 @@ +# MinLZ + +I have taken the experiences from this library and created a backwards compatible compression package called MinLZ. + +That package will seamlessly decode S2 content, making the transition from this package fairly trivial. + +There are many improvements to pretty much all aspects of S2 since we have "broken free" of the Snappy format specification. +You can read a writeup on [Design and Improvements over S2](https://gist.github.com/klauspost/a25b66198cdbdf7b5b224f670c894ed5). + +The only aspect not covered is custom dictionary encoding. While I do intend to fix errors in this package, +I do not expect to make significant improvements, since I consider MinLZ a better basis for going forward. + +See https://github.com/minio/minlz for all details. + # S2 Compression S2 is an extension of [Snappy](https://github.com/google/snappy). diff --git a/vendor/github.com/klauspost/compress/s2/decode_other.go b/vendor/github.com/klauspost/compress/s2/decode_other.go index c99d40b69d..2905ba2774 100644 --- a/vendor/github.com/klauspost/compress/s2/decode_other.go +++ b/vendor/github.com/klauspost/compress/s2/decode_other.go @@ -4,7 +4,6 @@ // license that can be found in the LICENSE file. //go:build (!amd64 && !arm64) || appengine || !gc || noasm -// +build !amd64,!arm64 appengine !gc noasm package s2 diff --git a/vendor/github.com/klauspost/compress/s2/encode.go b/vendor/github.com/klauspost/compress/s2/encode.go index 20b802270a..330e755716 100644 --- a/vendor/github.com/klauspost/compress/s2/encode.go +++ b/vendor/github.com/klauspost/compress/s2/encode.go @@ -117,8 +117,10 @@ func EstimateBlockSize(src []byte) (d int) { func EncodeBetter(dst, src []byte) []byte { if n := MaxEncodedLen(len(src)); n < 0 { panic(ErrTooLarge) - } else if len(dst) < n { + } else if cap(dst) < n { dst = make([]byte, n) + } else { + dst = dst[:n] } // The block starts with the varint-encoded length of the decompressed bytes. @@ -159,8 +161,10 @@ func EncodeBetter(dst, src []byte) []byte { func EncodeBest(dst, src []byte) []byte { if n := MaxEncodedLen(len(src)); n < 0 { panic(ErrTooLarge) - } else if len(dst) < n { + } else if cap(dst) < n { dst = make([]byte, n) + } else { + dst = dst[:n] } // The block starts with the varint-encoded length of the decompressed bytes. diff --git a/vendor/github.com/klauspost/compress/s2/encode_all.go b/vendor/github.com/klauspost/compress/s2/encode_all.go index a473b64529..9d12c44f38 100644 --- a/vendor/github.com/klauspost/compress/s2/encode_all.go +++ b/vendor/github.com/klauspost/compress/s2/encode_all.go @@ -903,10 +903,7 @@ func encodeBlockDictGo(dst, src []byte, dict *Dict) (d int) { // sLimit is when to stop looking for offset/length copies. The inputMargin // lets us use a fast path for emitLiteral in the main loop, while we are // looking for copies. - sLimit := len(src) - inputMargin - if sLimit > MaxDictSrcOffset-maxAhead { - sLimit = MaxDictSrcOffset - maxAhead - } + sLimit := min(len(src)-inputMargin, MaxDictSrcOffset-maxAhead) // Bail if we can't compress to at least this. dstLimit := len(src) - len(src)>>5 - 5 diff --git a/vendor/github.com/klauspost/compress/s2/encode_amd64.go b/vendor/github.com/klauspost/compress/s2/encode_amd64.go index 7aadd255fe..68d72a41d3 100644 --- a/vendor/github.com/klauspost/compress/s2/encode_amd64.go +++ b/vendor/github.com/klauspost/compress/s2/encode_amd64.go @@ -1,5 +1,4 @@ //go:build !appengine && !noasm && gc -// +build !appengine,!noasm,gc package s2 diff --git a/vendor/github.com/klauspost/compress/s2/encode_best.go b/vendor/github.com/klauspost/compress/s2/encode_best.go index 47bac74234..c857c5c283 100644 --- a/vendor/github.com/klauspost/compress/s2/encode_best.go +++ b/vendor/github.com/klauspost/compress/s2/encode_best.go @@ -42,10 +42,7 @@ func encodeBlockBest(dst, src []byte, dict *Dict) (d int) { if len(src) < minNonLiteralBlockSize { return 0 } - sLimitDict := len(src) - inputMargin - if sLimitDict > MaxDictSrcOffset-inputMargin { - sLimitDict = MaxDictSrcOffset - inputMargin - } + sLimitDict := min(len(src)-inputMargin, MaxDictSrcOffset-inputMargin) var lTable [maxLTableSize]uint64 var sTable [maxSTableSize]uint64 diff --git a/vendor/github.com/klauspost/compress/s2/encode_better.go b/vendor/github.com/klauspost/compress/s2/encode_better.go index 90ebf89c20..1e30fb7317 100644 --- a/vendor/github.com/klauspost/compress/s2/encode_better.go +++ b/vendor/github.com/klauspost/compress/s2/encode_better.go @@ -914,10 +914,7 @@ func encodeBlockBetterDict(dst, src []byte, dict *Dict) (d int) { debug = false ) - sLimit := len(src) - inputMargin - if sLimit > MaxDictSrcOffset-maxAhead { - sLimit = MaxDictSrcOffset - maxAhead - } + sLimit := min(len(src)-inputMargin, MaxDictSrcOffset-maxAhead) if len(src) < minNonLiteralBlockSize { return 0 } diff --git a/vendor/github.com/klauspost/compress/s2/encode_go.go b/vendor/github.com/klauspost/compress/s2/encode_go.go index e25b78445d..5597f3ef2e 100644 --- a/vendor/github.com/klauspost/compress/s2/encode_go.go +++ b/vendor/github.com/klauspost/compress/s2/encode_go.go @@ -1,5 +1,4 @@ //go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm package s2 diff --git a/vendor/github.com/klauspost/compress/s2/index.go b/vendor/github.com/klauspost/compress/s2/index.go index 4229957b96..fb7db25315 100644 --- a/vendor/github.com/klauspost/compress/s2/index.go +++ b/vendor/github.com/klauspost/compress/s2/index.go @@ -72,7 +72,7 @@ func (i *Index) add(compressedOffset, uncompressedOffset int64) error { return fmt.Errorf("internal error: Earlier uncompressed received (%d > %d)", latest.uncompressedOffset, uncompressedOffset) } if latest.compressedOffset > compressedOffset { - return fmt.Errorf("internal error: Earlier compressed received (%d > %d)", latest.uncompressedOffset, uncompressedOffset) + return fmt.Errorf("internal error: Earlier compressed received (%d > %d)", latest.compressedOffset, compressedOffset) } if latest.uncompressedOffset+minIndexDist > uncompressedOffset { // Only add entry if distance is large enough. diff --git a/vendor/github.com/klauspost/compress/s2/reader.go b/vendor/github.com/klauspost/compress/s2/reader.go index 8372d752f9..4d01c4190c 100644 --- a/vendor/github.com/klauspost/compress/s2/reader.go +++ b/vendor/github.com/klauspost/compress/s2/reader.go @@ -1046,7 +1046,7 @@ func (r *Reader) ReadByte() (byte, error) { return c, nil } var tmp [1]byte - for i := 0; i < 10; i++ { + for range 10 { n, err := r.Read(tmp[:]) if err != nil { return 0, err diff --git a/vendor/github.com/klauspost/compress/s2/writer.go b/vendor/github.com/klauspost/compress/s2/writer.go index fd15078f7d..09f1cff3a9 100644 --- a/vendor/github.com/klauspost/compress/s2/writer.go +++ b/vendor/github.com/klauspost/compress/s2/writer.go @@ -47,7 +47,7 @@ func NewWriter(w io.Writer, opts ...WriterOption) *Writer { w2.obufLen = obufHeaderLen + MaxEncodedLen(w2.blockSize) w2.paramsOK = true w2.ibuf = make([]byte, 0, w2.blockSize) - w2.buffers.New = func() interface{} { + w2.buffers.New = func() any { return make([]byte, w2.obufLen) } w2.Reset(w) diff --git a/vendor/github.com/nats-io/nats.go/.gitignore b/vendor/github.com/nats-io/nats.go/.gitignore index ae4871f468..01716ae1b1 100644 --- a/vendor/github.com/nats-io/nats.go/.gitignore +++ b/vendor/github.com/nats-io/nats.go/.gitignore @@ -21,6 +21,9 @@ _testmain.go *.exe +# Git backup files +*.orig + # Emacs *~ \#*\# @@ -42,4 +45,4 @@ _testmain.go .idea # VS Code -.vscode \ No newline at end of file +.vscode diff --git a/vendor/github.com/nats-io/nats.go/CLAUDE.md b/vendor/github.com/nats-io/nats.go/CLAUDE.md new file mode 100644 index 0000000000..2d8e042204 --- /dev/null +++ b/vendor/github.com/nats-io/nats.go/CLAUDE.md @@ -0,0 +1,174 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +Official Go client library for the NATS messaging system. Provides core pub/sub, request/reply, JetStream (streams, consumers, KV, object store), and a micro services framework. Module path: `github.com/nats-io/nats.go`. + +## Build and Test Commands + +This project uses a **dual module** setup: `go.mod` for production (minimal deps) and `go_test.mod` for testing (protobuf encoder + jwt + nkeys + nuid). Always use `-modfile=go_test.mod` when running tests. + +Integration tests (everything in `./test/`, `./jetstream/test/`, `./micro/test/`) run against a remote **ntf-server** docker service (`synadia/ntf-server:v0.0.5-nats-2.14.3`) instead of an in-process nats-server. Bring it up first via the Makefile, then run tests with `TESTER_NATS_URL` pointing at it. + +```bash +# Start the tester (host-side mode publishes the tester's ports so `go test` +# from your terminal can reach the spawned NATS servers via localhost). +make tester-up-host + +# Run all tests against the tester (single command, covers both white-box +# tests at the repo root and integration tests in ./test/, ./jetstream/test/, +# ./micro/test/). +TESTER_NATS_URL=nats://localhost:4222 \ + go test -modfile=go_test.mod -race -v -p=1 ./... --failfast -vet=off -tags=internal_testing + +# Run NoRace tests (must be run separately, without -race flag) +TESTER_NATS_URL=nats://localhost:4222 \ + go test -modfile=go_test.mod -v -run=TestNoRace -p=1 ./... --failfast -vet=off + +# Run a specific test +TESTER_NATS_URL=nats://localhost:4222 \ + go test -modfile=go_test.mod -race -tags=internal_testing -run TestName ./... + +# Run tests for a specific package +TESTER_NATS_URL=nats://localhost:4222 go test -modfile=go_test.mod -race ./jetstream/test/... --failfast +TESTER_NATS_URL=nats://localhost:4222 go test -modfile=go_test.mod -race ./micro/test/... --failfast + +# Makefile wrappers for the above (TESTER_NATS_URL defaults to nats://localhost:4222) +make test # full race-enabled suite with internal_testing tag +make test T=TestName PKG=./test/... # single test, verbose +make test-norace # NoRace suite + +# Stop the tester +make tester-down + +# Alternative: run the full suite inside an alpine sibling container (matches CI). +# Doesn't need TESTER_NATS_URL or tester-up-host — the Makefile target handles it. +make test-tester + +# Build +go build ./... + +# Formatting +go fmt -modfile=go_test.mod ./... + +# Vet +go vet -modfile=go_test.mod ./... + +# Static analysis (as CI does it) +staticcheck -modfile=go_test.mod ./... + +# Linting (golangci-lint runs only on jetstream/; the modfile GOFLAGS lets it +# typecheck jetstream/test, whose deps live in go_test.mod only) +GOFLAGS="-mod=mod -modfile=go_test.mod" golangci-lint run --timeout 5m0s ./jetstream/... + +# Spell check +find . -type f -name "*.go" | xargs misspell -error -locale US + +# Update test dependencies (never change go.mod for test deps) +go mod tidy -modfile=go_test.mod +``` + +If `TESTER_NATS_URL` is unset, the integration tests skip via `t.Skip` rather than fail — so default `go test ./...` on a fresh checkout just runs the white-box unit tests. + +## Important Build Tags + +- **`internal_testing`** -- Exposes internal test helpers (e.g., `AddMsgFilter`, `CloseTCPConn`) from `testing_internal.go`. Required for some tests in `./test/`. +- **`!race && !skip_no_race_tests`** -- NoRace tests in `test/norace_test.go` only run when the race detector is OFF. +- **`compat`** -- Compatibility tests in `test/compat_test.go` (connect to an external NATS server via `NATS_URL`). +- **`go1.23`** -- Iterator-based tests in `test/nats_iter_test.go` and `nats_iter.go`. + +## CI Pipeline (ci.yaml) + +1. **lint** -- `go fmt`, `go vet`, `staticcheck`, `misspell` (all packages), `golangci-lint` (jetstream only). +2. **test** -- Matrix of Go 1.25 and 1.26. Runs inside an `alpine` container on the same docker network as the `synadia/ntf-server` service, which is started with `command: serve --advertise nats` (the integration tests dial the spawned NATS servers by service name). Two steps: NoRace tests (without `-race`), then full race-enabled tests with `-tags=internal_testing` (the Go 1.26 row runs `scripts/cov.sh` for coverage instead of the plain race run). + +## Project Structure + +``` +nats.go # Core connection, pub/sub, request/reply (~6500 lines) +parser.go # Client-side protocol parser +ws.go # WebSocket transport support +js.go # Legacy JetStream API (deprecated, see jetstream/) +jsm.go # Legacy JetStream management +kv.go # Legacy KeyValue API +object.go # Legacy Object Store API +enc.go # EncodedConn (deprecated) +netchan.go # Go channel bindings +timer.go # Internal timer utilities +context.go # Context-aware request methods +nats_iter.go # Go 1.23+ iterator support (go:build go1.23) +testing_internal.go # Internal test hooks (go:build internal_testing) + +jetstream/ # New JetStream API (preferred over legacy) + jetstream.go # Top-level JetStream interface + stream.go # Stream management + stream_config.go # Stream configuration types + consumer.go # Consumer management + consumer_config.go # Consumer configuration types + pull.go # Pull consumer implementation + push.go # Push consumer (deprecated) + ordered.go # Ordered consumer + publish.go # JetStream publish methods + kv.go # KeyValue store + object.go # Object store + message.go # JetStream message types + errors.go # JetStream error types + test/ # Integration tests (package test, uses testservice) + +micro/ # Micro services framework + service.go # Service interface and implementation + request.go # Request handling + test/ # Integration tests + +internal/ + parser/ # NATS protocol parser (used by core client) + syncx/ # Concurrent map utility + +encoders/ + builtin/ # Default encoders (JSON, GOB, string) + protobuf/ # Protocol Buffers encoder + +test/ # Integration tests for core package (package test) + testservice_helper_test.go # withServer / withServerInstance / newTester / dialInstance helpers + helper_test.go # Shared utility helpers (Wait, checkFor, getStableNumGoroutine, ...) + norace_test.go # Tests that cannot run with -race (build tag guarded) + js_internal_test.go # Tests requiring internal_testing tag + configs/certs/ # CA/server/key PEMs loaded by TLS tests (the *.conf files are unused) + +bench/ # Benchmarking utilities +examples/ # Example command-line tools (nats-pub, nats-sub, etc.) +scripts/cov.sh # Coverage collection script (run by the CI coverage matrix row) +``` + +The tester client is an external test-only dependency: `github.com/synadia-io/orbit.go/ntf-client` +(package `ntf`, imported under the alias `testservice`). It lives in `go_test.mod` only. + +## Test Architecture + +- **Root `nats_test.go`** (package `nats`) -- White-box unit tests with access to unexported internals. +- **`test/`** (package `test`) -- Black-box integration tests. Tests bring up a NATS server via the testservice helpers (`withServer`, `withJSServer`, `withJSCluster`, ...) which talk to a remote `synadia/ntf-server:v0.0.5-nats-2.14.3` docker service over NATS. `TESTER_NATS_URL` must point at that service; if unset, tests skip via `t.Skip`. +- **`jetstream/test/`** (package `test`) -- Integration tests for the new JetStream API, same testservice harness. +- **`micro/test/`** (package `micro_test`) -- Integration tests for the micro services framework, same testservice harness. +- **NoRace tests** -- Prefixed `TestNoRace*`, guarded by `//go:build !race && !skip_no_race_tests`. Must be run separately without `-race`. +- Tests always run with `-p=1` (no parallel packages) because the tester serializes some bookkeeping that doesn't tolerate concurrent CreateServer calls from independent test binaries. + +## Code Conventions + +- **License header** -- Every `.go` file starts with the Apache 2.0 license header (Copyright year range). +- **Error variables** -- Exported errors defined as `var Err... = errors.New("nats: ...")` in `nats.go`. JetStream errors in `jetstream/errors.go` follow the same pattern. +- **Options pattern** -- Connection options use functional options: `nats.Connect(url, nats.Name("myapp"), nats.MaxReconnects(5))`. JetStream and micro use similar patterns. +- **No external dependencies in production** -- Only `klauspost/compress`, `nkeys`, `nuid` in `go.mod`. Test deps (protobuf, jwt, etc.) are isolated in `go_test.mod`. PRs adding dependencies are scrutinized heavily. +- **Commits require sign-off** -- Use `git commit -s` (DCO: `Signed-off-by`). +- **US English spelling** -- Enforced by `misspell -locale US` in CI. +- **Interface-driven design** -- JetStream and micro packages define interfaces (`JetStream`, `Stream`, `Consumer`, `Service`) with concrete unexported implementations. + +## Key Types + +- `nats.Conn` -- Core connection, handles all NATS protocol operations. +- `nats.Msg` -- Message type for pub/sub and request/reply. +- `nats.Subscription` -- Represents a subscription (sync, async, or channel-based). +- `jetstream.JetStream` -- Entry point for new JetStream API (created via `jetstream.New(nc)`). +- `jetstream.Stream`, `jetstream.Consumer` -- Stream and consumer management. +- `micro.Service` -- Micro service instance (created via `micro.AddService(nc, config)`). diff --git a/vendor/github.com/nats-io/nats.go/CONTRIBUTING.md b/vendor/github.com/nats-io/nats.go/CONTRIBUTING.md index cfb7e4e8af..666cdaf9cd 100644 --- a/vendor/github.com/nats-io/nats.go/CONTRIBUTING.md +++ b/vendor/github.com/nats-io/nats.go/CONTRIBUTING.md @@ -66,15 +66,23 @@ send your question to the [NATS Google Group](https://groups.google.com/forum/#! ## Testing -You should use `go_test.mod` to manage your testing dependencies. Please use the following command to update your -dependencies and avoid changing the main `go.mod` in a PR: +The integration tests run against real NATS servers spawned by the +[synadia/ntf-server](https://hub.docker.com/r/synadia/ntf-server) docker service. See [TESTING.md](TESTING.md) for the +full workflow; the short version: ```shell -go mod tidy -modfile=go_test.mod +make tester-up-host # once: start the test-server manager (requires docker) +make test T=TestName PKG=./test/... # iterate on a single test +make test # full race-enabled suite +make tester-down # tear everything down ``` -To the tests you can pass `-modfile=go_test.mod` flag to `go test` or instead you can also set `GOFLAGS="-modfile=go_test.mod"` as an environment variable: +Without a running tester (`TESTER_NATS_URL` unset), `go test ./...` runs only the unit tests — the integration suites +skip silently, so a green run on a fresh checkout does not mean the integration tests passed. + +You should use `go_test.mod` to manage your testing dependencies. Please use the following command to update your +dependencies and avoid changing the main `go.mod` in a PR: ```shell -go test ./... -modfile=go_test.mod +go mod tidy -modfile=go_test.mod ``` diff --git a/vendor/github.com/nats-io/nats.go/Makefile b/vendor/github.com/nats-io/nats.go/Makefile new file mode 100644 index 0000000000..0a7100f9fd --- /dev/null +++ b/vendor/github.com/nats-io/nats.go/Makefile @@ -0,0 +1,127 @@ +# Local convenience targets for running tests against the synadia/ntf-server +# service. The CI `test` job (.github/workflows/ci.yaml) runs the same suite, +# with the tester attached as a docker service container. +# +# Quick start (sibling-container mode — full suite, matches CI): +# make tester-up # start the tester container on a dedicated docker network +# make test-tester # run the full suite inside a sibling container +# make tester-down # tear everything down +# +# Quick start (host-side mode — iterating on individual tests): +# make tester-up-host # start the tester with its ports published +# make test T=TestName PKG=./test/... +# make tester-down +# +# `make test` wraps the full `go test` incantation (modfile, internal_testing +# tag, -race, -p=1). The equivalent raw command is: +# TESTER_NATS_URL=nats://localhost:4222 \ +# go test -modfile=go_test.mod -tags=internal_testing -race -p=1 ./... --failfast -vet=off +# `-p=1` is required: the tester does not tolerate concurrent CreateServer +# calls from independent test binaries. + +# The tester image is pinned in ci.yaml (the single source of truth); parse it +# from there so server version bumps happen in one place. +TESTER_IMAGE ?= $(shell sed -n 's|^ *image: *\(synadia/ntf-server:[^ ]*\).*|\1|p' .github/workflows/ci.yaml) +ifeq ($(strip $(TESTER_IMAGE)),) +$(error could not parse the tester image from .github/workflows/ci.yaml) +endif +TESTER_NAME ?= nats-tester +TESTER_NETWORK ?= nats-tester-net +GO_IMAGE ?= golang:1.26-alpine + +# Host-side test runs (tester started with `make tester-up-host`). +# T limits the run to a single test (-run, verbose); PKG limits the packages. +TESTER_NATS_URL ?= nats://localhost:4222 +PKG ?= ./... + +.PHONY: tester-net tester-up tester-up-host tester-down tester-restart tester-logs test-tester test test-norace + +# test runs the race-enabled suite, like CI. Examples: +# make test # everything +# make test T=TestSubSubject # one test, verbose +# make test PKG=./jetstream/test/... # one package +test: + TESTER_NATS_URL=$(TESTER_NATS_URL) go test -modfile=go_test.mod -tags=internal_testing -race -p=1 $(if $(T),-v -run '$(T)') $(PKG) --failfast -vet=off + +# test-norace runs the TestNoRace* tests, which must run with the race +# detector off. T overrides the -run pattern within the NoRace suite. +test-norace: + TESTER_NATS_URL=$(TESTER_NATS_URL) go test -modfile=go_test.mod -p=1 $(if $(T),-v) -run '$(or $(T),TestNoRace)' $(PKG) --failfast -vet=off + +tester-net: + @docker network inspect $(TESTER_NETWORK) >/dev/null 2>&1 || \ + docker network create $(TESTER_NETWORK) + +# tester-up runs the tester WITHOUT host port publishing. Use this when running +# tests via `make test-tester` (sibling-container mode — the test container is +# on the same docker network as the tester, so host port publishing is not +# only unnecessary, it actively breaks server bring-up: docker-proxy holds +# 0.0.0.0: inside the container's net namespace, racing the tester's +# localhost:0 port-reservation handover and causing intermittent +# "bind: address already in use" failures. +# +# No sysctl-constrained ephemeral port range either: the spawned servers can +# use the full kernel default (typically 32768-60999), so churn-driven TIME_WAIT +# accumulation never crowds the pool. The constrained range is only meaningful +# when ports must match a host-published range (see tester-up-host). +tester-up: tester-net + docker run -d \ + --name $(TESTER_NAME) \ + --network $(TESTER_NETWORK) \ + --restart unless-stopped \ + -e NATS_ADVERTISE=$(TESTER_NAME) \ + $(TESTER_IMAGE) serve + @echo "Tester running on docker network $(TESTER_NETWORK) as host '$(TESTER_NAME)'" + @echo "Sibling-container mode: use 'make test-tester' to run the suite." + @echo "For host-side dev (running 'go test' directly), use 'make tester-up-host' instead." + +# tester-up-host runs the tester WITH host port publishing for host-side dev +# workflows (running 'go test' directly from your terminal). The +# ip_local_port_range sysctl is intentionally narrowed to match the published +# port range so the tester's net.Listen(":0") picks ports the host can reach. +# Note: in this mode, docker-proxy on macOS races the tester's port handover +# and causes intermittent server-creation failures (~5-10% of runs in heavy +# suites); rerun the failing test or restart the tester if it happens. +# Sibling-container mode (tester-up + make test-tester) does not have this issue. +tester-up-host: tester-net + docker run -d \ + --name $(TESTER_NAME) \ + --network $(TESTER_NETWORK) \ + --restart unless-stopped \ + --sysctl net.ipv4.ip_local_port_range="30000 31000" \ + -p 4222:4222 \ + -p 30000-31000:30000-31000 \ + -e NATS_ADVERTISE=localhost \ + $(TESTER_IMAGE) serve + @echo "Tester running on docker network $(TESTER_NETWORK) as host '$(TESTER_NAME)'" + @echo "Run the full suite: make test" + @echo "Run a single test: make test T=TestName PKG=./test/..." + @echo "Or directly: TESTER_NATS_URL=nats://localhost:4222 go test -modfile=go_test.mod -tags=internal_testing -race -p=1 -v -run TestName ./test/..." + +# tester-down stops AND removes the container; logs are lost. Use tester-restart +# instead to keep the container (and its logs) around for debugging. +tester-down: + -docker rm -f $(TESTER_NAME) + -docker network rm $(TESTER_NETWORK) + +tester-restart: + -docker restart $(TESTER_NAME) + @echo "Tester restarted; logs preserved (use 'make tester-logs')" + +tester-logs: + docker logs -f $(TESTER_NAME) + +# test-tester runs the same suite as the CI `test` job: the NoRace pass first +# (needs the race detector off), then the full race-enabled suite with +# -tags=internal_testing. +test-tester: tester-net + docker run --rm \ + --network $(TESTER_NETWORK) \ + -v $(CURDIR):/src \ + -w /src \ + -e TESTER_NATS_URL=nats://$(TESTER_NAME):4222 \ + -e CGO_ENABLED=1 \ + $(GO_IMAGE) sh -c '\ + apk add --no-cache gcc libc-dev git make >/dev/null && \ + go test -modfile=go_test.mod -v -run=TestNoRace -p=1 ./... --failfast -vet=off && \ + go test -modfile=go_test.mod -tags=internal_testing -race -v -p=1 ./... --failfast -vet=off' diff --git a/vendor/github.com/nats-io/nats.go/README.md b/vendor/github.com/nats-io/nats.go/README.md index 087344d6c3..1e5e86ec9b 100644 --- a/vendor/github.com/nats-io/nats.go/README.md +++ b/vendor/github.com/nats-io/nats.go/README.md @@ -7,8 +7,8 @@ A [Go](http://golang.org) client for the [NATS messaging system](https://nats.io [License-Image]: https://img.shields.io/badge/License-Apache2-blue.svg [ReportCard-Url]: https://goreportcard.com/report/github.com/nats-io/nats.go [ReportCard-Image]: https://goreportcard.com/badge/github.com/nats-io/nats.go -[Build-Status-Url]: https://github.com/nats-io/nats.go/actions -[Build-Status-Image]: https://github.com/nats-io/nats.go/actions/workflows/ci.yaml/badge.svg?branch=main +[Build-Status-Url]: https://github.com/nats-io/nats.go/actions/workflows/ci.yaml?query=event%3Arelease +[Build-Status-Image]: https://github.com/nats-io/nats.go/actions/workflows/ci.yaml/badge.svg?event=release [GoDoc-Url]: https://pkg.go.dev/github.com/nats-io/nats.go [GoDoc-Image]: https://img.shields.io/badge/GoDoc-reference-007d9c [Coverage-Url]: https://coveralls.io/r/nats-io/nats.go?branch=main @@ -23,7 +23,7 @@ A [Go](http://golang.org) client for the [NATS messaging system](https://nats.io go get github.com/nats-io/nats.go@latest # To get a specific version: -go get github.com/nats-io/nats.go@v1.43.0 +go get github.com/nats-io/nats.go@v1.53.1 # Note that the latest major version for NATS Server is v2: go get github.com/nats-io/nats-server/v2@latest @@ -134,7 +134,7 @@ The simplest form is to use the helper method UserCredentials(credsFilepath). nc, err := nats.Connect(url, nats.UserCredentials("user.creds")) ``` -The helper methods creates two callback handlers to present the user JWT and sign the nonce challenge from the server. +The helper method creates two callback handlers to present the user JWT and sign the nonce challenge from the server. The core client library never has direct access to your private key and simply performs the callback for signing the server challenge. The helper will load and wipe and erase memory it uses for each connect or reconnect. @@ -177,7 +177,7 @@ nc, err := nats.Connect("tls://nats.demo.io:4443") // We provide a helper method to make this case easier. nc, err = nats.Connect("tls://localhost:4443", nats.RootCAs("./configs/certs/ca.pem")) -// If the server requires client certificate, there is an helper function for that too: +// If the server requires client certificate, there is a helper function for that too: cert := nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem") nc, err = nats.Connect("tls://localhost:4443", cert) @@ -210,17 +210,17 @@ if err != nil { // "*" matches any token, at any level of the subject. nc.Subscribe("foo.*.baz", func(m *Msg) { - fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)); + fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)) }) nc.Subscribe("foo.bar.*", func(m *Msg) { - fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)); + fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)) }) // ">" matches any length of the tail of a subject, and can only be the last token // E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22' nc.Subscribe("foo.>", func(m *Msg) { - fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)); + fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)) }) // Matches all of the above @@ -237,7 +237,7 @@ nc.Publish("foo.bar.baz", []byte("Hello World")) // Normal subscribers will continue to work as expected. nc.QueueSubscribe("foo", "job_workers", func(_ *Msg) { - received += 1; + received += 1 }) ``` @@ -267,9 +267,9 @@ fmt.Println("All clear!") // FlushTimeout specifies a timeout value as well. err := nc.FlushTimeout(1*time.Second) if err != nil { - fmt.Println("All clear!") -} else { fmt.Println("Flushed timed out!") +} else { + fmt.Println("All clear!") } // Auto-unsubscribe after MAX_WANTED messages received @@ -285,7 +285,7 @@ nc1.Subscribe("foo", func(m *Msg) { fmt.Printf("Received a message: %s\n", string(m.Data)) }) -nc2.Publish("foo", []byte("Hello World!")); +nc2.Publish("foo", []byte("Hello World!")) ``` @@ -339,7 +339,7 @@ nc, err = nats.Connect("nats://localhost:4222", nats.UserInfo("foo", "bar")) // For token based authentication: nc, err = nats.Connect("nats://localhost:4222", nats.Token("S3cretT0ken")) -// You can even pass the two at the same time in case one of the server +// You can even pass the two at the same time in case one of the servers // in the mesh requires token instead of user name and password. nc, err = nats.Connect("nats://localhost:4222", nats.UserInfo("foo", "bar"), @@ -372,7 +372,7 @@ msg, err := sub.NextMsgWithContext(ctx) ``` -## Backwards compatibility +## Backward compatibility In the development of nats.go, we are committed to maintaining backward compatibility and ensuring a stable and reliable experience for all users. In general, we follow the standard go compatibility guidelines. However, it's important to clarify our stance on certain types of changes: @@ -385,6 +385,10 @@ Extending public interfaces with new methods is also not viewed as a breaking ch Additionally, this library always supports at least 2 latest minor Go versions. For example, if the latest Go version is 1.22, the library will support Go 1.21 and 1.22. +## Testing + +See [TESTING.md](TESTING.md) for how to run the test suite locally. + ## License Unless otherwise noted, the NATS source files are distributed diff --git a/vendor/github.com/nats-io/nats.go/TESTING.md b/vendor/github.com/nats-io/nats.go/TESTING.md new file mode 100644 index 0000000000..748c4ed80e --- /dev/null +++ b/vendor/github.com/nats-io/nats.go/TESTING.md @@ -0,0 +1,106 @@ +# Testing + +## TL;DR + +```shell +make tester-up-host # once: start the test-server manager (requires docker) +make test T=TestName PKG=./test/... # iterate on a single test +make test # full race-enabled suite +make tester-down # tear everything down +``` + +## How the suite is set up + +The repo uses two module files: `go.mod` for production (minimal dependencies) +and `go_test.mod` for testing. Always pass `-modfile=go_test.mod` to `go test`; +the make targets below do this for you. + +Unit tests live at the repo root (package `nats`, white-box) and run with plain +`go test`. Integration tests live in `./test`, `./jetstream/test`, and +`./micro/test`; they bring up real NATS servers by talking to a **tester** +service (the `synadia/ntf-server` docker image, driven through the +`github.com/synadia-io/orbit.go/ntf-client` package) which spawns `nats-server` +instances, clusters, and super-clusters on demand. Tests find the tester via +the `TESTER_NATS_URL` environment variable. + +If `TESTER_NATS_URL` is unset, the integration tests **skip silently** — a +green `go test ./...` on a fresh checkout means only the unit tests ran. + +## Host-side mode (iterating on individual tests) + +`make tester-up-host` starts the tester with its ports published, so `go test` +run from your terminal can reach the spawned servers via localhost. + +```shell +make tester-up-host +make test T=TestSubSubject PKG=./test/... # one test, verbose +make test PKG=./jetstream/test/... # one package +make test # everything +make test-norace # NoRace tests (race detector off) +``` + +`make test` wraps the full invocation, which is equivalent to: + +```shell +TESTER_NATS_URL=nats://localhost:4222 \ + go test -modfile=go_test.mod -tags=internal_testing -race -p=1 ./... --failfast -vet=off +``` + +`-p=1` is required: the tester does not tolerate concurrent CreateServer calls +from independent test binaries. + +Known caveat: on macOS, docker-proxy races the tester's port handover, so in +heavy suites roughly 5-10% of server creations can fail with +`bind: address already in use`. Rerun the failing test, or use +sibling-container mode for full-suite runs. + +## Sibling-container mode (full suite, matches CI) + +```shell +make tester-up +make test-tester +make tester-down +``` + +`make test-tester` runs the whole suite (NoRace pass, then the race-enabled +pass) inside a Go container on the same docker network as the tester — no +published ports, so the docker-proxy race above does not apply. This is the +same shape CI uses, with the tester attached as a service container +(`.github/workflows/ci.yaml`). + +## NoRace tests + +Tests prefixed `TestNoRace` are guarded by `//go:build !race && +!skip_no_race_tests` and must run with the race detector off: +`make test-norace`. + +## Build tags + +- `internal_testing` — exposes internal test hooks from `testing_internal.go`; + required by some tests in `./test`. The make targets set it. +- `skip_no_race_tests` — excludes the NoRace tests from a non-race run (used + by `scripts/cov.sh`). +- `compat` — compatibility tests in `test/compat_test.go`, which connect to an + external NATS server via `NATS_URL`. +- `go1.23` — iterator-based tests in `test/nats_iter_test.go`. + +## Coverage + +```shell +TESTER_NATS_URL=nats://localhost:4222 ./scripts/cov.sh +``` + +Merges unit and integration coverage into `acc.out` and opens the HTML report +(CI passes an argument to skip the browser). + +## Troubleshooting + +- `cannot reach the tester at ...` — the tester is not running (or its ports + are not published); run `make tester-up-host`. +- Integration tests skip — `TESTER_NATS_URL` is unset. +- `make tester-logs` — follow the tester's logs; server spawn and config + errors show up there. +- `make tester-restart` — restart the tester but keep its logs; + `make tester-down` removes the container (and its logs). +- Updating test-only dependencies: `go mod tidy -modfile=go_test.mod` (never + change the main `go.mod` for test dependencies). diff --git a/vendor/github.com/nats-io/nats.go/context.go b/vendor/github.com/nats-io/nats.go/context.go index 382335e836..b3dfa4f06d 100644 --- a/vendor/github.com/nats-io/nats.go/context.go +++ b/vendor/github.com/nats-io/nats.go/context.go @@ -95,7 +95,7 @@ func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, hdr, dat s.AutoUnsubscribe(1) defer s.Unsubscribe() - err = nc.publish(subj, inbox, hdr, data) + err = nc.publish(subj, inbox, false, hdr, data) if err != nil { return nil, err } diff --git a/vendor/github.com/nats-io/nats.go/dependencies.md b/vendor/github.com/nats-io/nats.go/dependencies.md index ec9ab3c6ab..a2e85ba5a3 100644 --- a/vendor/github.com/nats-io/nats.go/dependencies.md +++ b/vendor/github.com/nats-io/nats.go/dependencies.md @@ -2,14 +2,14 @@ This file lists the dependencies used in this repository. -| Dependency | License | -|-----------------------------------|--------------| -| Go | BSD 3-Clause | -| github.com/golang/protobuf/proto | BSD-3-Clause | -| github.com/klauspost/compress | BSD-3-Clause | -| github.com/nats-io/nats-server/v2 | Apache-2.0 | -| github.com/nats-io/nkeys | Apache-2.0 | -| github.com/nats-io/nuid | Apache-2.0 | -| go.uber.org/goleak | MIT | -| golang.org/x/text | BSD-3-Clause | -| google.golang.org/protobuf | BSD-3-Clause | +| Dependency | License | +|-------------------------------------------|--------------| +| Go | BSD 3-Clause | +| github.com/golang/protobuf/proto | BSD-3-Clause | +| github.com/klauspost/compress | BSD-3-Clause | +| github.com/nats-io/nkeys | Apache-2.0 | +| github.com/nats-io/nuid | Apache-2.0 | +| github.com/synadia-io/orbit.go/ntf-client | Apache-2.0 | +| go.uber.org/goleak | MIT | +| golang.org/x/text | BSD-3-Clause | +| google.golang.org/protobuf | BSD-3-Clause | diff --git a/vendor/github.com/nats-io/nats.go/enc.go b/vendor/github.com/nats-io/nats.go/enc.go index 34a3fae7fe..f2297b49a7 100644 --- a/vendor/github.com/nats-io/nats.go/enc.go +++ b/vendor/github.com/nats-io/nats.go/enc.go @@ -107,7 +107,7 @@ func (c *EncodedConn) Publish(subject string, v any) error { if err != nil { return err } - return c.Conn.publish(subject, _EMPTY_, nil, b) + return c.Conn.publish(subject, _EMPTY_, false, nil, b) } // PublishRequest will perform a Publish() expecting a response on the @@ -120,7 +120,7 @@ func (c *EncodedConn) PublishRequest(subject, reply string, v any) error { if err != nil { return err } - return c.Conn.publish(subject, reply, nil, b) + return c.Conn.publish(subject, reply, true, nil, b) } // Request will create an Inbox and perform a Request() call diff --git a/vendor/github.com/nats-io/nats.go/go_test.mod b/vendor/github.com/nats-io/nats.go/go_test.mod index 5d2111b246..8f3051df1c 100644 --- a/vendor/github.com/nats-io/nats.go/go_test.mod +++ b/vendor/github.com/nats-io/nats.go/go_test.mod @@ -1,22 +1,19 @@ module github.com/nats-io/nats.go -go 1.23.0 +go 1.25.0 require ( - github.com/golang/protobuf v1.4.2 - github.com/klauspost/compress v1.18.0 - github.com/nats-io/jwt v1.2.2 - github.com/nats-io/nats-server/v2 v2.11.2 - github.com/nats-io/nkeys v0.4.11 + github.com/golang/protobuf v1.5.4 + github.com/klauspost/compress v1.19.1 + github.com/nats-io/jwt/v2 v2.8.1 + github.com/nats-io/nkeys v0.4.16 github.com/nats-io/nuid v1.0.1 - google.golang.org/protobuf v1.23.0 + github.com/synadia-io/orbit.go/ntf-client v0.0.3 + google.golang.org/protobuf v1.33.0 ) require ( - github.com/google/go-tpm v0.9.3 // indirect - github.com/minio/highwayhash v1.0.3 // indirect - github.com/nats-io/jwt/v2 v2.7.4 // indirect - golang.org/x/crypto v0.37.0 // indirect - golang.org/x/sys v0.32.0 // indirect - golang.org/x/time v0.11.0 // indirect + github.com/google/go-cmp v0.6.0 // indirect + golang.org/x/crypto v0.54.0 // indirect + golang.org/x/sys v0.47.0 // indirect ) diff --git a/vendor/github.com/nats-io/nats.go/go_test.sum b/vendor/github.com/nats-io/nats.go/go_test.sum index 6d411a20a7..d03954441f 100644 --- a/vendor/github.com/nats-io/nats.go/go_test.sum +++ b/vendor/github.com/nats-io/nats.go/go_test.sum @@ -1,52 +1,20 @@ -github.com/antithesishq/antithesis-sdk-go v0.4.3-default-no-op h1:+OSa/t11TFhqfrX0EOSqQBDJ0YlpmK0rDSiB19dg9M0= -github.com/antithesishq/antithesis-sdk-go v0.4.3-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-tpm v0.9.3 h1:+yx0/anQuGzi+ssRqeD6WpXjW2L/V0dItUayO0i9sRc= -github.com/google/go-tpm v0.9.3/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= -github.com/minio/highwayhash v1.0.3 h1:kbnuUMoHYyVl7szWjSxJnxw11k2U709jqFPPmIUyD6Q= -github.com/minio/highwayhash v1.0.3/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= -github.com/nats-io/jwt v1.2.2 h1:w3GMTO969dFg+UOKTmmyuu7IGdusK+7Ytlt//OYH/uU= -github.com/nats-io/jwt v1.2.2/go.mod h1:/xX356yQA6LuXI9xWW7mZNpxgF2mBmGecH+Fj34sP5Q= -github.com/nats-io/jwt/v2 v2.7.4 h1:jXFuDDxs/GQjGDZGhNgH4tXzSUK6WQi2rsj4xmsNOtI= -github.com/nats-io/jwt/v2 v2.7.4/go.mod h1:me11pOkwObtcBNR8AiMrUbtVOUGkqYjMQZ6jnSdVUIA= -github.com/nats-io/nats-server/v2 v2.11.2 h1:k5KBAuRpJW9qAF11Io2txNhR5m1KUmqVkalLAw2yLfk= -github.com/nats-io/nats-server/v2 v2.11.2/go.mod h1:6Z6Fd+JgckqzKig7DYwhgrE7bJ6fypPHnGPND+DqgMY= -github.com/nats-io/nkeys v0.2.0/go.mod h1:XdZpAbhgyyODYqjTawOnIOI7VlbKSarI9Gfy1tqEu/s= -github.com/nats-io/nkeys v0.4.11 h1:q44qGV008kYd9W1b1nEBkNzvnWxtRSQ7A8BoqRrcfa0= -github.com/nats-io/nkeys v0.4.11/go.mod h1:szDimtgmfOi9n25JpfIdGw12tZFYXqhGxjhVxsatHVE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= +github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/nats-io/jwt/v2 v2.8.1 h1:V0xpGuD/N8Mi+fQNDynXohVvp7ZztevW5io8CUWlPmU= +github.com/nats-io/jwt/v2 v2.8.1/go.mod h1:nWnOEEiVMiKHQpnAy4eXlizVEtSfzacZ1Q43LIRavZg= +github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= +github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= -golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= -golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0= -golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +github.com/synadia-io/orbit.go/ntf-client v0.0.3 h1:FoFjSd+idhy10BqDadGpUk4OcpBu/7V/Y8sHWhbSjdc= +github.com/synadia-io/orbit.go/ntf-client v0.0.3/go.mod h1:P745h+KxJPtoHF6csj2PQUB+uf72XR49o2krTaTQ8Ls= +golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= +golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= diff --git a/vendor/github.com/nats-io/nats.go/js.go b/vendor/github.com/nats-io/nats.go/js.go index 6dafb8c45b..c3c1a5f6a8 100644 --- a/vendor/github.com/nats-io/nats.go/js.go +++ b/vendor/github.com/nats-io/nats.go/js.go @@ -296,8 +296,7 @@ type jsOpts struct { } const ( - defaultRequestWait = 5 * time.Second - defaultAccountCheck = 20 * time.Second + defaultRequestWait = 5 * time.Second ) // JetStream returns a JetStreamContext for messaging and stream management. @@ -446,15 +445,23 @@ func StreamListFilter(subject string) JSOpt { } func (js *js) apiSubj(subj string) string { - if js.opts.pre == _EMPTY_ { + return apiSubjWithPrefix(js.opts.pre, subj) +} + +func apiSubjWithPrefix(pre, subj string) string { + if pre == _EMPTY_ { return subj } var b strings.Builder - b.WriteString(js.opts.pre) + b.WriteString(pre) b.WriteString(subj) return b.String() } +func (o *jsOpts) apiSubj(subj string) string { + return apiSubjWithPrefix(o.pre, subj) +} + // PubOpt configures options for publishing JetStream messages. type PubOpt interface { configurePublish(opts *pubOpts) error @@ -1132,7 +1139,7 @@ func (js *js) PublishMsgAsync(m *Msg, opts ...PubOpt) (PubAckFuture, error) { if err != nil { return nil, err } - if err := js.nc.publish(m.Subject, reply, hdr, m.Data); err != nil { + if err := js.nc.publish(m.Subject, reply, false, hdr, m.Data); err != nil { js.clearPAF(id) return nil, err } @@ -1948,7 +1955,6 @@ func (js *js) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync, } else if consName == "" { consName = getHash(nuid.Next()) } - var info *ConsumerInfo if o.ctx != nil { info, err = js.upsertConsumer(stream, consName, ccreq.Config, Context(o.ctx)) } else { @@ -1960,7 +1966,11 @@ func (js *js) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync, cleanUpSub() return nil, err } - if consumer == _EMPTY_ || + lookupConsumer := consumer + if lookupConsumer == _EMPTY_ { + lookupConsumer = consName + } + if lookupConsumer == _EMPTY_ || (apiErr.ErrorCode != JSErrCodeConsumerAlreadyExists && apiErr.ErrorCode != JSErrCodeConsumerNameExists) { cleanUpSub() if errors.Is(apiErr, ErrStreamNotFound) { @@ -1973,7 +1983,7 @@ func (js *js) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync, cleanUpSub() } - info, err = js.ConsumerInfo(stream, consumer) + info, err = js.ConsumerInfo(stream, lookupConsumer) if err != nil { return nil, err } @@ -2030,10 +2040,7 @@ func (js *js) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync, // If maxap is greater than the default sub's pending limit, use that. if maxap > DefaultSubPendingMsgsLimit { // For bytes limit, use the min of maxp*1MB or DefaultSubPendingBytesLimit - bl := maxap * 1024 * 1024 - if bl < DefaultSubPendingBytesLimit { - bl = DefaultSubPendingBytesLimit - } + bl := max(maxap*1024*1024, DefaultSubPendingBytesLimit) if err := sub.SetPendingLimits(maxap, bl); err != nil { return nil, err } @@ -2263,8 +2270,13 @@ func (sub *Subscription) resetOrderedConsumer(sseq uint64) { jsi.cmeta = _EMPTY_ jsi.fcr, jsi.fcd = _EMPTY_, 0 jsi.deliver = newDeliver - // Reset consumer request for starting policy. - cfg := jsi.ccreq.Config + // Reset consumer request for starting policy. Take a value copy of the + // ConsumerConfig so concurrent activityCheck-spawned resets don't race + // on a shared *ConsumerConfig — a later goroutine's writes here would + // otherwise overlap an earlier goroutine's json.Marshal in + // upsertConsumer below (called outside sub.mu). + cfgCopy := *jsi.ccreq.Config + cfg := &cfgCopy cfg.DeliverSubject = newDeliver cfg.DeliverPolicy = DeliverByStartSequencePolicy cfg.OptStartSeq = sseq @@ -2835,8 +2847,15 @@ func ConsumerFilterSubjects(subjects ...string) SubOpt { func (sub *Subscription) ConsumerInfo() (*ConsumerInfo, error) { sub.mu.Lock() // TODO(dlc) - Better way to mark especially if we attach. - if sub.jsi == nil || sub.jsi.consumer == _EMPTY_ { + if sub.jsi == nil { + sub.mu.Unlock() + return nil, ErrTypeSubscription + } else if sub.jsi.consumer == _EMPTY_ { + ordered := sub.jsi.ordered sub.mu.Unlock() + if ordered { + return nil, ErrConsumerInfoOnOrderedReset + } return nil, ErrTypeSubscription } @@ -3108,10 +3127,7 @@ func (sub *Subscription) Fetch(batch int, opts ...PullOpt) ([]*Msg, error) { } // Make our request expiration a bit shorter than the current timeout. - expiresDiff := time.Duration(float64(ttl) * 0.1) - if expiresDiff > 5*time.Second { - expiresDiff = 5 * time.Second - } + expiresDiff := min(time.Duration(float64(ttl)*0.1), 5*time.Second) expires := ttl - expiresDiff nr.Batch = batch - len(msgs) @@ -3392,10 +3408,7 @@ func (sub *Subscription) FetchBatch(batch int, opts ...PullOpt) (MessageBatch, e ttl = time.Until(deadline) // Make our request expiration a bit shorter than the current timeout. - expiresDiff := time.Duration(float64(ttl) * 0.1) - if expiresDiff > 5*time.Second { - expiresDiff = 5 * time.Second - } + expiresDiff := min(time.Duration(float64(ttl)*0.1), 5*time.Second) expires := ttl - expiresDiff connStatusChanged := nc.StatusChanged() @@ -3510,12 +3523,12 @@ func (o *pullOpts) checkCtxErr(err error) error { func (js *js) getConsumerInfo(stream, consumer string) (*ConsumerInfo, error) { ctx, cancel := context.WithTimeout(context.Background(), js.opts.wait) defer cancel() - return js.getConsumerInfoContext(ctx, stream, consumer) + return js.getConsumerInfoContext(ctx, stream, consumer, js.opts) } -func (js *js) getConsumerInfoContext(ctx context.Context, stream, consumer string) (*ConsumerInfo, error) { +func (js *js) getConsumerInfoContext(ctx context.Context, stream, consumer string, o *jsOpts) (*ConsumerInfo, error) { ccInfoSubj := fmt.Sprintf(apiConsumerInfoT, stream, consumer) - resp, err := js.apiRequestWithContext(ctx, js.apiSubj(ccInfoSubj), nil) + resp, err := js.apiRequestWithContext(ctx, o.apiSubj(ccInfoSubj), nil) if err != nil { if errors.Is(err, ErrNoResponders) { err = ErrJetStreamNotEnabled @@ -3556,7 +3569,7 @@ func (js *js) apiRequestWithContext(ctx context.Context, subj string, data []byt } if js.opts.shouldTrace { ctrace := js.opts.ctrace - if ctrace.RequestSent != nil { + if ctrace.ResponseReceived != nil { ctrace.ResponseReceived(subj, resp.Data, resp.Header) } } @@ -3746,6 +3759,13 @@ const ( // AckExplicitPolicy requires ack or nack for all messages. AckExplicitPolicy + // AckFlowControlPolicy functions like AckAllPolicy, but acks based on + // responses to flow control. Used by durable stream sourcing and + // mirroring against an existing durable push consumer. + // + // This feature requires nats-server v2.14.0 or later. + AckFlowControlPolicy + // For configuration mismatch check ackPolicyNotSet = 99 ) @@ -3762,6 +3782,8 @@ func (p *AckPolicy) UnmarshalJSON(data []byte) error { *p = AckAllPolicy case jsonString("explicit"): *p = AckExplicitPolicy + case jsonString("flow_control"): + *p = AckFlowControlPolicy default: return fmt.Errorf("nats: can not unmarshal %q", data) } @@ -3777,6 +3799,8 @@ func (p AckPolicy) MarshalJSON() ([]byte, error) { return json.Marshal("all") case AckExplicitPolicy: return json.Marshal("explicit") + case AckFlowControlPolicy: + return json.Marshal("flow_control") default: return nil, fmt.Errorf("nats: unknown acknowledgement policy %v", p) } @@ -3790,6 +3814,8 @@ func (p AckPolicy) String() string { return "AckAll" case AckExplicitPolicy: return "AckExplicit" + case AckFlowControlPolicy: + return "AckFlowControl" case ackPolicyNotSet: return "Not Initialized" default: diff --git a/vendor/github.com/nats-io/nats.go/jserrors.go b/vendor/github.com/nats-io/nats.go/jserrors.go index 6d72bbcc50..7b07b665db 100644 --- a/vendor/github.com/nats-io/nats.go/jserrors.go +++ b/vendor/github.com/nats-io/nats.go/jserrors.go @@ -60,6 +60,11 @@ var ( // ErrConsumerNotFound is an error returned when consumer with given name does not exist. ErrConsumerNotFound JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeConsumerNotFound, Description: "consumer not found", Code: 404}} + // ErrConsumerCreationResponseEmpty is an error returned when the response from the server + // when creating a consumer is empty. This means that the state of the consumer is unknown and + // the consumer may not have been created successfully. + ErrConsumerCreationResponseEmpty JetStreamError = &jsError{message: "consumer creation response is empty"} + // ErrMsgNotFound is returned when message with provided sequence number does npt exist. ErrMsgNotFound JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeMessageNotFound, Description: "message not found", Code: 404}} @@ -145,6 +150,9 @@ var ( // ErrConsumerLeadershipChanged is returned when pending requests are no longer valid after leadership has changed ErrConsumerLeadershipChanged JetStreamError = &jsError{message: "Leadership Changed"} + // ErrConsumerInfoOnOrderedReset is returned when attempting to fetch consumer info for an ordered consumer that is currently being recreated. + ErrConsumerInfoOnOrderedReset JetStreamError = &jsError{message: "cannot fetch consumer info; ordered consumer is being reset"} + // ErrNoHeartbeat is returned when no heartbeat is received from server when sending requests with pull consumer. ErrNoHeartbeat JetStreamError = &jsError{message: "no heartbeat received"} @@ -195,6 +203,11 @@ const ( JSStreamInvalidConfig ErrorCode = 10052 JSErrCodeStreamWrongLastSequence ErrorCode = 10071 + + // JSErrCodeStreamWrongLastSequenceConstant is returned instead of + // JSErrCodeStreamWrongLastSequence for CAS conflicts on replicated (R>1) + // streams. The two are equivalent "wrong last sequence" responses. + JSErrCodeStreamWrongLastSequenceConstant ErrorCode = 10164 ) // APIError is included in all API responses if there was an error. diff --git a/vendor/github.com/nats-io/nats.go/jsm.go b/vendor/github.com/nats-io/nats.go/jsm.go index 18ee255f24..a135f6bc3b 100644 --- a/vendor/github.com/nats-io/nats.go/jsm.go +++ b/vendor/github.com/nats-io/nats.go/jsm.go @@ -367,8 +367,10 @@ type Tier struct { // APIStats reports on API calls to JetStream for this account. type APIStats struct { - Total uint64 `json:"total"` - Errors uint64 `json:"errors"` + Level int `json:"level"` + Total uint64 `json:"total"` + Errors uint64 `json:"errors"` + Inflight uint64 `json:"inflight,omitempty"` } // AccountLimits includes the JetStream limits of the current account. @@ -404,7 +406,7 @@ func (js *js) AccountInfo(opts ...JSOpt) (*AccountInfo, error) { defer cancel() } - resp, err := js.apiRequestWithContext(o.ctx, js.apiSubj(apiAccountInfo), nil) + resp, err := js.apiRequestWithContext(o.ctx, o.apiSubj(apiAccountInfo), nil) if err != nil { // todo maybe nats server should never have no responder on this subject and always respond if they know there is no js to be had if errors.Is(err, ErrNoResponders) { @@ -531,7 +533,7 @@ func (js *js) upsertConsumer(stream, consumerName string, cfg *ConsumerConfig, o } } - resp, err := js.apiRequestWithContext(o.ctx, js.apiSubj(ccSubj), req) + resp, err := js.apiRequestWithContext(o.ctx, o.apiSubj(ccSubj), req) if err != nil { if errors.Is(err, ErrNoResponders) { err = ErrJetStreamNotEnabled @@ -553,6 +555,10 @@ func (js *js) upsertConsumer(stream, consumerName string, cfg *ConsumerConfig, o return nil, info.Error } + if info.Error == nil && info.ConsumerInfo == nil { + return nil, ErrConsumerCreationResponseEmpty + } + // check whether multiple filter subjects (if used) are reflected in the returned ConsumerInfo if len(cfg.FilterSubjects) != 0 && len(info.Config.FilterSubjects) == 0 { return nil, ErrConsumerMultipleFilterSubjectsNotSupported @@ -605,7 +611,7 @@ func (js *js) DeleteConsumer(stream, consumer string, opts ...JSOpt) error { defer cancel() } - dcSubj := js.apiSubj(fmt.Sprintf(apiConsumerDeleteT, stream, consumer)) + dcSubj := o.apiSubj(fmt.Sprintf(apiConsumerDeleteT, stream, consumer)) r, err := js.apiRequestWithContext(o.ctx, dcSubj, nil) if err != nil { return err @@ -639,7 +645,7 @@ func (js *js) ConsumerInfo(stream, consumer string, opts ...JSOpt) (*ConsumerInf if cancel != nil { defer cancel() } - return js.getConsumerInfoContext(o.ctx, stream, consumer) + return js.getConsumerInfoContext(o.ctx, stream, consumer, o) } // consumerLister fetches pages of ConsumerInfo objects. This object is not @@ -914,7 +920,7 @@ func (js *js) AddStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error) { return nil, err } - csSubj := js.apiSubj(fmt.Sprintf(apiStreamCreateT, cfg.Name)) + csSubj := o.apiSubj(fmt.Sprintf(apiStreamCreateT, cfg.Name)) r, err := js.apiRequestWithContext(o.ctx, csSubj, req) if err != nil { return nil, err @@ -995,7 +1001,7 @@ func (js *js) StreamInfo(stream string, opts ...JSOpt) (*StreamInfo, error) { } } - siSubj := js.apiSubj(fmt.Sprintf(apiStreamInfoT, stream)) + siSubj := o.apiSubj(fmt.Sprintf(apiStreamInfoT, stream)) r, err := js.apiRequestWithContext(o.ctx, siSubj, req) if err != nil { @@ -1089,9 +1095,13 @@ type StreamState struct { // ClusterInfo shows information about the underlying set of servers // that make up the stream or consumer. type ClusterInfo struct { - Name string `json:"name,omitempty"` - Leader string `json:"leader,omitempty"` - Replicas []*PeerInfo `json:"replicas,omitempty"` + Name string `json:"name,omitempty"` + RaftGroup string `json:"raft_group,omitempty"` + Leader string `json:"leader,omitempty"` + LeaderSince *time.Time `json:"leader_since,omitempty"` + SystemAcc bool `json:"system_account,omitempty"` + TrafficAcc string `json:"traffic_account,omitempty"` + Replicas []*PeerInfo `json:"replicas,omitempty"` } // PeerInfo shows information about all the peers in the cluster that @@ -1125,7 +1135,7 @@ func (js *js) UpdateStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error return nil, err } - usSubj := js.apiSubj(fmt.Sprintf(apiStreamUpdateT, cfg.Name)) + usSubj := o.apiSubj(fmt.Sprintf(apiStreamUpdateT, cfg.Name)) r, err := js.apiRequestWithContext(o.ctx, usSubj, req) if err != nil { return nil, err @@ -1179,7 +1189,7 @@ func (js *js) DeleteStream(name string, opts ...JSOpt) error { defer cancel() } - dsSubj := js.apiSubj(fmt.Sprintf(apiStreamDeleteT, name)) + dsSubj := o.apiSubj(fmt.Sprintf(apiStreamDeleteT, name)) r, err := js.apiRequestWithContext(o.ctx, dsSubj, nil) if err != nil { return err @@ -1255,7 +1265,7 @@ func (js *js) getMsg(name string, mreq *apiMsgGetRequest, opts ...JSOpt) (*RawSt var apiSubj string if o.directGet && mreq.LastFor != _EMPTY_ { apiSubj = apiDirectMsgGetLastBySubjectT - dsSubj := js.apiSubj(fmt.Sprintf(apiSubj, name, mreq.LastFor)) + dsSubj := o.apiSubj(fmt.Sprintf(apiSubj, name, mreq.LastFor)) r, err := js.apiRequestWithContext(o.ctx, dsSubj, nil) if err != nil { return nil, err @@ -1275,7 +1285,7 @@ func (js *js) getMsg(name string, mreq *apiMsgGetRequest, opts ...JSOpt) (*RawSt return nil, err } - dsSubj := js.apiSubj(fmt.Sprintf(apiSubj, name)) + dsSubj := o.apiSubj(fmt.Sprintf(apiSubj, name)) r, err := js.apiRequestWithContext(o.ctx, dsSubj, req) if err != nil { return nil, err @@ -1406,7 +1416,7 @@ func (js *js) DeleteMsg(name string, seq uint64, opts ...JSOpt) error { defer cancel() } - return js.deleteMsg(o.ctx, name, &msgDeleteRequest{Seq: seq, NoErase: true}) + return js.deleteMsg(o, name, &msgDeleteRequest{Seq: seq, NoErase: true}) } // SecureDeleteMsg deletes a message from a stream. The deleted message is overwritten with random data @@ -1420,10 +1430,10 @@ func (js *js) SecureDeleteMsg(name string, seq uint64, opts ...JSOpt) error { defer cancel() } - return js.deleteMsg(o.ctx, name, &msgDeleteRequest{Seq: seq}) + return js.deleteMsg(o, name, &msgDeleteRequest{Seq: seq}) } -func (js *js) deleteMsg(ctx context.Context, stream string, req *msgDeleteRequest) error { +func (js *js) deleteMsg(o *jsOpts, stream string, req *msgDeleteRequest) error { if err := checkStreamName(stream); err != nil { return err } @@ -1432,8 +1442,8 @@ func (js *js) deleteMsg(ctx context.Context, stream string, req *msgDeleteReques return err } - dsSubj := js.apiSubj(fmt.Sprintf(apiMsgDeleteT, stream)) - r, err := js.apiRequestWithContext(ctx, dsSubj, reqJSON) + dsSubj := o.apiSubj(fmt.Sprintf(apiMsgDeleteT, stream)) + r, err := js.apiRequestWithContext(o.ctx, dsSubj, reqJSON) if err != nil { return err } @@ -1495,7 +1505,7 @@ func (js *js) purgeStream(stream string, req *StreamPurgeRequest, opts ...JSOpt) } } - psSubj := js.apiSubj(fmt.Sprintf(apiStreamPurgeT, stream)) + psSubj := o.apiSubj(fmt.Sprintf(apiStreamPurgeT, stream)) r, err := js.apiRequestWithContext(o.ctx, psSubj, b) if err != nil { return err @@ -1739,7 +1749,7 @@ func (jsc *js) StreamNameBySubject(subj string, opts ...JSOpt) (string, error) { return _EMPTY_, err } - resp, err := jsc.apiRequestWithContext(o.ctx, jsc.apiSubj(apiStreams), j) + resp, err := jsc.apiRequestWithContext(o.ctx, o.apiSubj(apiStreams), j) if err != nil { if errors.Is(err, ErrNoResponders) { err = ErrJetStreamNotEnabled @@ -1778,6 +1788,11 @@ func getJSContextOpts(defs *jsOpts, opts ...JSOpt) (*jsOpts, context.CancelFunc, if o.pre == _EMPTY_ { o.pre = defs.pre } - + if o.ctx != nil { + // if context does not have a deadline, use timeout from js context + if _, hasDeadline := o.ctx.Deadline(); !hasDeadline { + o.ctx, cancel = context.WithTimeout(o.ctx, defs.wait) + } + } return &o, cancel, nil } diff --git a/vendor/github.com/nats-io/nats.go/kv.go b/vendor/github.com/nats-io/nats.go/kv.go index e1ab3c0d45..e992d8737e 100644 --- a/vendor/github.com/nats-io/nats.go/kv.go +++ b/vendor/github.com/nats-io/nats.go/kv.go @@ -19,6 +19,7 @@ import ( "fmt" "reflect" "regexp" + "slices" "strconv" "strings" "sync" @@ -54,11 +55,19 @@ type KeyValue interface { // Create will add the key/value pair iff it does not exist. Create(key string, value []byte) (revision uint64, err error) // Update will update the value iff the latest revision matches. + // If the provided revision does not match the key's current revision, + // ErrKeyRevisionMismatch is returned. // Update also resets the TTL associated with the key (if any). Update(key string, value []byte, last uint64) (revision uint64, err error) - // Delete will place a delete marker and leave all revisions. + // Delete will place a delete marker and leave all revisions. The + // LastRevision option can be specified to only perform the delete if the + // latest revision matches the provided one; if it does not, + // ErrKeyRevisionMismatch is returned. Delete(key string, opts ...DeleteOpt) error - // Purge will place a delete marker and remove all previous revisions. + // Purge will place a delete marker and remove all previous revisions. The + // LastRevision option can be specified to only perform the purge if the + // latest revision matches the provided one; if it does not, + // ErrKeyRevisionMismatch is returned. Purge(key string, opts ...DeleteOpt) error // Watch for any updates to keys that match the keys argument which could include wildcards. // Watch will send a nil entry when it has received all initial values. @@ -68,10 +77,13 @@ type KeyValue interface { // WatchFiltered will watch for any updates to keys that match the keys // argument. It can be configured with the same options as Watch. WatchFiltered(keys []string, opts ...WatchOpt) (KeyWatcher, error) - // Keys will return all keys. - // Deprecated: Use ListKeys instead to avoid memory issues. + // Keys will return all keys, filtering out any duplicates. + // For large datasets, this can be memory-heavy as all keys are loaded + // into memory. Use ListKeys for a streaming alternative. Keys(opts ...WatchOpt) ([]string, error) // ListKeys will return all keys in a channel. + // Note: On buckets with a large number of keys and frequent writes, + // duplicate keys may be reported during listing. ListKeys(opts ...WatchOpt) (KeyLister, error) // History will return all historical values for the key. History(key string, opts ...WatchOpt) ([]KeyValueEntry, error) @@ -105,6 +117,9 @@ type KeyValueStatus interface { // IsCompressed indicates if the data is compressed on disk IsCompressed() bool + + // Config returns the original configuration used to create the bucket + Config() KeyValueConfig } // KeyWatcher is what is returned when doing a watch. @@ -115,12 +130,22 @@ type KeyWatcher interface { Updates() <-chan KeyValueEntry // Stop will stop this watcher. Stop() error + // Error returns a channel that will receive any error that occurs during + // watching. In particular, this will receive an error if the watcher times + // out while expecting more initial keys. The channel is closed when the + // watch operation completes or when Stop() is called. + Error() <-chan error } // KeyLister is used to retrieve a list of key value store keys type KeyLister interface { Keys() <-chan string Stop() error + // Error returns a channel that will receive any error that occurs during + // key listing. In particular, this will receive an error if the underlying + // watcher times out while expecting more keys. The channel is closed when + // the listing operation completes or when Stop() is called. + Error() <-chan error } type WatchOpt interface { @@ -331,10 +356,26 @@ var ( ErrKeyDeleted = errors.New("nats: key was deleted") ErrHistoryToLarge = errors.New("nats: history limited to a max of 64") ErrNoKeysFound = errors.New("nats: no keys found") + ErrKeyWatcherTimeout = errors.New("nats: key watcher timed out waiting for initial keys") ) var ( + // ErrKeyExists is returned when attempting to create a key that already + // exists. + // + // Note: ErrKeyExists matches errors by code 10071, which CAS conflicts + // from Update/Delete/Purge also carry on non-replicated streams; + // replicated (R>1) streams report code 10164 instead and will not match. + // Do not use ErrKeyExists to detect revision conflicts - use + // ErrKeyRevisionMismatch. ErrKeyExists JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeStreamWrongLastSequence, Code: 400}, message: "key exists"} + + // ErrKeyRevisionMismatch is returned by Update, and by Delete/Purge when + // the LastRevision option is used, if the provided revision does not + // match the key's current revision (an optimistic-concurrency conflict). + // Replicated (R>1) streams report this as error code 10164 instead of + // 10071; both map to this error. + ErrKeyRevisionMismatch JetStreamError = &jsError{message: "key revision mismatch"} ) const ( @@ -343,7 +384,6 @@ const ( kvSubjectsTmpl = "$KV.%s.>" kvSubjectsPreTmpl = "$KV.%s." kvSubjectsPreDomainTmpl = "%s.$KV.%s." - kvNoPending = "0" ) // Regex for valid keys and buckets. @@ -560,14 +600,14 @@ func bucketValid(bucket string) bool { } func keyValid(key string) bool { - if len(key) == 0 || key[0] == '.' || key[len(key)-1] == '.' { + if len(key) == 0 || key[0] == '.' || key[len(key)-1] == '.' || strings.Contains(key, "..") { return false } return validKeyRe.MatchString(key) } func searchKeyValid(key string) bool { - if len(key) == 0 || key[0] == '.' || key[len(key)-1] == '.' { + if len(key) == 0 || key[0] == '.' || key[len(key)-1] == '.' || strings.Contains(key, "..") { return false } return validSearchKeyRe.MatchString(key) @@ -687,7 +727,7 @@ func (kv *kvs) PutString(key string, value string) (revision uint64, err error) // Create will add the key/value pair if it does not exist. func (kv *kvs) Create(key string, value []byte) (revision uint64, err error) { - v, err := kv.Update(key, value, 0) + v, err := kv.update(key, value, 0) if err == nil { return v, nil } @@ -695,21 +735,53 @@ func (kv *kvs) Create(key string, value []byte) (revision uint64, err error) { // TODO(dlc) - Since we have tombstones for DEL ops for watchers, this could be from that // so we need to double check. if e, err := kv.get(key, kvLatestRevision); errors.Is(err, ErrKeyDeleted) { - return kv.Update(key, value, e.Revision()) + return kv.update(key, value, e.Revision()) } - // Check if the expected last subject sequence is not zero which implies - // the key already exists. - if errors.Is(err, ErrKeyExists) { - jserr := ErrKeyExists.(*jsError) - return 0, fmt.Errorf("%w: %s", err, jserr.message) + // A wrong-last-sequence response means the key already exists. + if isWrongLastSeqErr(err) { + // 10071 matches ErrKeyExists via its code and keeps its original + // message; 10164 (replicated streams) must wrap ErrKeyExists explicitly. + if errors.Is(err, ErrKeyExists) { + jserr := ErrKeyExists.(*jsError) + return 0, fmt.Errorf("%w: %s", err, jserr.message) + } + return 0, fmt.Errorf("%w: %w", err, ErrKeyExists) } return 0, err } +// isWrongLastSeqErr reports whether err is a "wrong last sequence" API error. +// Replicated (R>1) streams report CAS conflicts as 10164 instead of 10071. +func isWrongLastSeqErr(err error) bool { + var apiErr *APIError + if !errors.As(err, &apiErr) { + return false + } + return apiErr.ErrorCode == JSErrCodeStreamWrongLastSequence || + apiErr.ErrorCode == JSErrCodeStreamWrongLastSequenceConstant +} + +// mapRevisionMismatch wraps a wrong-last-sequence error with +// ErrKeyRevisionMismatch so callers can detect CAS conflicts regardless of +// whether the stream reported code 10071 or 10164. +func mapRevisionMismatch(err error) error { + if err != nil && isWrongLastSeqErr(err) { + return fmt.Errorf("%w: %w", err, ErrKeyRevisionMismatch) + } + return err +} + // Update will update the value if the latest revision matches. +// If the provided revision does not match the key's current revision, +// ErrKeyRevisionMismatch is returned. func (kv *kvs) Update(key string, value []byte, revision uint64) (uint64, error) { + rev, err := kv.update(key, value, revision) + return rev, mapRevisionMismatch(err) +} + +func (kv *kvs) update(key string, value []byte, revision uint64) (uint64, error) { if !keyValid(key) { return 0, ErrInvalidKey } @@ -732,6 +804,9 @@ func (kv *kvs) Update(key string, value []byte, revision uint64) (uint64, error) } // Delete will place a delete marker and leave all revisions. +// The LastRevision option can be specified to only perform the delete if the +// latest revision matches the provided one; if it does not, +// ErrKeyRevisionMismatch is returned. func (kv *kvs) Delete(key string, opts ...DeleteOpt) error { if !keyValid(key) { return ErrInvalidKey @@ -772,10 +847,13 @@ func (kv *kvs) Delete(key string, opts ...DeleteOpt) error { } _, err := kv.js.PublishMsg(m) - return err + return mapRevisionMismatch(err) } // Purge will remove the key and all revisions. +// The LastRevision option can be specified to only perform the purge if the +// latest revision matches the provided one; if it does not, +// ErrKeyRevisionMismatch is returned. func (kv *kvs) Purge(key string, opts ...DeleteOpt) error { return kv.Delete(key, append(opts, purge())...) } @@ -854,7 +932,7 @@ func (kv *kvs) PurgeDeletes(opts ...PurgeOpt) error { return nil } -// Keys() will return all keys. +// Keys will return all keys, filtering out any duplicates. func (kv *kvs) Keys(opts ...WatchOpt) ([]string, error) { opts = append(opts, IgnoreDeletes(), MetaOnly()) watcher, err := kv.WatchAll(opts...) @@ -873,7 +951,8 @@ func (kv *kvs) Keys(opts ...WatchOpt) ([]string, error) { if len(keys) == 0 { return nil, ErrNoKeysFound } - return keys, nil + slices.Sort(keys) + return slices.Compact(keys), nil } type keyLister struct { @@ -882,6 +961,8 @@ type keyLister struct { } // ListKeys will return all keys. +// Note: On buckets with a large number of keys and frequent writes, +// duplicate keys may be reported during listing. func (kv *kvs) ListKeys(opts ...WatchOpt) (KeyLister, error) { opts = append(opts, IgnoreDeletes(), MetaOnly()) watcher, err := kv.WatchAll(opts...) @@ -911,6 +992,10 @@ func (kl *keyLister) Stop() error { return kl.watcher.Stop() } +func (kl *keyLister) Error() <-chan error { + return kl.watcher.Error() +} + // History will return all values for the key. func (kv *kvs) History(key string, opts ...WatchOpt) ([]KeyValueEntry, error) { opts = append(opts, IncludeHistory()) @@ -943,6 +1028,7 @@ type watcher struct { received uint64 ctx context.Context initDoneTimer *time.Timer + errCh chan error } // Context returns the context for the watcher if set. @@ -969,6 +1055,16 @@ func (w *watcher) Stop() error { return w.sub.Unsubscribe() } +// Error returns a channel that will receive any error that occurs during watching. +func (w *watcher) Error() <-chan error { + if w == nil { + closedCh := make(chan error) + close(closedCh) + return closedCh + } + return w.errCh +} + // WatchAll watches all keys. func (kv *kvs) WatchAll(opts ...WatchOpt) (KeyWatcher, error) { return kv.Watch(AllKeys, opts...) @@ -1006,7 +1102,11 @@ func (kv *kvs) WatchFiltered(keys []string, opts ...WatchOpt) (KeyWatcher, error } // We will block below on placing items on the chan. That is by design. - w := &watcher{updates: make(chan KeyValueEntry, 256), ctx: o.ctx} + w := &watcher{ + updates: make(chan KeyValueEntry, 256), + ctx: o.ctx, + errCh: make(chan error, 1), + } update := func(m *Msg) { tokens, err := parser.GetMetadataFields(m.Reply) @@ -1046,11 +1146,9 @@ func (kv *kvs) WatchFiltered(keys []string, opts ...WatchOpt) (KeyWatcher, error // Skip if UpdatesOnly() is set, since there will never be updates initially. if !w.initDone { w.received++ - // We set this on the first trip through.. - if w.initPending == 0 { - w.initPending = delta - } - if w.received > w.initPending || delta == 0 { + // Use the stable initPending value set at consumer creation. + // We're done if we've received all expected messages OR there are no more pending + if w.received >= w.initPending || delta == 0 { // Avoid possible race setting up timer. if w.initDoneTimer != nil { w.initDoneTimer.Stop() @@ -1098,19 +1196,26 @@ func (kv *kvs) WatchFiltered(keys []string, opts ...WatchOpt) (KeyWatcher, error // of the consumer, send the marker. // Skip if UpdatesOnly() is set, since there will never be updates initially. if !o.updatesOnly { - if sub.jsi != nil && sub.jsi.pending == 0 { - w.initDone = true - w.updates <- nil - } else { - // Set a timer to send the marker if we do not get any messages. - w.initDoneTimer = time.AfterFunc(kv.js.opts.wait, func() { - w.mu.Lock() - defer w.mu.Unlock() - if !w.initDone { - w.initDone = true - w.updates <- nil - } - }) + if sub.jsi != nil { + if sub.jsi.pending == 0 { + w.initDone = true + w.updates <- nil + } else { + w.initPending = sub.jsi.pending + // Set a timer to send the marker if we do not get any messages. + w.initDoneTimer = time.AfterFunc(kv.js.opts.wait, func() { + w.mu.Lock() + defer w.mu.Unlock() + if !w.initDone { + w.initDone = true + select { + case w.errCh <- ErrKeyWatcherTimeout: + default: + } + w.updates <- nil + } + }) + } } } else { // if UpdatesOnly was used, mark initialization as complete @@ -1124,6 +1229,7 @@ func (kv *kvs) WatchFiltered(keys []string, opts ...WatchOpt) (KeyWatcher, error w.initDoneTimer.Stop() } close(w.updates) + close(w.errCh) } sub.mu.Unlock() @@ -1173,6 +1279,24 @@ func (s *KeyValueBucketStatus) Bytes() uint64 { return s.nfo.State.Bytes } // IsCompressed indicates if the data is compressed on disk func (s *KeyValueBucketStatus) IsCompressed() bool { return s.nfo.Config.Compression != NoCompression } +func (s *KeyValueBucketStatus) Config() KeyValueConfig { + return KeyValueConfig{ + Bucket: s.bucket, + Description: s.nfo.Config.Description, + MaxValueSize: s.nfo.Config.MaxMsgSize, + History: uint8(s.nfo.Config.MaxMsgsPerSubject), + TTL: s.nfo.Config.MaxAge, + MaxBytes: s.nfo.Config.MaxBytes, + Storage: s.nfo.Config.Storage, + Replicas: s.nfo.Config.Replicas, + Placement: s.nfo.Config.Placement, + RePublish: s.nfo.Config.RePublish, + Mirror: s.nfo.Config.Mirror, + Sources: s.nfo.Config.Sources, + Compression: s.nfo.Config.Compression != NoCompression, + } +} + // Status retrieves the status and configuration of a bucket func (kv *kvs) Status() (KeyValueStatus, error) { nfo, err := kv.js.StreamInfo(kv.stream) diff --git a/vendor/github.com/nats-io/nats.go/nats.go b/vendor/github.com/nats-io/nats.go/nats.go index 48a6f2bd77..b773c52b00 100644 --- a/vendor/github.com/nats-io/nats.go/nats.go +++ b/vendor/github.com/nats-io/nats.go/nats.go @@ -1,4 +1,4 @@ -// Copyright 2012-2024 The NATS Authors +// Copyright 2012-2026 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -33,10 +33,12 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strconv" "strings" "sync" "sync/atomic" + "syscall" "time" "github.com/nats-io/nkeys" @@ -47,7 +49,7 @@ import ( // Default Constants const ( - Version = "1.43.0" + Version = "1.53.1" DefaultURL = "nats://127.0.0.1:4222" DefaultPort = 4222 DefaultMaxReconnect = 60 @@ -59,6 +61,7 @@ const ( DefaultMaxPingOut = 2 DefaultMaxChanLen = 64 * 1024 // 64k DefaultReconnectBufSize = 8 * 1024 * 1024 // 8MB + DefaultWriteBufSize = defaultBufSize RequestChanLen = 8 DefaultDrainTimeout = 30 * time.Second DefaultFlusherTimeout = time.Minute @@ -84,68 +87,76 @@ const ( // ACCOUNT_AUTHENTICATION_EXPIRED_ERR is for when nats server account authorization has expired. ACCOUNT_AUTHENTICATION_EXPIRED_ERR = "account authentication expired" - // MAX_CONNECTIONS_ERR is for when nats server denies the connection due to server max_connections limit + // MAX_CONNECTIONS_ERR is for when nats server denies the connection due to server max_connections limit. MAX_CONNECTIONS_ERR = "maximum connections exceeded" - // MAX_SUBSCRIPTIONS_ERR is for when nats server denies the connection due to server subscriptions limit + // MAX_ACCOUNT_CONNECTIONS_ERR is for when nats server denies the connection due to server max_connections limit on the account. + MAX_ACCOUNT_CONNECTIONS_ERR = `maximum account active connections exceeded` + + // MAX_SUBSCRIPTIONS_ERR is for when nats server denies the connection due to server subscriptions limit. MAX_SUBSCRIPTIONS_ERR = "maximum subscriptions exceeded" ) // Errors var ( - ErrConnectionClosed = errors.New("nats: connection closed") - ErrConnectionDraining = errors.New("nats: connection draining") - ErrDrainTimeout = errors.New("nats: draining connection timed out") - ErrConnectionReconnecting = errors.New("nats: connection reconnecting") - ErrSecureConnRequired = errors.New("nats: secure connection required") - ErrSecureConnWanted = errors.New("nats: secure connection not available") - ErrBadSubscription = errors.New("nats: invalid subscription") - ErrTypeSubscription = errors.New("nats: invalid subscription type") - ErrBadSubject = errors.New("nats: invalid subject") - ErrBadQueueName = errors.New("nats: invalid queue name") - ErrSlowConsumer = errors.New("nats: slow consumer, messages dropped") - ErrTimeout = errors.New("nats: timeout") - ErrBadTimeout = errors.New("nats: timeout invalid") - ErrAuthorization = errors.New("nats: authorization violation") - ErrAuthExpired = errors.New("nats: authentication expired") - ErrAuthRevoked = errors.New("nats: authentication revoked") - ErrPermissionViolation = errors.New("nats: permissions violation") - ErrAccountAuthExpired = errors.New("nats: account authentication expired") - ErrNoServers = errors.New("nats: no servers available for connection") - ErrJsonParse = errors.New("nats: connect message, json parse error") - ErrChanArg = errors.New("nats: argument needs to be a channel type") - ErrMaxPayload = errors.New("nats: maximum payload exceeded") - ErrMaxMessages = errors.New("nats: maximum messages delivered") - ErrSyncSubRequired = errors.New("nats: illegal call on an async subscription") - ErrMultipleTLSConfigs = errors.New("nats: multiple tls.Configs not allowed") - ErrClientCertOrRootCAsRequired = errors.New("nats: at least one of certCB or rootCAsCB must be set") - ErrNoInfoReceived = errors.New("nats: protocol exception, INFO not received") - ErrReconnectBufExceeded = errors.New("nats: outbound buffer limit exceeded") - ErrInvalidConnection = errors.New("nats: invalid connection") - ErrInvalidMsg = errors.New("nats: invalid message or message nil") - ErrInvalidArg = errors.New("nats: invalid argument") - ErrInvalidContext = errors.New("nats: invalid context") - ErrNoDeadlineContext = errors.New("nats: context requires a deadline") - ErrNoEchoNotSupported = errors.New("nats: no echo option not supported by this server") - ErrClientIDNotSupported = errors.New("nats: client ID not supported by this server") - ErrUserButNoSigCB = errors.New("nats: user callback defined without a signature handler") - ErrNkeyButNoSigCB = errors.New("nats: nkey defined without a signature handler") - ErrNoUserCB = errors.New("nats: user callback not defined") - ErrNkeyAndUser = errors.New("nats: user callback and nkey defined") - ErrNkeysNotSupported = errors.New("nats: nkeys not supported by the server") - ErrStaleConnection = errors.New("nats: " + STALE_CONNECTION) - ErrTokenAlreadySet = errors.New("nats: token and token handler both set") - ErrUserInfoAlreadySet = errors.New("nats: cannot set user info callback and user/pass") - ErrMsgNotBound = errors.New("nats: message is not bound to subscription/connection") - ErrMsgNoReply = errors.New("nats: message does not have a reply") - ErrClientIPNotSupported = errors.New("nats: client IP not supported by this server") - ErrDisconnected = errors.New("nats: server is disconnected") - ErrHeadersNotSupported = errors.New("nats: headers not supported by this server") - ErrBadHeaderMsg = errors.New("nats: message could not decode headers") - ErrNoResponders = errors.New("nats: no responders available for request") - ErrMaxConnectionsExceeded = errors.New("nats: server maximum connections exceeded") - ErrConnectionNotTLS = errors.New("nats: connection is not tls") - ErrMaxSubscriptionsExceeded = errors.New("nats: server maximum subscriptions exceeded") + ErrConnectionClosed = errors.New("nats: connection closed") + ErrConnectionDraining = errors.New("nats: connection draining") + ErrDrainTimeout = errors.New("nats: draining connection timed out") + ErrConnectionReconnecting = errors.New("nats: connection reconnecting") + ErrSecureConnRequired = errors.New("nats: secure connection required") + ErrSecureConnWanted = errors.New("nats: secure connection not available") + ErrBadSubscription = errors.New("nats: invalid subscription") + ErrTypeSubscription = errors.New("nats: invalid subscription type") + ErrBadSubject = errors.New("nats: invalid subject") + ErrBadQueueName = errors.New("nats: invalid queue name") + ErrSlowConsumer = errors.New("nats: slow consumer, messages dropped") + ErrTimeout = errors.New("nats: timeout") + ErrBadTimeout = errors.New("nats: timeout invalid") + ErrAuthorization = errors.New("nats: authorization violation") + ErrAuthExpired = errors.New("nats: authentication expired") + ErrAuthRevoked = errors.New("nats: authentication revoked") + ErrPermissionViolation = errors.New("nats: permissions violation") + ErrAccountAuthExpired = errors.New("nats: account authentication expired") + ErrNoServers = errors.New("nats: no servers available for connection") + ErrJsonParse = errors.New("nats: connect message, json parse error") + ErrChanArg = errors.New("nats: argument needs to be a channel type") + ErrMaxPayload = errors.New("nats: maximum payload exceeded") + ErrMaxMessages = errors.New("nats: maximum messages delivered") + ErrSyncSubRequired = errors.New("nats: illegal call on an async subscription") + ErrMultipleTLSConfigs = errors.New("nats: multiple tls.Configs not allowed") + ErrClientCertOrRootCAsRequired = errors.New("nats: at least one of certCB or rootCAsCB must be set") + ErrNoInfoReceived = errors.New("nats: protocol exception, INFO not received") + ErrReconnectBufExceeded = errors.New("nats: outbound buffer limit exceeded") + ErrInvalidConnection = errors.New("nats: invalid connection") + ErrInvalidMsg = errors.New("nats: invalid message or message nil") + ErrInvalidArg = errors.New("nats: invalid argument") + ErrInvalidContext = errors.New("nats: invalid context") + ErrNoDeadlineContext = errors.New("nats: context requires a deadline") + ErrNoEchoNotSupported = errors.New("nats: no echo option not supported by this server") + ErrClientIDNotSupported = errors.New("nats: client ID not supported by this server") + ErrUserButNoSigCB = errors.New("nats: user callback defined without a signature handler") + ErrNkeyButNoSigCB = errors.New("nats: nkey defined without a signature handler") + ErrNoUserCB = errors.New("nats: user callback not defined") + ErrNkeyAndUser = errors.New("nats: user callback and nkey defined") + ErrNkeysNotSupported = errors.New("nats: nkeys not supported by the server") + ErrStaleConnection = errors.New("nats: " + STALE_CONNECTION) + ErrTokenAlreadySet = errors.New("nats: token and token handler both set") + ErrUserInfoAlreadySet = errors.New("nats: cannot set user info callback and user/pass") + ErrMsgNotBound = errors.New("nats: message is not bound to subscription/connection") + ErrMsgNoReply = errors.New("nats: message does not have a reply") + ErrClientIPNotSupported = errors.New("nats: client IP not supported by this server") + ErrDisconnected = errors.New("nats: server is disconnected") + ErrHeadersNotSupported = errors.New("nats: headers not supported by this server") + ErrBadHeaderMsg = errors.New("nats: message could not decode headers") + ErrNoResponders = errors.New("nats: no responders available for request") + ErrMaxConnectionsExceeded = errors.New("nats: server maximum connections exceeded") + ErrMaxAccountConnectionsExceeded = errors.New("nats: maximum account active connections exceeded") + ErrConnectionNotTLS = errors.New("nats: connection is not tls") + ErrTLS = errors.New("nats: tls error") + ErrMaxSubscriptionsExceeded = errors.New("nats: server maximum subscriptions exceeded") + ErrWebSocketHeadersAlreadySet = errors.New("nats: websocket connection headers already set") + ErrServerNotInPool = errors.New("nats: selected server is not in the pool") + ErrMixingWebsocketSchemes = errors.New("nats: mixing of websocket and non websocket URLs is not allowed") ) // GetDefaultOptions returns default configuration options for the client. @@ -236,7 +247,7 @@ type SignatureHandler func([]byte) ([]byte, error) // AuthTokenHandler is used to generate a new token. type AuthTokenHandler func() string -// UserInfoCB is used to pass the username and password when establishing connection. +// UserInfoCB is used to pass the username and password when establishing a connection. type UserInfoCB func() (string, string) // ReconnectDelayHandler is used to get from the user the desired @@ -245,6 +256,28 @@ type UserInfoCB func() (string, string) // whole list of URLs and failed to reconnect. type ReconnectDelayHandler func(attempts int) time.Duration +// WebSocketHeadersHandler is an optional callback handler for generating token used for WebSocket connections. +type WebSocketHeadersHandler func() (http.Header, error) + +// ReconnectToServerHandler is used to determine the server to reconnect to during +// the reconnection process. The handler receives a snapshot of available servers +// in the pool and should return a pointer to one of the servers from the provided +// slice and a delay before attempting the connection. +// +// Return values: +// - *Server: The server to connect to. Must be a pointer to an element from the +// provided servers slice. If the returned server is not in the pool, the library +// will fire ReconnectErrCB with ErrServerNotInPool and fall back to default +// server selection. +// - time.Duration: The delay before attempting the connection. If zero, the +// connection attempt is made immediately. If non-zero, the library sleeps +// for exactly that duration before attempting. +// +// MaxReconnect limits are enforced automatically: servers exceeding the configured +// MaxReconnect attempts are removed from the pool before the handler is called. +// To disable this limit, set MaxReconnect to a negative value. +type ReconnectToServerHandler func([]Server, ServerInfo) (*Server, time.Duration) + // asyncCB is used to preserve order for async callbacks. type asyncCB struct { f func() @@ -341,7 +374,7 @@ type Options struct { // Defaults to 60. MaxReconnect int - // ReconnectWait sets the time to backoff after attempting a reconnect + // ReconnectWait sets the time to back off after attempting a reconnect // to a server that we were already connected to previously. // Defaults to 2s. ReconnectWait time.Duration @@ -368,7 +401,7 @@ type Options struct { // Defaults to 2s. Timeout time.Duration - // DrainTimeout sets the timeout for a Drain Operation to complete. + // DrainTimeout sets the timeout for a drain operation to complete. // Defaults to 30s. DrainTimeout time.Duration @@ -377,6 +410,34 @@ type Options struct { // Defaults to 1m. FlusherTimeout time.Duration + // ReconnectOnFlusherError, when set to true, causes the client to + // trigger a reconnect if the background flusher fails to write to the + // underlying connection for any reason (timeout, broken pipe, + // connection reset, EOF etc.). + // + // This is an advanced option. Most applications do not need to enable + // it: the server-side stale connection detection (via PingInterval / + // MaxPingsOut) and the read loop's own error handling will eventually + // notice a dead connection and the client will reconnect. Enable this + // only if you need faster recovery from a stalled or broken TCP write + // — for example, in latency-sensitive setups where waiting for a ping + // timeout is unacceptable. + // + // Messages buffered at the time of the error are lost, as they are + // with any flusher write error. The purpose of this option is to + // limit the blast radius by preventing further messages from being + // buffered into a potentially corrupted connection, not to recover + // the in-flight data. + // + // When triggered, the standard DisconnectErrHandler and + // ReconnectHandler callbacks are invoked as with any other reconnect. + // The first reconnect attempt bypasses the configured ReconnectWait + // so that recovery is as fast as possible; if that attempt fails, + // subsequent attempts obey the normal backoff. + // + // Defaults to false. + ReconnectOnFlusherError bool + // PingInterval is the period at which the client will be sending ping // commands to the server, disabled if 0 or negative. // Defaults to 2m. @@ -422,18 +483,25 @@ type Options struct { AsyncErrorCB ErrHandler // ReconnectErrCB sets the callback that is invoked whenever a - // reconnect attempt failed + // reconnect attempt fails. ReconnectErrCB ConnErrHandler + // ReconnectToServerCB is called before reconnection attempt. + // It is used to determine the server to reconnect to out of + // the list of available servers. + // If a reconnect attempt is not successful, this callback will + // be called again before the next attempt. + ReconnectToServerCB ReconnectToServerHandler + // ReconnectBufSize is the size of the backing bufio during reconnect. // Once this has been exhausted publish operations will return an error. // Defaults to 8388608 bytes (8MB). ReconnectBufSize int // SubChanLen is the size of the buffered channel used between the socket - // Go routine and the message delivery for SyncSubscriptions. + // goroutine and the message delivery for SyncSubscriptions. // NOTE: This does not affect AsyncSubscriptions which are - // dictated by PendingLimits() + // dictated by PendingLimits(). // Defaults to 65536. SubChanLen int @@ -461,7 +529,8 @@ type Options struct { // Token sets the token to be used when connecting to a server. Token string - // TokenHandler designates the function used to generate the token to be used when connecting to a server. + // TokenHandler designates the function used to generate the token + // used when connecting to a server. TokenHandler AuthTokenHandler // Dialer allows a custom net.Dialer when forming connections. @@ -519,6 +588,29 @@ type Options struct { // from SubscribeSync if the server returns a permissions error for a subscription. // Defaults to false. PermissionErrOnSubscribe bool + + // WebSocketConnectionHeaders is an optional http request headers to be sent with the WebSocket request. + WebSocketConnectionHeaders http.Header + + // WebSocketConnectionHeadersHandler is an optional callback handler for generating token used for WebSocket connections. + WebSocketConnectionHeadersHandler WebSocketHeadersHandler + + // SkipSubjectValidation will disable publish subject validation. + // NOTE: This is not recommended in general, as the performance gain is minimal + // and may lead to breaking protocol. + SkipSubjectValidation bool + + // IgnoreDiscoveredServers will disable adding advertised server URLs + // from INFO messages to the server pool. + IgnoreDiscoveredServers bool + + // WriteBufferSize is an advanced option that sets the flush threshold + // of the write buffer used to batch outgoing data before writing to + // the underlying connection. In most cases, the default value should + // not be changed. A smaller buffer reduces the amount of data that + // can be lost on blocked writes but may significantly reduce throughput. + // Defaults to 32768 bytes (32KB). + WriteBufferSize int } const ( @@ -557,14 +649,14 @@ type Conn struct { // Modifying the configuration of a running Conn is a race. Opts Options wg sync.WaitGroup - srvPool []*srv - current *srv + srvPool []*Server + current *Server urls map[string]struct{} // Keep track of all known URLs (used by processInfo) conn net.Conn bw *natsWriter br *natsReader fch chan struct{} - info serverInfo + info ServerInfo ssid int64 subsMu sync.RWMutex subs map[int64]*Subscription @@ -761,23 +853,144 @@ func (m *Msg) headerBytes() ([]byte, error) { return hdr, nil } + // Validate the keys and calculate an upper bound for the total encoded + // size. + // + // The size calculation may not be exact if any values contain + // leading/trailing whitespace (as those will be trimmed later), but a + // slight over-estimation here is more preferable than an under-estimation + // (which could lead to unnecessary memory allocations). + // + // We don't perform any special validation on header values because we + // consider all strings to be valid values (including Unicode strings, + // special characters, etc.). + hdrSize := len(hdrLine) + len(crlf) + for k, vs := range m.Header { + if !isHeaderKeyValid(k) { + return nil, ErrBadHeaderMsg + } + for _, v := range vs { + hdrSize += len(k) + len(v) + 4 // 4 is for the colon, space, CR, and LF + } + } + + // NOTE: bytes.Buffer.WriteString() returns an error because bytes.Buffer + // is intended to be a valid implementation of the io.StringWriter interface. + // This implementation cannot actually fail in practice, so it is safe to + // ignore write errors here. var b bytes.Buffer - _, err := b.WriteString(hdrLine) - if err != nil { - return nil, ErrBadHeaderMsg + b.Grow(hdrSize) + _, _ = b.WriteString(hdrLine) + for k, vs := range m.Header { + for _, v := range vs { + _, _ = b.WriteString(k) + _, _ = b.WriteString(": ") + writeHeaderValue(&b, v) + _, _ = b.WriteString(crlf) + } } + _, _ = b.WriteString(crlf) - err = http.Header(m.Header).Write(&b) - if err != nil { - return nil, ErrBadHeaderMsg + return b.Bytes(), nil +} + +// asciiSet is a 256-byte lookup table for fast ASCII character membership testing. +// This implementation mirrors the one Go uses internally for many string operations, +// including strings.Contains(). +// +// References: +// - https://github.com/golang/go/blob/master/src/strings/strings.go +type asciiSet [256]bool + +func (as *asciiSet) MatchesString(s string) bool { + + // Implementation note: Our high level strategy is to compare each byte in + // 's' with the corresponding entry in 'as'. If the entry is 'true', the + // character is valid, so we can move forward with the next byte in 's'. If + // the entry in 'as' is 'false', the character is invalid, so we can bail + // out. + // + // Benchmarking shows there to be some benefit to manually unrolling the + // loop (up to ~35% faster in some cases), so that's what we've done here. + + i := 0 + + // Process the string in batches of 8 bytes + for ; i <= len(s)-8; i += 8 { + if !as[s[i]] { + return false + } + if !as[s[i+1]] { + return false + } + if !as[s[i+2]] { + return false + } + if !as[s[i+3]] { + return false + } + if !as[s[i+4]] { + return false + } + if !as[s[i+5]] { + return false + } + if !as[s[i+6]] { + return false + } + if !as[s[i+7]] { + return false + } } - _, err = b.WriteString(crlf) - if err != nil { - return nil, ErrBadHeaderMsg + // Handle any remaining bytes at the end of the string + for ; i < len(s); i++ { + if !as[s[i]] { + return false + } } + return true +} - return b.Bytes(), nil +// The asciiSet that represents valid header keys can be precalculated and +// cached since it will never change during the lifetime of the application. +var validHeaderKeyChars = makeValidHeaderKeyAsciiSet() + +func makeValidHeaderKeyAsciiSet() asciiSet { + + // ADR-4 specifies that header keys must be printable ASCII characters + // (e.g. those in the range [33, 126]), except for colons. This + // implementation is very slightly stricter, as it disallows several + // additional special characters. + const forbiddenChars = "\"()/,:;<=>?@[\\]{}" + + var as asciiSet + for i := rune(33); i <= rune(126); i++ { + if !strings.ContainsRune(forbiddenChars, i) { + as[i] = true + } + } + return as +} + +func isHeaderKeyValid(k string) bool { + return len(k) > 0 && validHeaderKeyChars.MatchesString(k) +} + +var headerValueNewlineReplacer = strings.NewReplacer("\r", " ", "\n", " ") + +func writeHeaderValue(buffer *bytes.Buffer, value string) { + + // ADR-4 specifies that header values must be ASCII characters (except for + // '\r' or '\n'), however the Go implementation is slightly more lenient + // to maintain backwards compatibility with older versions of the library. + // We allow arbitrary UTF-8 strings to be used as values and deliberately + // sanitize '\r' and '\n' characters by replacing them with spaces. + + // NOTE: It is safe to ignore the error returned by WriteString because + // we're writing to a bytes.Buffer object, and that implementation never + // returns an error. + _, _ = headerValueNewlineReplacer.WriteString(buffer, textproto.TrimString(value)) } type barrierInfo struct { @@ -795,18 +1008,27 @@ type Statistics struct { Reconnects uint64 } -// Tracks individual backend servers. -type srv struct { - url *url.URL +// Server represents a server in the pool of servers that the client can connect to. +type Server struct { + URL *url.URL + Reconnects int didConnect bool - reconnects int lastErr error isImplicit bool tlsName string } -// The INFO block received from the server. -type serverInfo struct { +func (s Server) clone() Server { + c := s + if s.URL != nil { + u := *s.URL + c.URL = &u + } + return c +} + +// ServerInfo represents the information about the server that is sent in the INFO protocol message. +type ServerInfo struct { ID string `json:"server_id"` Name string `json:"server_name"` Proto int `json:"proto"` @@ -824,6 +1046,14 @@ type serverInfo struct { Cluster string `json:"cluster,omitempty"` ConnectURLs []string `json:"connect_urls,omitempty"` LameDuckMode bool `json:"ldm,omitempty"` + // JetStream indicates whether the server has JetStream enabled. + JetStream bool `json:"jetstream,omitempty"` + // IsSystemAccount indicates whether the connected client's account + // is the system account. + IsSystemAccount bool `json:"acc_is_sys,omitempty"` + // JSApiLevel is the JetStream API level advertised by the server. + // Requires nats-server v2.12.0 or later; older servers will report 0. + JSApiLevel int `json:"api_lvl,omitempty"` } const ( @@ -887,7 +1117,7 @@ func Name(name string) Option { } } -// InProcessServer is an Option that will try to establish a direction to a NATS server +// InProcessServer is an Option that will try to establish a connection to a NATS server // running within the process instead of dialing via TCP. func InProcessServer(server InProcessConnProvider) Option { return func(o *Options) error { @@ -1067,6 +1297,19 @@ func CustomReconnectDelay(cb ReconnectDelayHandler) Option { } } +// ReconnectToServer is an Option to set a custom server selection callback +// for reconnection attempts. The callback receives a snapshot of available +// servers and must return a server from the pool to connect to and a delay +// duration before attempting the connection. +// +// See ReconnectToServerHandler for detailed documentation and usage examples. +func ReconnectToServer(cb ReconnectToServerHandler) Option { + return func(o *Options) error { + o.ReconnectToServerCB = cb + return nil + } +} + // PingInterval is an Option to set the period for client ping commands. // Defaults to 2m. func PingInterval(t time.Duration) Option { @@ -1095,6 +1338,19 @@ func ReconnectBufSize(size int) Option { } } +// WriteBufferSize is an advanced option that sets the flush threshold +// of the write buffer used to batch outgoing data before writing to +// the underlying connection. In most cases, the default value should +// not be changed. A smaller buffer reduces the amount of data that +// can be lost on blocked writes but may significantly reduce throughput. +// Defaults to 32768 bytes (32KB). +func WriteBufferSize(size int) Option { + return func(o *Options) error { + o.WriteBufferSize = size + return nil + } +} + // Timeout is an Option to set the timeout for Dial on a connection. // Defaults to 2s. func Timeout(t time.Duration) Option { @@ -1112,6 +1368,17 @@ func FlusherTimeout(t time.Duration) Option { } } +// ReconnectOnFlusherError is an Option to automatically trigger a +// reconnect when the background flusher hits any write error. See +// [Options.ReconnectOnFlusherError] for details. This is an +// advanced option and is usually not required. +func ReconnectOnFlusherError() Option { + return func(o *Options) error { + o.ReconnectOnFlusherError = true + return nil + } +} + // DrainTimeout is an Option to set the timeout for draining a connection. // Defaults to 30s. func DrainTimeout(t time.Duration) Option { @@ -1247,6 +1514,35 @@ func UserCredentials(userOrChainedFile string, seedFiles ...string) Option { return UserJWT(userCB, sigCB) } +// UserCredentialBytes is a convenience function that takes the JWT and seed +// values as byte slices. This allows passing credentials directly from memory +// or environment variables without needing to write them to disk. +func UserCredentialBytes(userOrChainedFileBytes []byte, seedFiles ...[]byte) Option { + userCB := func() (string, error) { + return nkeys.ParseDecoratedJWT(userOrChainedFileBytes) + } + + var seedBytes []byte + if len(seedFiles) > 0 { + seedBytes = seedFiles[0] + } else { + seedBytes = userOrChainedFileBytes + } + + sigCB := func(nonce []byte) ([]byte, error) { + kp, err := nkeys.ParseDecoratedNKey(seedBytes) + if err != nil { + return nil, fmt.Errorf("unable to extract key pair from bytes: %w", err) + } + defer kp.Wipe() + + sig, _ := kp.Sign(nonce) + return sig, nil + } + + return UserJWT(userCB, sigCB) +} + // UserJWTAndSeed is a convenience function that takes the JWT and seed // values as strings. func UserJWTAndSeed(jwt string, seed string) Option { @@ -1383,8 +1679,12 @@ func Compression(enabled bool) Option { } } -// ProxyPath is an option for websocket connections that adds a path to connections url. -// This is useful when connecting to NATS behind a proxy. +// ProxyPath sets a path added to every WebSocket connection URL. This is +// useful when NATS is behind a reverse proxy that routes by path. Unlike a +// path in the connect URL, ProxyPath is also applied to server-discovered +// URLs (which are bare host:port). Use ProxyPath for clustered setups +// behind a proxy, so the client can connect to discovered servers on +// failover. When set, it overrides any path in the connection URL. func ProxyPath(path string) Option { return func(o *Options) error { o.ProxyPath = path @@ -1438,6 +1738,59 @@ func TLSHandshakeFirst() Option { } } +// WebSocketConnectionHeaders sets a fixed set of HTTP headers that will be +// sent during the WebSocket connection handshake. +// This option is mutually exclusive with WebSocketConnectionHeadersHandler; +// if a headers handler has already been configured, it returns +// ErrWebSocketHeadersAlreadySet. +func WebSocketConnectionHeaders(headers http.Header) Option { + return func(o *Options) error { + if o.WebSocketConnectionHeadersHandler != nil { + return ErrWebSocketHeadersAlreadySet + } + o.WebSocketConnectionHeaders = headers + return nil + } +} + +// WebSocketConnectionHeadersHandler registers a callback used to supply HTTP +// headers for the WebSocket connection handshake. +// This option is mutually exclusive with WebSocketConnectionHeaders; if +// non-empty static headers have already been configured, it returns +// ErrWebSocketHeadersAlreadySet. +func WebSocketConnectionHeadersHandler(cb WebSocketHeadersHandler) Option { + return func(o *Options) error { + if len(o.WebSocketConnectionHeaders) != 0 { + return ErrWebSocketHeadersAlreadySet + } + o.WebSocketConnectionHeadersHandler = cb + return nil + } +} + +// SkipSubjectValidation is an Option to skip subject validation when +// publishing messages. +// By default, subject validation is performed to ensure that subjects +// are valid according to NATS subject syntax (no spaces newlines and tabs). +// NOTE: It is not recommended to use this option as the performance gain +// is minimal and disabling subject validation can lead to breaking protocol +// rules. +func SkipSubjectValidation() Option { + return func(o *Options) error { + o.SkipSubjectValidation = true + return nil + } +} + +// IgnoreDiscoveredServers is an Option to disable adding advertised +// server URLs from INFO messages to the server pool. +func IgnoreDiscoveredServers() Option { + return func(o *Options) error { + o.IgnoreDiscoveredServers = true + return nil + } +} + // Handler processing // SetDisconnectHandler will set the disconnect event handler. @@ -1582,6 +1935,10 @@ func (o Options) Connect() (*Conn, error) { if nc.Opts.ReconnectBufSize == 0 { nc.Opts.ReconnectBufSize = DefaultReconnectBufSize } + // Default WriteBufferSize + if nc.Opts.WriteBufferSize <= 0 { + nc.Opts.WriteBufferSize = DefaultWriteBufSize + } // Ensure that Timeout is not 0 if nc.Opts.Timeout == 0 { nc.Opts.Timeout = DefaultTimeout @@ -1626,16 +1983,21 @@ func (o Options) Connect() (*Conn, error) { // Create reader/writer nc.newReaderWriter() + // Spin up the async cb dispatcher before connect so it's ready + // to handle callbacks, especially when RetryOnFailedConnect is used + // and initial connection fails. + go nc.ach.asyncCBDispatcher() + connectionEstablished, err := nc.connect() if err != nil { + nc.ach.close() return nil, err } - // Spin up the async cb dispatcher on success - go nc.ach.asyncCBDispatcher() - - if connectionEstablished && nc.Opts.ConnectedCB != nil { - nc.ach.push(func() { nc.Opts.ConnectedCB(nc) }) + if connectionEstablished { + if connectedCB := nc.Opts.ConnectedCB; connectedCB != nil { + nc.ach.push(func() { connectedCB(nc) }) + } } return nc, nil @@ -1692,7 +2054,7 @@ const ( ) // Return the currently selected server -func (nc *Conn) currentServer() (int, *srv) { +func (nc *Conn) currentServer() (int, *Server) { for i, s := range nc.srvPool { if s == nil { continue @@ -1706,7 +2068,7 @@ func (nc *Conn) currentServer() (int, *srv) { // Pop the current server and put onto the end of the list. Select head of list as long // as number of reconnect attempts under MaxReconnect. -func (nc *Conn) selectNextServer() (*srv, error) { +func (nc *Conn) selectNextServer() (*Server, error) { i, s := nc.currentServer() if i < 0 { return nil, ErrNoServers @@ -1715,7 +2077,7 @@ func (nc *Conn) selectNextServer() (*srv, error) { num := len(sp) copy(sp[i:num-1], sp[i+1:num]) maxReconnect := nc.Opts.MaxReconnect - if maxReconnect < 0 || s.reconnects < maxReconnect { + if maxReconnect < 0 || s.Reconnects < maxReconnect { nc.srvPool[num-1] = s } else { nc.srvPool = sp[0 : num-1] @@ -1751,7 +2113,7 @@ const tlsScheme = "tls" // Server Options. We will randomize the server pool unless // the NoRandomize flag is set. func (nc *Conn) setupServerPool() error { - nc.srvPool = make([]*srv, 0, srvPoolSize) + nc.srvPool = make([]*Server, 0, srvPoolSize) nc.urls = make(map[string]struct{}, srvPoolSize) // Create srv objects from each url string in nc.Opts.Servers @@ -1788,7 +2150,7 @@ func (nc *Conn) setupServerPool() error { // Check for Scheme hint to move to TLS mode. for _, srv := range nc.srvPool { - if srv.url.Scheme == tlsScheme || srv.url.Scheme == wsSchemeTLS { + if srv.URL.Scheme == tlsScheme || srv.URL.Scheme == wsSchemeTLS { // FIXME(dlc), this is for all in the pool, should be case by case. nc.Opts.Secure = true if nc.Opts.TLSConfig == nil { @@ -1819,8 +2181,10 @@ func hostIsIP(u *url.URL) bool { return net.ParseIP(u.Hostname()) != nil } -// addURLToPool adds an entry to the server pool -func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error { +// parseServerURL parses a server URL string into a Server struct. +// It handles scheme defaults and port defaults. Does not validate websocket consistency. +// Returns the parsed Server and whether it's a websocket URL. +func (nc *Conn) parseServerURL(sURL string, implicit, saveTLSName bool) (*Server, error) { if !strings.Contains(sURL, "://") { sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL) } @@ -1831,7 +2195,7 @@ func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error { for i := 0; i < 2; i++ { u, err = url.Parse(sURL) if err != nil { - return err + return nil, err } if u.Port() != "" { break @@ -1851,19 +2215,9 @@ func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error { } } - isWS := isWebsocketScheme(u) - // We don't support mix and match of websocket and non websocket URLs. - // If this is the first URL, then we accept and switch the global state - // to websocket. After that, we will know how to reject mixed URLs. - if len(nc.srvPool) == 0 { - nc.ws = isWS - } else if isWS && !nc.ws || !isWS && nc.ws { - return errors.New("mixing of websocket and non websocket URLs is not allowed") - } - var tlsName string if implicit { - curl := nc.current.url + curl := nc.current.URL // Check to see if we do not have a url.User but current connected // url does. If so copy over. if u.User == nil && curl.User != nil { @@ -1877,9 +2231,29 @@ func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error { } } - s := &srv{url: u, isImplicit: implicit, tlsName: tlsName} + s := &Server{URL: u, isImplicit: implicit, tlsName: tlsName} + return s, nil +} + +// addURLToPool adds an entry to the server pool +func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error { + s, err := nc.parseServerURL(sURL, implicit, saveTLSName) + if err != nil { + return err + } + + // We don't support mix and match of websocket and non websocket URLs. + // If this is the first URL, then we accept and switch the global state + // to websocket. After that, we will know how to reject mixed URLs. + isWS := isWebsocketScheme(s.URL) + if len(nc.srvPool) == 0 { + nc.ws = isWS + } else if isWS != nc.ws { + return ErrMixingWebsocketSchemes + } + nc.srvPool = append(nc.srvPool, s) - nc.urls[u.Host] = struct{}{} + nc.urls[s.URL.Host] = struct{}{} return nil } @@ -1904,7 +2278,7 @@ func (nc *Conn) newReaderWriter() { off: -1, } nc.bw = &natsWriter{ - limit: defaultBufSize, + limit: nc.Opts.WriteBufferSize, plimit: nc.Opts.ReconnectBufSize, } } @@ -2075,7 +2449,7 @@ func (nc *Conn) createConn() (err error) { // We will auto-expand host names if they resolve to multiple IPs hosts := []string{} - u := nc.current.url + u := nc.current.URL if !nc.Opts.SkipHostLookup && net.ParseIP(u.Hostname()) == nil { addrs, _ := net.LookupHost(u.Hostname()) @@ -2161,14 +2535,14 @@ func (nc *Conn) makeTLSConn() error { if nc.current.tlsName != _EMPTY_ { tlsCopy.ServerName = nc.current.tlsName } else { - h, _, _ := net.SplitHostPort(nc.current.url.Host) + h, _, _ := net.SplitHostPort(nc.current.URL.Host) tlsCopy.ServerName = h } } nc.conn = tls.Client(nc.conn, tlsCopy) conn := nc.conn.(*tls.Conn) if err := conn.Handshake(); err != nil { - return err + return fmt.Errorf("%w: %w", ErrTLS, err) } nc.bindToNewConn() return nil @@ -2238,8 +2612,10 @@ func (nc *Conn) ForceReconnect() error { // Stop ping timer if set. nc.stopPingTimer() - // Go ahead and make sure we have flushed the outbound + // flush any pending data and switch to pending mode to buffer new outgoing + // data until we reconnect and can flush it. nc.bw.flush() + nc.bw.switchToPending() nc.conn.Close() nc.changeConnStatus(RECONNECTING) @@ -2259,7 +2635,7 @@ func (nc *Conn) ConnectedUrl() string { if nc.status != CONNECTED { return _EMPTY_ } - return nc.current.url.String() + return nc.current.URL.String() } // ConnectedUrlRedacted reports the connected server's URL with passwords redacted @@ -2274,7 +2650,7 @@ func (nc *Conn) ConnectedUrlRedacted() string { if nc.status != CONNECTED { return _EMPTY_ } - return nc.current.url.Redacted() + return nc.current.URL.Redacted() } // ConnectedAddr returns the connected server's IP @@ -2398,6 +2774,40 @@ func (nc *Conn) ConnectedClusterName() string { return nc.info.Cluster } +// ConnectedServerJetStream reports whether the connected server has +// JetStream enabled and, if so, its API level. The API level is +// advertised by nats-server v2.12.0 or later; older servers will +// report 0 even when JetStream is enabled. +func (nc *Conn) ConnectedServerJetStream() (bool, int) { + if nc == nil { + return false, 0 + } + + nc.mu.RLock() + defer nc.mu.RUnlock() + + if nc.status != CONNECTED { + return false, 0 + } + return nc.info.JetStream, nc.info.JSApiLevel +} + +// IsSystemAccount reports whether the connected client's account +// is the system account. +func (nc *Conn) IsSystemAccount() bool { + if nc == nil { + return false + } + + nc.mu.RLock() + defer nc.mu.RUnlock() + + if nc.status != CONNECTED { + return false + } + return nc.info.IsSystemAccount +} + // Low level setup for structs, etc func (nc *Conn) setup() { nc.subs = make(map[int64]*Subscription) @@ -2411,6 +2821,31 @@ func (nc *Conn) setup() { copy(pub, _HPUB_P_) } +// tlsHandshakeEOF wraps an error with context when it occurs right after +// a completed TLS handshake, which typically indicates the remote side +// rejected the client certificate (e.g. an mTLS proxy like nginx). +// Depending on timing, the error may be io.EOF (read from closed conn) +// or a "broken pipe"/"connection reset" (write to closed conn). +func (nc *Conn) tlsHandshakeEOF(err error) error { + tlsConn, ok := nc.conn.(*tls.Conn) + if !ok || !tlsConn.ConnectionState().HandshakeComplete { + return err + } + if errors.Is(err, io.EOF) || isConnClosedError(err) { + return fmt.Errorf("%w: connection closed by remote after TLS handshake: %w", ErrTLS, err) + } + return err +} + +// isConnClosedError reports whether the error indicates the remote +// side closed the connection (broken pipe or connection reset). +// NOTE: On Windows, connection resets use WSAECONNRESET which may not +// match syscall.ECONNRESET. In that case, the error will not be +// detected here but will still be returned unwrapped by the caller. +func isConnClosedError(err error) bool { + return errors.Is(err, syscall.EPIPE) || errors.Is(err, syscall.ECONNRESET) +} + // Process a connected connection and initialize properly. func (nc *Conn) processConnectInit() error { // Set our deadline for the whole connect process @@ -2431,14 +2866,14 @@ func (nc *Conn) processConnectInit() error { // Process the INFO protocol received from the server err := nc.processExpectedInfo() if err != nil { - return err + return nc.tlsHandshakeEOF(err) } // Send the CONNECT protocol along with the initial PING protocol. // Wait for the PONG response (or any error that we get from the server). err = nc.sendConnect() if err != nil { - return err + return nc.tlsHandshakeEOF(err) } // Reset the number of PING sent out @@ -2489,7 +2924,7 @@ func (nc *Conn) connect() (bool, error) { if err == nil { nc.current.didConnect = true - nc.current.reconnects = 0 + nc.current.Reconnects = 0 nc.current.lastErr = nil break } else { @@ -2520,7 +2955,7 @@ func (nc *Conn) connect() (bool, error) { nc.setup() nc.changeConnStatus(RECONNECTING) nc.bw.switchToPending() - go nc.doReconnect(ErrNoServers, false) + go nc.doReconnect(err, false) err = nil } else { nc.current = nil @@ -2606,7 +3041,7 @@ func (nc *Conn) sendProto(proto string) { func (nc *Conn) connectProto() (string, error) { o := nc.Opts var nkey, sig, user, pass, token, ujwt string - u := nc.current.url.User + u := nc.current.URL.User if u != nil { // if no password, assume username is authToken if _, ok := u.Password(); !ok { @@ -2710,8 +3145,10 @@ func (nc *Conn) sendConnect() error { // Construct the CONNECT protocol string cProto, err := nc.connectProto() if err != nil { - if !nc.initc && nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) + if !nc.initc { + if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil { + nc.ach.push(func() { asyncErrorCB(nc, nil, err) }) + } } return err } @@ -2727,8 +3164,10 @@ func (nc *Conn) sendConnect() error { // reading byte-by-byte here is ok. proto, err := nc.readProto() if err != nil { - if !nc.initc && nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) + if !nc.initc { + if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil { + nc.ach.push(func() { asyncErrorCB(nc, nil, err) }) + } } return err } @@ -2738,8 +3177,10 @@ func (nc *Conn) sendConnect() error { // Read the rest now... proto, err = nc.readProto() if err != nil { - if !nc.initc && nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) + if !nc.initc { + if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil { + nc.ach.push(func() { asyncErrorCB(nc, nil, err) }) + } } return err } @@ -2843,13 +3284,20 @@ func (nc *Conn) doReconnect(err error, forceReconnect bool) { // Clear any errors. nc.err = nil + // Perform appropriate callback if needed for a disconnect. // DisconnectedErrCB has priority over deprecated DisconnectedCB if !nc.initc { - if nc.Opts.DisconnectedErrCB != nil { - nc.ach.push(func() { nc.Opts.DisconnectedErrCB(nc, err) }) - } else if nc.Opts.DisconnectedCB != nil { - nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) }) + if disconnectedErrCB := nc.Opts.DisconnectedErrCB; disconnectedErrCB != nil { + nc.ach.push(func() { disconnectedErrCB(nc, err) }) + } else if disconnectedCB := nc.Opts.DisconnectedCB; disconnectedCB != nil { + nc.ach.push(func() { disconnectedCB(nc) }) + } + } else if nc.Opts.RetryOnFailedConnect && nc.initc && err != nil { + // For initial connection failure with RetryOnFailedConnect, + // report the error via ReconnectErrCB if available + if nc.Opts.ReconnectErrCB != nil { + nc.ach.push(func() { nc.Opts.ReconnectErrCB(nc, err) }) } } @@ -2888,17 +3336,88 @@ func (nc *Conn) doReconnect(err error, forceReconnect bool) { } for i := 0; len(nc.srvPool) > 0; { - cur, err := nc.selectNextServer() - if err != nil { - nc.err = err - break + var err error + var cur *Server + var callbackDelay time.Duration + var useCallbackDelay bool + + if nc.Opts.ReconnectToServerCB != nil { + // Enforce MaxReconnect limits before calling the callback + maxReconnect := nc.Opts.MaxReconnect + if maxReconnect >= 0 { + // Remove servers that have exceeded MaxReconnect attempts + filtered := make([]*Server, 0, len(nc.srvPool)) + for _, srv := range nc.srvPool { + if srv != nil && srv.Reconnects < maxReconnect { + filtered = append(filtered, srv) + } + } + nc.srvPool = filtered + } + + // Check if we still have servers after filtering + if len(nc.srvPool) == 0 { + nc.err = ErrNoServers + break + } + + // Copy server values to avoid caller modifying internal state + srvVals := make([]Server, len(nc.srvPool)) + for idx, srv := range nc.srvPool { + if srv != nil { + srvVals[idx] = srv.clone() + } + } + + var selectedSrv *Server + selectedSrv, callbackDelay = nc.Opts.ReconnectToServerCB(srvVals, nc.info) + if selectedSrv != nil { + idx := slices.IndexFunc(nc.srvPool, func(srv *Server) bool { + return srv != nil && srv.URL.String() == selectedSrv.URL.String() + }) + if idx != -1 { + cur = nc.srvPool[idx] + nc.current = cur + useCallbackDelay = true + } else if reconnectErrCB := nc.Opts.ReconnectErrCB; reconnectErrCB != nil { + nc.ach.push(func() { reconnectErrCB(nc, ErrServerNotInPool) }) + } + } + } + + var doSleep bool + if cur == nil { + cur, err = nc.selectNextServer() + if err != nil { + nc.err = err + break + } + doSleep = i+1 >= len(nc.srvPool) && !forceReconnect } - doSleep := i+1 >= len(nc.srvPool) && !forceReconnect forceReconnect = false nc.mu.Unlock() - if !doSleep { + if useCallbackDelay { + if callbackDelay > 0 { + i = 0 + if rt == nil { + rt = time.NewTimer(callbackDelay) + } else { + rt.Reset(callbackDelay) + } + select { + case <-rqch: + rt.Stop() + nc.mu.Lock() + nc.rqch = make(chan struct{}) + nc.mu.Unlock() + case <-rt.C: + } + } else { + runtime.Gosched() + } + } else if !doSleep { i++ // Release the lock to give a chance to a concurrent nc.Close() to break the loop. runtime.Gosched() @@ -2944,7 +3463,7 @@ func (nc *Conn) doReconnect(err error, forceReconnect bool) { } // Mark that we tried a reconnect - cur.reconnects++ + cur.Reconnects++ // Try to create a new connection err = nc.createConn() @@ -2952,8 +3471,8 @@ func (nc *Conn) doReconnect(err error, forceReconnect bool) { // Continue to hold the lock if err != nil { // Perform appropriate callback for a failed connection attempt. - if nc.Opts.ReconnectErrCB != nil { - nc.ach.push(func() { nc.Opts.ReconnectErrCB(nc, err) }) + if reconnectErrCB := nc.Opts.ReconnectErrCB; reconnectErrCB != nil { + nc.ach.push(func() { reconnectErrCB(nc, err) }) } nc.err = nil continue @@ -2979,7 +3498,7 @@ func (nc *Conn) doReconnect(err error, forceReconnect bool) { // Clear out server stats for the server we connected to.. cur.didConnect = true - cur.reconnects = 0 + cur.Reconnects = 0 // Send existing subscription state nc.resendSubscriptions() @@ -3003,10 +3522,10 @@ func (nc *Conn) doReconnect(err error, forceReconnect bool) { // Queue up the correct callback. If we are in initial connect state // (using retry on failed connect), we will call the ConnectedCB, // otherwise the ReconnectedCB. - if nc.Opts.ReconnectedCB != nil && !nc.initc { - nc.ach.push(func() { nc.Opts.ReconnectedCB(nc) }) - } else if nc.Opts.ConnectedCB != nil && nc.initc { - nc.ach.push(func() { nc.Opts.ConnectedCB(nc) }) + if reconnectedCB := nc.Opts.ReconnectedCB; reconnectedCB != nil && !nc.initc { + nc.ach.push(func() { reconnectedCB(nc) }) + } else if connectedCB := nc.Opts.ConnectedCB; connectedCB != nil && nc.initc { + nc.ach.push(func() { connectedCB(nc) }) } // If we are here with a retry on failed connect, indicate that the @@ -3031,8 +3550,10 @@ func (nc *Conn) doReconnect(err error, forceReconnect bool) { } // processOpErr handles errors from reading or parsing the protocol. -// The lock should not be held entering this function. -func (nc *Conn) processOpErr(err error) bool { +// The lock should not be held entering this function. If forceReconnect +// is true, the first reconnect attempt will bypass the configured +// ReconnectWait; subsequent attempts still obey the normal backoff. +func (nc *Conn) processOpErr(err error, forceReconnect bool) bool { nc.mu.Lock() defer nc.mu.Unlock() if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() { @@ -3055,7 +3576,7 @@ func (nc *Conn) processOpErr(err error) bool { // Clear any queued pongs, e.g. pending flush calls. nc.clearPendingFlushCalls() - go nc.doReconnect(err, false) + go nc.doReconnect(err, forceReconnect) return false } @@ -3158,7 +3679,7 @@ func (nc *Conn) readLoop() { err = nc.parse(buf) } if err != nil { - if shouldClose := nc.processOpErr(err); shouldClose { + if shouldClose := nc.processOpErr(err, false); shouldClose { nc.close(CLOSED, true, nil) } break @@ -3320,8 +3841,8 @@ func (nc *Conn) processMsg(data []byte) { // We will pass the message through but send async error. nc.mu.Lock() nc.err = ErrBadHeaderMsg - if nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, sub, ErrBadHeaderMsg) }) + if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil { + nc.ach.push(func() { asyncErrorCB(nc, sub, ErrBadHeaderMsg) }) } nc.mu.Unlock() } @@ -3403,6 +3924,10 @@ func (nc *Conn) processMsg(data []byte) { if sub.mch != nil { select { case sub.mch <- m: + // For ChanSubscribe, track delivered count here + if sub.typ == ChanSubscription { + sub.delivered++ + } default: goto slowConsumer } @@ -3462,6 +3987,19 @@ func (nc *Conn) processMsg(data []byte) { nc.checkForSequenceMismatch(m, sub, jsi) } + // Check if we need to auto-unsubscribe for chan subscriptions + if sub.typ == ChanSubscription && sub.max > 0 && !ctrlMsg { + sub.mu.Lock() + if sub.delivered >= sub.max { + sub.mu.Unlock() + nc.mu.Lock() + nc.removeSub(sub) + nc.mu.Unlock() + } else { + sub.mu.Unlock() + } + } + return slowConsumer: @@ -3481,8 +4019,8 @@ slowConsumer: // is already experiencing client-side slow consumer situation. nc.mu.Lock() nc.err = ErrSlowConsumer - if nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, sub, ErrSlowConsumer) }) + if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil { + nc.ach.push(func() { asyncErrorCB(nc, sub, ErrSlowConsumer) }) } nc.mu.Unlock() } else { @@ -3525,8 +4063,8 @@ func (nc *Conn) processTransientError(err error) { } } } - if nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) + if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil { + nc.ach.push(func() { asyncErrorCB(nc, nil, err) }) } nc.mu.Unlock() } @@ -3538,8 +4076,10 @@ func (nc *Conn) processTransientError(err error) { // Connection lock is held on entry func (nc *Conn) processAuthError(err error) bool { nc.err = err - if !nc.initc && nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) + if !nc.initc { + if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil { + nc.ach.push(func() { asyncErrorCB(nc, nil, err) }) + } } // We should give up if we tried twice on this server and got the // same error. This behavior can be modified using IgnoreAuthErrorAbort. @@ -3584,8 +4124,15 @@ func (nc *Conn) flusher() { if nc.err == nil { nc.err = err } - if nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) + if asyncErrorCB := nc.Opts.AsyncErrorCB; asyncErrorCB != nil { + nc.ach.push(func() { asyncErrorCB(nc, nil, err) }) + } + if nc.Opts.ReconnectOnFlusherError { + nc.mu.Unlock() + if shouldClose := nc.processOpErr(err, true); shouldClose { + nc.close(CLOSED, true, nil) + } + return } } } @@ -3628,7 +4175,7 @@ func (nc *Conn) processInfo(info string) error { if info == _EMPTY_ { return nil } - var ncInfo serverInfo + var ncInfo ServerInfo if err := json.Unmarshal([]byte(info), &ncInfo); err != nil { return err } @@ -3639,7 +4186,7 @@ func (nc *Conn) processInfo(info string) error { // if advertise is disabled on that server, or servers that // did not include themselves in the async INFO protocol. // If empty, do not remove the implicit servers from the pool. - if len(nc.info.ConnectURLs) == 0 { + if len(nc.info.ConnectURLs) == 0 || nc.Opts.IgnoreDiscoveredServers { if !nc.initc && ncInfo.LameDuckMode && nc.Opts.LameDuckModeHandler != nil { nc.ach.push(func() { nc.Opts.LameDuckModeHandler(nc) }) } @@ -3662,7 +4209,7 @@ func (nc *Conn) processInfo(info string) error { sp := nc.srvPool for i := 0; i < len(sp); i++ { srv := sp[i] - curl := srv.url.Host + curl := srv.URL.Host // Check if this URL is in the INFO protocol _, inInfo := tmp[curl] // Remove from the temp map so that at the end we are left with only @@ -3670,7 +4217,7 @@ func (nc *Conn) processInfo(info string) error { delete(tmp, curl) // Keep servers that were set through Options, but also the one that // we are currently connected to (even if it is a discovered server). - if !srv.isImplicit || srv.url == nc.current.url { + if !srv.isImplicit || srv.URL == nc.current.URL { continue } if !inInfo { @@ -3682,7 +4229,7 @@ func (nc *Conn) processInfo(info string) error { } } // Figure out if we should save off the current non-IP hostname if we encounter a bare IP. - saveTLS := nc.current != nil && !hostIsIP(nc.current.url) + saveTLS := nc.current != nil && !hostIsIP(nc.current.URL) // If there are any left in the tmp map, these are new (or restarted) servers // and need to be added to the pool. @@ -3699,12 +4246,16 @@ func (nc *Conn) processInfo(info string) error { if !nc.Opts.NoRandomize { nc.shufflePool(1) } - if !nc.initc && nc.Opts.DiscoveredServersCB != nil { - nc.ach.push(func() { nc.Opts.DiscoveredServersCB(nc) }) + if !nc.initc { + if discoveredServersCB := nc.Opts.DiscoveredServersCB; discoveredServersCB != nil { + nc.ach.push(func() { discoveredServersCB(nc) }) + } } } - if !nc.initc && ncInfo.LameDuckMode && nc.Opts.LameDuckModeHandler != nil { - nc.ach.push(func() { nc.Opts.LameDuckModeHandler(nc) }) + if !nc.initc && ncInfo.LameDuckMode { + if lameDuckModeHandler := nc.Opts.LameDuckModeHandler; lameDuckModeHandler != nil { + nc.ach.push(func() { lameDuckModeHandler(nc) }) + } } return nil } @@ -3762,9 +4313,11 @@ func (nc *Conn) processErr(ie string) { // FIXME(dlc) - process Slow Consumer signals special. if e == STALE_CONNECTION { - close = nc.processOpErr(ErrStaleConnection) + close = nc.processOpErr(ErrStaleConnection, false) } else if e == MAX_CONNECTIONS_ERR { - close = nc.processOpErr(ErrMaxConnectionsExceeded) + close = nc.processOpErr(ErrMaxConnectionsExceeded, false) + } else if e == MAX_ACCOUNT_CONNECTIONS_ERR { + close = nc.processOpErr(ErrMaxAccountConnectionsExceeded, false) } else if strings.HasPrefix(e, PERMISSIONS_ERR) { nc.processTransientError(fmt.Errorf("%w: %s", ErrPermissionViolation, ne)) } else if strings.HasPrefix(e, MAX_SUBSCRIPTIONS_ERR) { @@ -3799,7 +4352,7 @@ func (nc *Conn) kickFlusher() { // argument is left untouched and needs to be correctly interpreted on // the receiver. func (nc *Conn) Publish(subj string, data []byte) error { - return nc.publish(subj, _EMPTY_, nil, data) + return nc.publish(subj, _EMPTY_, false, nil, data) } // Header represents the optional Header for a NATS message, @@ -3942,27 +4495,71 @@ func (nc *Conn) PublishMsg(m *Msg) error { if err != nil { return err } - return nc.publish(m.Subject, m.Reply, hdr, m.Data) + validateReply := m.Reply != _EMPTY_ + return nc.publish(m.Subject, m.Reply, validateReply, hdr, m.Data) } // PublishRequest will perform a Publish() expecting a response on the // reply subject. Use Request() for automatically waiting for a response // inline. func (nc *Conn) PublishRequest(subj, reply string, data []byte) error { - return nc.publish(subj, reply, nil, data) + return nc.publish(subj, reply, true, nil, data) } // Used for handrolled Itoa const digits = "0123456789" +// validateSubject checks if the subject contains characters that break the NATS protocol. +// Uses an adaptive algorithm: manual loop for short subjects (< 16 chars) and +// SIMD-optimized strings.IndexByte for longer subjects. +func validateSubject(subj string) error { + if subj == "" { + return ErrBadSubject + } + + // Adaptive threshold based on benchmark data showing crossover at ~15-20 characters. + const lengthThreshold = 16 + + if len(subj) < lengthThreshold { + // Fast path for short subjects (< 16 chars) + // Short-circuit on non-control characters. + for i := range len(subj) { + c := subj[i] + if c <= ' ' && (c == ' ' || c == '\t' || c == '\r' || c == '\n') { + return ErrBadSubject + } + } + return nil + } + + // Optimized path for long subjects (>= 16 chars) + // Uses SIMD-optimized strings.IndexByte (processes 16+ bytes per instruction) + if strings.IndexByte(subj, ' ') >= 0 || + strings.IndexByte(subj, '\t') >= 0 || + strings.IndexByte(subj, '\r') >= 0 || + strings.IndexByte(subj, '\n') >= 0 { + return ErrBadSubject + } + return nil +} + // publish is the internal function to publish messages to a nats-server. // Sends a protocol data message by queuing into the bufio writer // and kicking the flush go routine. These writes should be protected. -func (nc *Conn) publish(subj, reply string, hdr, data []byte) error { +func (nc *Conn) publish(subj, reply string, validateReply bool, hdr, data []byte) error { if nc == nil { return ErrInvalidConnection } - if subj == "" { + if !nc.Opts.SkipSubjectValidation { + if err := validateSubject(subj); err != nil { + return err + } + if validateReply { + if err := validateSubject(reply); err != nil { + return ErrBadSubject + } + } + } else if subj == _EMPTY_ { return ErrBadSubject } nc.mu.Lock() @@ -4128,7 +4725,7 @@ func (nc *Conn) createNewRequestAndSend(subj string, hdr, data []byte) (chan *Ms } nc.mu.Unlock() - if err := nc.publish(subj, respInbox, hdr, data); err != nil { + if err := nc.publish(subj, respInbox, false, hdr, data); err != nil { return nil, token, err } @@ -4224,7 +4821,7 @@ func (nc *Conn) oldRequest(subj string, hdr, data []byte, timeout time.Duration) s.AutoUnsubscribe(1) defer s.Unsubscribe() - err = nc.publish(subj, inbox, hdr, data) + err = nc.publish(subj, inbox, false, hdr, data) if err != nil { return nil, err } @@ -4585,7 +5182,7 @@ func (s *Subscription) IsValid() bool { // // For a JetStream subscription, if the library has created the JetStream // consumer, the library will send a DeleteConsumer request to the server -// when the Drain operation completes. If a failure occurs when deleting +// when the drain operation completes. If a failure occurs when deleting // the JetStream consumer, an error will be reported to the asynchronous // error callback. // If you do not wish the JetStream consumer to be automatically deleted, @@ -4628,6 +5225,15 @@ func (s *Subscription) StatusChanged(statuses ...SubStatus) <-chan SubStatus { ch := make(chan SubStatus, 10) s.mu.Lock() defer s.mu.Unlock() + + if s.status == SubscriptionClosed { + if slices.Contains(statuses, SubscriptionClosed) { + ch <- SubscriptionClosed + } + close(ch) + return ch + } + for _, status := range statuses { s.registerStatusChangeListener(status, ch) // initial status @@ -4657,7 +5263,7 @@ func (s *Subscription) registerStatusChangeListener(status SubStatus, ch chan Su // will not block. Lock should be held entering. func (s *Subscription) sendStatusEvent(status SubStatus) { for ch, statuses := range s.statListeners { - if !containsStatus(statuses, status) { + if !slices.Contains(statuses, status) { continue } // only send event if someone's listening @@ -4665,19 +5271,16 @@ func (s *Subscription) sendStatusEvent(status SubStatus) { case ch <- status: default: } - if status == SubscriptionClosed { - close(ch) - } } -} - -func containsStatus(statuses []SubStatus, status SubStatus) bool { - for _, s := range statuses { - if s == status { - return true + // After sending SubscriptionClosed status to all listeners, + // close all channels and clear the map to prevent future + // sends to closed channels that could cause panics + if status == SubscriptionClosed { + for ch := range s.statListeners { + close(ch) } + s.statListeners = nil } - return false } // changeSubStatus changes subscription status and sends events @@ -5158,8 +5761,8 @@ func (s *Subscription) ClearMaxPending() error { // Pending Limits const ( - // DefaultSubPendingMsgsLimit will be 512k msgs. - DefaultSubPendingMsgsLimit = 512 * 1024 + // DefaultSubPendingMsgsLimit will be 500k msgs. + DefaultSubPendingMsgsLimit = 500_000 // DefaultSubPendingBytesLimit is 64MB DefaultSubPendingBytesLimit = 64 * 1024 * 1024 ) @@ -5305,7 +5908,7 @@ func (nc *Conn) processPingTimer() { nc.pout++ if nc.pout > nc.Opts.MaxPingsOut { nc.mu.Unlock() - if shouldClose := nc.processOpErr(ErrStaleConnection); shouldClose { + if shouldClose := nc.processOpErr(ErrStaleConnection, false); shouldClose { nc.close(CLOSED, true, nil) } return @@ -5509,6 +6112,14 @@ func (nc *Conn) close(status Status, doCBs bool, err error) { close(s.mch) } s.mch = nil + + // Call closed handler for non-AsyncSubscription types (AsyncSubscription handlers + // are called by waitForMsgs when it exits) + var done func(string) + if s.typ != AsyncSubscription && s.pDone != nil { + done = s.pDone + } + // Mark as invalid, for signaling to waitForMsgs s.closed = true // Mark connection closed in subscription @@ -5519,6 +6130,11 @@ func (nc *Conn) close(status Status, doCBs bool, err error) { } s.mu.Unlock() + + // Call the closed handler outside the lock to avoid potential deadlocks + if done != nil { + done(s.Subject) + } } nc.subs = nil nc.subsMu.Unlock() @@ -5534,8 +6150,8 @@ func (nc *Conn) close(status Status, doCBs bool, err error) { nc.ach.push(func() { disconnectedCB(nc) }) } } - if nc.Opts.ClosedCB != nil { - nc.ach.push(func() { nc.Opts.ClosedCB(nc) }) + if closedCB := nc.Opts.ClosedCB; closedCB != nil { + nc.ach.push(func() { closedCB(nc) }) } } // If this is terminal, then we have to notify the asyncCB handler that @@ -5725,7 +6341,7 @@ func (nc *Conn) getServers(implicitOnly bool) []string { if implicitOnly && !nc.srvPool[i].isImplicit { continue } - url := nc.srvPool[i].url + url := nc.srvPool[i].URL servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host)) } return servers @@ -5881,6 +6497,103 @@ func (nc *Conn) Barrier(f func()) error { return nil } +// ServerPool returns a copy of the current server pool for the connection. +// +// This function should not be called from within connection callbacks to avoid +// potential deadlocks. +func (nc *Conn) ServerPool() []Server { + nc.mu.RLock() + defer nc.mu.RUnlock() + servers := make([]Server, len(nc.srvPool)) + for i, srv := range nc.srvPool { + if srv != nil { + // Return a copy to avoid exposing internal state + servers[i] = srv.clone() + } + } + return servers +} + +// SetServerPool allows updating the server pool for the connection. This +// replaces the existing pool with the provided list of server URLs. If the +// current server is not in the new pool, the client will switch to a server in +// the new pool on the next reconnect attempt. This function is thread-safe and +// can be called while the connection is active. It will return an error if the +// connection is closed or if any of the provided URLs are invalid. +// +// This function does not trigger an immediate reconnect. The new server +// pool will be used on the next reconnect attempt. +// If you want to trigger an immediate reconnect to apply the new server pool, +// you can call [Conn.ForceReconnect] after this function. +// +// Unless [IgnoreDiscoveredServers] is used true, the client will continue to +// discover and add new servers to the pool as it receives INFO messages from +// the server. If you want to prevent this behavior and only use the servers +// provided in SetServerPool, use [IgnoreDiscoveredServers]. +// +// This function should not be called from within connection callbacks to avoid +// potential deadlocks. +func (nc *Conn) SetServerPool(servers []string) error { + nc.mu.Lock() + defer nc.mu.Unlock() + if nc.isClosed() { + return ErrConnectionClosed + } + + // Parse and validate all URLs first (without modifying state) + newPool := make([]*Server, 0, len(servers)) + newURLs := make(map[string]struct{}) + + for _, addr := range servers { + s, err := nc.parseServerURL(addr, false, false) + if err != nil { + return err + } + if isWebsocketScheme(s.URL) != nc.ws { + return ErrMixingWebsocketSchemes + } + + newPool = append(newPool, s) + newURLs[s.URL.Host] = struct{}{} + } + + // Preserve state from existing pool entries + for _, newSrv := range newPool { + if idx := slices.IndexFunc(nc.srvPool, func(oldSrv *Server) bool { + return oldSrv != nil && oldSrv.URL.String() == newSrv.URL.String() + }); idx != -1 { + newSrv.Reconnects = nc.srvPool[idx].Reconnects + newSrv.didConnect = nc.srvPool[idx].didConnect + newSrv.lastErr = nc.srvPool[idx].lastErr + } + } + + nc.srvPool = newPool + nc.urls = newURLs + + // Update nc.current to point to the corresponding server in the new pool + // This is important because currentServer() uses pointer equality + if nc.current != nil { + currentURL := nc.current.URL.String() + found := false + for _, s := range newPool { + if s.URL.String() == currentURL { + // Update nc.current to point to the server instance in the new pool + nc.current = s + found = true + break + } + } + if !found && len(newPool) > 0 { + // Current server not in new pool - point to first server in new pool + // This ensures selectNextServer() can find it and properly rotate + nc.current = newPool[0] + } + } + + return nil +} + // GetClientIP returns the client IP as known by the server. // Supported as of server version 2.1.6. func (nc *Conn) GetClientIP() (net.IP, error) { @@ -5943,8 +6656,8 @@ func (nc *Conn) RemoveStatusListener(ch chan (Status)) { } for _, listeners := range nc.statListeners { - for l := range listeners { - delete(listeners, l) + for range listeners { + delete(listeners, ch) } } } @@ -6107,18 +6820,12 @@ func sigHandler(nonce []byte, seedFile string) ([]byte, error) { type timeoutWriter struct { timeout time.Duration conn net.Conn - err error } // Write implements the io.Writer interface. func (tw *timeoutWriter) Write(p []byte) (int, error) { - if tw.err != nil { - return 0, tw.err - } - - var n int tw.conn.SetWriteDeadline(time.Now().Add(tw.timeout)) - n, tw.err = tw.conn.Write(p) + n, err := tw.conn.Write(p) tw.conn.SetWriteDeadline(time.Time{}) - return n, tw.err + return n, err } diff --git a/vendor/github.com/nats-io/nats.go/nats_iter.go b/vendor/github.com/nats-io/nats.go/nats_iter.go index 05234d5b08..60b781f972 100644 --- a/vendor/github.com/nats-io/nats.go/nats_iter.go +++ b/vendor/github.com/nats-io/nats.go/nats_iter.go @@ -63,6 +63,7 @@ func (sub *Subscription) MsgsTimeout(timeout time.Duration) iter.Seq2[*Msg, erro if !errors.Is(err, ErrTimeout) { return } + continue } if !yield(msg, nil) { return diff --git a/vendor/github.com/nats-io/nats.go/ws.go b/vendor/github.com/nats-io/nats.go/ws.go index 46d8300dec..a9d66f3698 100644 --- a/vendor/github.com/nats-io/nats.go/ws.go +++ b/vendor/github.com/nats-io/nats.go/ws.go @@ -55,6 +55,12 @@ const ( wsMaxControlPayloadSize = 125 wsCloseSatusSize = 2 + // wsMaxMsgPayloadMultiple is the multiplier applied to MaxPayload to + // determine the maximum WebSocket frame size. + wsMaxMsgPayloadMultiple = 8 + // wsMaxMsgPayloadLimit is the absolute cap on WebSocket frame size (64MB). + wsMaxMsgPayloadLimit = 64 * 1024 * 1024 + // From https://tools.ietf.org/html/rfc6455#section-11.7 wsCloseStatusNormalClosure = 1000 wsCloseStatusNoStatusReceived = 1005 @@ -85,6 +91,7 @@ type websocketReader struct { nl bool dc *wsDecompressor nc *Conn + closeErr error } type wsDecompressor struct { @@ -113,10 +120,7 @@ func (d *wsDecompressor) Read(dst []byte) (int, error) { copied := 0 rem := len(dst) for buf := d.bufs[0]; buf != nil && rem > 0; { - n := len(buf[d.off:]) - if n > rem { - n = rem - } + n := min(len(buf[d.off:]), rem) copy(dst[copied:], buf[d.off:d.off+n]) copied += n rem -= n @@ -181,6 +185,18 @@ func wsNewReader(r io.Reader) *websocketReader { return &websocketReader{r: r, ff: true} } +// maxFrameSize returns the maximum allowed WebSocket frame size based on the +// negotiated MaxPayload. This mirrors the server-side wsMaxMessageSize logic. +func (r *websocketReader) maxFrameSize() uint64 { + if r.nc != nil { + mp := r.nc.info.MaxPayload + if mp > 0 && uint64(mp) <= wsMaxMsgPayloadLimit/wsMaxMsgPayloadMultiple { + return uint64(mp) * wsMaxMsgPayloadMultiple + } + } + return wsMaxMsgPayloadLimit +} + // From now on, reads will be from the readLoop and we will need to // acquire the connection lock should we have to send/write a control // message from handleControlFrame. @@ -202,6 +218,15 @@ func (r *websocketReader) Read(p []byte) (int, error) { return r.drainPending(p), nil } + // If we have a deferred close error (from a previous Read that + // had both data frames and a close frame), return it now that + // pending data has been drained. + if r.closeErr != nil { + err := r.closeErr + r.closeErr = nil + return 0, err + } + // Get some data from the underlying reader. n, err := r.r.Read(p) if err != nil { @@ -278,13 +303,27 @@ func (r *websocketReader) Read(p []byte) (int, error) { if err != nil { return 0, err } - rem = int(binary.BigEndian.Uint64(tmpBuf)) + rem64 := binary.BigEndian.Uint64(tmpBuf) + if rem64&(1<<63) != 0 { + return 0, errors.New("invalid websocket frame: MSB set in 64-bit payload length") + } + if rem64 > r.maxFrameSize() { + return 0, fmt.Errorf("websocket frame too large: %d", rem64) + } + rem = int(rem64) } // Handle control messages in place... if wsIsControlFrame(frameType) { pos, err = r.handleControlFrame(frameType, buf, pos, rem) if err != nil { + // If we already have pending data (e.g. a -ERR message + // that arrived before this close frame), defer the error + // so the pending data can be returned to the caller first. + if len(r.pending) > 0 { + r.closeErr = err + break + } return 0, err } rem = 0 @@ -583,6 +622,11 @@ func (nc *Conn) wsInitHandshake(u *url.URL) error { proxyPath = "/" + proxyPath } ustr += proxyPath + } else if u.Path != "" { + ustr += u.Path + } + if u.RawQuery != "" { + ustr += "?" + u.RawQuery } u, err = url.Parse(ustr) @@ -610,6 +654,9 @@ func (nc *Conn) wsInitHandshake(u *url.URL) error { if compress { req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue) } + if err := nc.wsUpdateConnectionHeaders(req); err != nil { + return err + } if err := req.Write(nc.conn); err != nil { return err } @@ -728,6 +775,25 @@ func (nc *Conn) wsEnqueueControlMsg(needsLock bool, frameType wsOpCode, payload nc.bw.flush() } +func (nc *Conn) wsUpdateConnectionHeaders(req *http.Request) error { + var headers http.Header + var err error + if nc.Opts.WebSocketConnectionHeadersHandler != nil { + headers, err = nc.Opts.WebSocketConnectionHeadersHandler() + if err != nil { + return err + } + } else { + headers = nc.Opts.WebSocketConnectionHeaders + } + for key, values := range headers { + for _, val := range values { + req.Header.Add(key, val) + } + } + return nil +} + func wsPMCExtensionSupport(header http.Header) (bool, bool) { for _, extensionList := range header["Sec-Websocket-Extensions"] { extensions := strings.Split(extensionList, ",") diff --git a/vendor/github.com/nats-io/nkeys/.goreleaser.yml b/vendor/github.com/nats-io/nkeys/.goreleaser.yml index e5c4f154a4..cf9d92487b 100644 --- a/vendor/github.com/nats-io/nkeys/.goreleaser.yml +++ b/vendor/github.com/nats-io/nkeys/.goreleaser.yml @@ -1,3 +1,4 @@ +version: 2 project_name: nkeys release: github: @@ -41,7 +42,8 @@ archives: - name_template: '{{ .ProjectName }}-v{{ .Version }}-{{ .Os }}-{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' wrap_in_directory: true - format: zip + formats: + - zip files: - README.md - LICENSE @@ -50,7 +52,7 @@ checksum: name_template: '{{ .ProjectName }}-v{{ .Version }}-checksums.txt' snapshot: - name_template: 'dev' + version_template: dev nfpms: - file_name_template: '{{ .ProjectName }}-v{{ .Version }}-{{ .Arch }}{{ if .Arm diff --git a/vendor/modules.txt b/vendor/modules.txt index 8ea6081685..fda09645a0 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1147,8 +1147,8 @@ github.com/kballard/go-shellquote # github.com/kevinburke/ssh_config v1.2.0 ## explicit github.com/kevinburke/ssh_config -# github.com/klauspost/compress v1.18.0 -## explicit; go 1.22 +# github.com/klauspost/compress v1.18.5 +## explicit; go 1.24 github.com/klauspost/compress/flate github.com/klauspost/compress/internal/le github.com/klauspost/compress/internal/race @@ -1226,14 +1226,14 @@ github.com/munnerz/goautoneg # github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f ## explicit github.com/mxk/go-flowrate/flowrate -# github.com/nats-io/nats.go v1.43.0 -## explicit; go 1.23.0 +# github.com/nats-io/nats.go v1.53.1 +## explicit; go 1.25.0 github.com/nats-io/nats.go github.com/nats-io/nats.go/encoders/builtin github.com/nats-io/nats.go/internal/parser github.com/nats-io/nats.go/util -# github.com/nats-io/nkeys v0.4.11 -## explicit; go 1.23.0 +# github.com/nats-io/nkeys v0.4.15 +## explicit; go 1.24.0 github.com/nats-io/nkeys # github.com/nats-io/nuid v1.0.1 ## explicit