Compare commits
	
		
			24 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| bac736deef | |||
| b89760a2cb | |||
| d830f70157 | |||
| 581fecd8f1 | |||
| d5d1e26d7b | |||
| aabfecfd3d | |||
| ff7a88fcce | |||
| 397f5414b3 | |||
| 9dd6efddf9 | |||
| 1e587b348a | |||
| 8475922d42 | |||
| 69fe6994ae | |||
| 6360feb351 | |||
| 0845f4873b | |||
| 747e35148f | |||
| 21f06fee6c | |||
| f4f8793686 | |||
| ec4922ad8b | |||
| eaea14e5a8 | |||
| f6f7139d2f | |||
| 51e4118dfc | |||
| aaf8c43e04 | |||
| cfecb4afd0 | |||
| ae4ae64694 | 
							
								
								
									
										53
									
								
								.github/workflows/job_coverage.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										53
									
								
								.github/workflows/job_coverage.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,53 @@ | |||||||
|  | name: coverage | ||||||
|  |  | ||||||
|  | on: | ||||||
|  |   push: | ||||||
|  |     branches: [ main, v3, v4 ] | ||||||
|  |     paths-ignore: | ||||||
|  |       - '.github/**' | ||||||
|  |       - '.gitea/**' | ||||||
|  |   pull_request: | ||||||
|  |     branches: [ main, v3, v4 ] | ||||||
|  |  | ||||||
|  | jobs: | ||||||
|  |  | ||||||
|  |   build: | ||||||
|  |     if: github.server_url != 'https://github.com' | ||||||
|  |     runs-on: ubuntu-latest | ||||||
|  |     steps: | ||||||
|  |     - name: checkout code | ||||||
|  |       uses: actions/checkout@v4 | ||||||
|  |       with: | ||||||
|  |         filter: 'blob:none' | ||||||
|  |  | ||||||
|  |     - name: setup go | ||||||
|  |       uses: actions/setup-go@v5 | ||||||
|  |       with: | ||||||
|  |         cache-dependency-path: "**/*.sum" | ||||||
|  |         go-version: 'stable' | ||||||
|  |  | ||||||
|  |     - name: test coverage | ||||||
|  |       run: | | ||||||
|  |         go test -v -cover ./... -covermode=count -coverprofile coverage.out -coverpkg ./... | ||||||
|  |         go tool cover -func coverage.out -o coverage.out | ||||||
|  |  | ||||||
|  |     - name: coverage badge | ||||||
|  |       uses: tj-actions/coverage-badge-go@v2 | ||||||
|  |       with: | ||||||
|  |         green: 80 | ||||||
|  |         filename: coverage.out | ||||||
|  |  | ||||||
|  |     - uses: stefanzweifel/git-auto-commit-action@v4 | ||||||
|  |       name: autocommit | ||||||
|  |       with: | ||||||
|  |         commit_message: Apply Code Coverage Badge | ||||||
|  |         skip_fetch: false | ||||||
|  |         skip_checkout: false | ||||||
|  |         file_pattern: ./README.md | ||||||
|  |  | ||||||
|  |     - name: push | ||||||
|  |       if: steps.auto-commit-action.outputs.changes_detected == 'true' | ||||||
|  |       uses: ad-m/github-push-action@master | ||||||
|  |       with: | ||||||
|  |         github_token: ${{ github.token }} | ||||||
|  |         branch: ${{ github.ref }} | ||||||
| @@ -3,10 +3,10 @@ name: lint | |||||||
| on: | on: | ||||||
|   pull_request: |   pull_request: | ||||||
|     types: [opened, reopened, synchronize] |     types: [opened, reopened, synchronize] | ||||||
|     branches: |     branches: [ master, v3, v4 ] | ||||||
|     - master |     paths-ignore: | ||||||
|     - v3 |       - '.github/**' | ||||||
|     - v4 |       - '.gitea/**' | ||||||
| 
 | 
 | ||||||
| jobs: | jobs: | ||||||
|   lint: |   lint: | ||||||
| @@ -20,10 +20,10 @@ jobs: | |||||||
|       uses: actions/setup-go@v5 |       uses: actions/setup-go@v5 | ||||||
|       with: |       with: | ||||||
|         cache-dependency-path: "**/*.sum" |         cache-dependency-path: "**/*.sum" | ||||||
|         go-version: 'stable'  |         go-version: 'stable' | ||||||
|     - name: setup deps |     - name: setup deps | ||||||
|       run: go get -v ./... |       run: go get -v ./... | ||||||
|     - name: run lint |     - name: run lint | ||||||
|       uses: https://github.com/golangci/golangci-lint-action@v6 |       uses: golangci/golangci-lint-action@v6 | ||||||
|       with: |       with: | ||||||
|         version: 'latest' |         version: 'latest' | ||||||
| @@ -3,15 +3,12 @@ name: test | |||||||
| on: | on: | ||||||
|   pull_request: |   pull_request: | ||||||
|     types: [opened, reopened, synchronize] |     types: [opened, reopened, synchronize] | ||||||
|     branches: |     branches: [ master, v3, v4 ] | ||||||
|     - master |  | ||||||
|     - v3 |  | ||||||
|     - v4 |  | ||||||
|   push: |   push: | ||||||
|     branches: |     branches: [ master, v3, v4 ] | ||||||
|     - master |     paths-ignore: | ||||||
|     - v3 |       - '.github/**' | ||||||
|     - v4 |       - '.gitea/**' | ||||||
| 
 | 
 | ||||||
| jobs: | jobs: | ||||||
|   test: |   test: | ||||||
| @@ -3,15 +3,12 @@ name: test | |||||||
| on: | on: | ||||||
|   pull_request: |   pull_request: | ||||||
|     types: [opened, reopened, synchronize] |     types: [opened, reopened, synchronize] | ||||||
|     branches: |     branches: [ master, v3, v4 ] | ||||||
|     - master |  | ||||||
|     - v3 |  | ||||||
|     - v4 |  | ||||||
|   push: |   push: | ||||||
|     branches: |     branches: [ master, v3, v4 ] | ||||||
|     - master |     paths-ignore: | ||||||
|     - v3 |       - '.github/**' | ||||||
|     - v4 |       - '.gitea/**' | ||||||
| 
 | 
 | ||||||
| jobs: | jobs: | ||||||
|   test: |   test: | ||||||
| @@ -35,19 +32,19 @@ jobs: | |||||||
|         go-version: 'stable' |         go-version: 'stable' | ||||||
|     - name: setup go work |     - name: setup go work | ||||||
|       env: |       env: | ||||||
|         GOWORK: /workspace/${{ github.repository_owner }}/go.work |         GOWORK: ${{ github.workspace }}/go.work | ||||||
|       run: | |       run: | | ||||||
|         go work init |         go work init | ||||||
|         go work use . |         go work use . | ||||||
|         go work use micro-tests         |         go work use micro-tests | ||||||
|     - name: setup deps |     - name: setup deps | ||||||
|       env: |       env: | ||||||
|         GOWORK: /workspace/${{ github.repository_owner }}/go.work |         GOWORK: ${{ github.workspace }}/go.work | ||||||
|       run: go get -v ./... |       run: go get -v ./... | ||||||
|     - name: run tests |     - name: run tests | ||||||
|       env: |       env: | ||||||
|         INTEGRATION_TESTS: yes |         INTEGRATION_TESTS: yes | ||||||
|         GOWORK: /workspace/${{ github.repository_owner }}/go.work |         GOWORK: ${{ github.workspace }}/go.work | ||||||
|       run: | |       run: | | ||||||
|         cd micro-tests |         cd micro-tests | ||||||
|         go test -mod readonly -v ./... || true         |         go test -mod readonly -v ./... || true | ||||||
| @@ -1,21 +1,5 @@ | |||||||
| run: | run: | ||||||
|   concurrency: 8 |   concurrency: 8 | ||||||
|   deadline: 5m |   timeout: 5m | ||||||
|   issues-exit-code: 1 |   issues-exit-code: 1 | ||||||
|   tests: true |   tests: true | ||||||
|  |  | ||||||
| linters: |  | ||||||
|   enable: |  | ||||||
|     - staticcheck |  | ||||||
|     - unused |  | ||||||
|     - gosimple |  | ||||||
|     - govet |  | ||||||
|     - prealloc |  | ||||||
|     - unconvert |  | ||||||
|     - nakedret |  | ||||||
|  |  | ||||||
| linters-settings: |  | ||||||
|   govet: |  | ||||||
|     check-all: true |  | ||||||
|     enable: |  | ||||||
|       - fieldalignment |  | ||||||
							
								
								
									
										37
									
								
								carrier.go
									
									
									
									
									
								
							
							
						
						
									
										37
									
								
								carrier.go
									
									
									
									
									
								
							| @@ -1,6 +1,10 @@ | |||||||
| package kgo | package kgo | ||||||
|  |  | ||||||
| import ( | import ( | ||||||
|  | 	"net/http" | ||||||
|  | 	"slices" | ||||||
|  | 	"strings" | ||||||
|  |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v3/metadata" | ||||||
| ) | ) | ||||||
| @@ -53,24 +57,37 @@ func (c RecordCarrier) Keys() []string { | |||||||
| 	return out | 	return out | ||||||
| } | } | ||||||
|  |  | ||||||
| func setHeaders(r *kgo.Record, md metadata.Metadata) { | func setHeaders(r *kgo.Record, md metadata.Metadata, exclude ...string) { | ||||||
| 	seen := make(map[string]struct{}) | 	seen := make(map[string]struct{}) | ||||||
|  |  | ||||||
| loop: | loop: | ||||||
| 	for k, v := range md { | 	for k, v := range md { | ||||||
|  | 		k = http.CanonicalHeaderKey(k) | ||||||
|  |  | ||||||
|  | 		if _, ok := seen[k]; ok { | ||||||
|  | 			continue loop | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		if slices.ContainsFunc(exclude, func(s string) bool { | ||||||
|  | 			return strings.EqualFold(s, k) | ||||||
|  | 		}) { | ||||||
|  | 			continue loop | ||||||
|  | 		} | ||||||
|  |  | ||||||
| 		for i := 0; i < len(r.Headers); i++ { | 		for i := 0; i < len(r.Headers); i++ { | ||||||
| 			if r.Headers[i].Key == k { | 			if strings.EqualFold(r.Headers[i].Key, k) { | ||||||
| 				// Key exist, update the value. | 				// Key exist, update the value. | ||||||
| 				r.Headers[i].Value = []byte(v) | 				r.Headers[i].Value = []byte(v) | ||||||
| 				continue loop | 				continue loop | ||||||
| 			} else if _, ok := seen[k]; ok { |  | ||||||
| 				continue loop |  | ||||||
| 			} | 			} | ||||||
| 			// Key does not exist, append new header. |  | ||||||
| 			r.Headers = append(r.Headers, kgo.RecordHeader{ |  | ||||||
| 				Key:   k, |  | ||||||
| 				Value: []byte(v), |  | ||||||
| 			}) |  | ||||||
| 			seen[k] = struct{}{} |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
|  | 		// Key does not exist, append new header. | ||||||
|  | 		r.Headers = append(r.Headers, kgo.RecordHeader{ | ||||||
|  | 			Key:   k, | ||||||
|  | 			Value: []byte(v), | ||||||
|  | 		}) | ||||||
|  |  | ||||||
|  | 		seen[k] = struct{}{} | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|   | |||||||
							
								
								
									
										10
									
								
								errors.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								errors.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,10 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  | 	"errors" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func isContextError(err error) bool { | ||||||
|  | 	return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) | ||||||
|  | } | ||||||
							
								
								
									
										29
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										29
									
								
								go.mod
									
									
									
									
									
								
							| @@ -1,27 +1,32 @@ | |||||||
| module go.unistack.org/micro-broker-kgo/v3 | module go.unistack.org/micro-broker-kgo/v3 | ||||||
|  |  | ||||||
| go 1.22.0 | go 1.24.0 | ||||||
|  |  | ||||||
|  | toolchain go1.24.3 | ||||||
|  |  | ||||||
| require ( | require ( | ||||||
| 	github.com/google/uuid v1.6.0 | 	github.com/google/uuid v1.6.0 | ||||||
| 	github.com/twmb/franz-go v1.18.0 | 	github.com/stretchr/testify v1.11.1 | ||||||
| 	github.com/twmb/franz-go/pkg/kadm v1.14.0 | 	github.com/twmb/franz-go v1.20.2 | ||||||
| 	github.com/twmb/franz-go/pkg/kmsg v1.9.0 | 	github.com/twmb/franz-go/pkg/kadm v1.17.1 | ||||||
| 	go.opentelemetry.io/otel v1.33.0 | 	github.com/twmb/franz-go/pkg/kmsg v1.12.0 | ||||||
| 	go.unistack.org/micro/v3 v3.11.37 | 	go.opentelemetry.io/otel v1.38.0 | ||||||
|  | 	go.unistack.org/micro/v3 v3.11.48 | ||||||
| ) | ) | ||||||
|  |  | ||||||
| require ( | require ( | ||||||
| 	github.com/ash3in/uuidv8 v1.2.0 // indirect | 	github.com/ash3in/uuidv8 v1.2.0 // indirect | ||||||
| 	github.com/klauspost/compress v1.17.11 // indirect | 	github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect | ||||||
|  | 	github.com/klauspost/compress v1.18.1 // indirect | ||||||
| 	github.com/kr/pretty v0.3.1 // indirect | 	github.com/kr/pretty v0.3.1 // indirect | ||||||
| 	github.com/matoous/go-nanoid v1.5.1 // indirect | 	github.com/matoous/go-nanoid v1.5.1 // indirect | ||||||
| 	github.com/pierrec/lz4/v4 v4.1.22 // indirect | 	github.com/pierrec/lz4/v4 v4.1.22 // indirect | ||||||
|  | 	github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect | ||||||
| 	go.unistack.org/micro-proto/v3 v3.4.1 // indirect | 	go.unistack.org/micro-proto/v3 v3.4.1 // indirect | ||||||
| 	golang.org/x/crypto v0.31.0 // indirect | 	golang.org/x/crypto v0.43.0 // indirect | ||||||
| 	golang.org/x/sys v0.28.0 // indirect | 	golang.org/x/sys v0.37.0 // indirect | ||||||
| 	google.golang.org/genproto/googleapis/rpc v0.0.0-20241216192217-9240e9c98484 // indirect | 	google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 // indirect | ||||||
| 	google.golang.org/grpc v1.69.2 // indirect | 	google.golang.org/grpc v1.76.0 // indirect | ||||||
| 	google.golang.org/protobuf v1.36.1 // indirect | 	google.golang.org/protobuf v1.36.10 // indirect | ||||||
| 	gopkg.in/yaml.v3 v3.0.1 // indirect | 	gopkg.in/yaml.v3 v3.0.1 // indirect | ||||||
| ) | ) | ||||||
|   | |||||||
							
								
								
									
										72
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										72
									
								
								go.sum
									
									
									
									
									
								
							| @@ -7,12 +7,14 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1 | |||||||
| github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||||||
| github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= | ||||||
| github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= | 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.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= | ||||||
| github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= | ||||||
| github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= | ||||||
| github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= | ||||||
| github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= | ||||||
| github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= | ||||||
|  | github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co= | ||||||
|  | github.com/klauspost/compress v1.18.1/go.mod h1:ZQFFVG+MdnR0P+l6wpXgIL4NTtwiKIdBnrBd8Nrxr+0= | ||||||
| github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= | ||||||
| github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= | ||||||
| github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= | ||||||
| @@ -27,34 +29,44 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH | |||||||
| github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= | ||||||
| github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= | github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= | ||||||
| github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= | github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= | ||||||
| github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= | github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= | ||||||
| github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= | github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= | ||||||
| github.com/twmb/franz-go v1.18.0 h1:25FjMZfdozBywVX+5xrWC2W+W76i0xykKjTdEeD2ejw= | github.com/twmb/franz-go v1.19.5 h1:W7+o8D0RsQsedqib71OVlLeZ0zI6CbFra7yTYhZTs5Y= | ||||||
| github.com/twmb/franz-go v1.18.0/go.mod h1:zXCGy74M0p5FbXsLeASdyvfLFsBvTubVqctIaa5wQ+I= | github.com/twmb/franz-go v1.19.5/go.mod h1:4kFJ5tmbbl7asgwAGVuyG1ZMx0NNpYk7EqflvWfPCpM= | ||||||
| github.com/twmb/franz-go/pkg/kadm v1.14.0 h1:nAn1co1lXzJQocpzyIyOFOjUBf4WHWs5/fTprXy2IZs= | github.com/twmb/franz-go v1.20.2 h1:CiwhyKZHW6vqSHJkh+RTxFAJkio0jBjM/JQhx/HZ72A= | ||||||
| github.com/twmb/franz-go/pkg/kadm v1.14.0/go.mod h1:XjOPz6ZaXXjrW2jVCfLuucP8H1w2TvD6y3PT2M+aAM4= | github.com/twmb/franz-go v1.20.2/go.mod h1:YCnepDd4gl6vdzG03I5Wa57RnCTIC6DVEyMpDX/J8UA= | ||||||
| github.com/twmb/franz-go/pkg/kmsg v1.9.0 h1:JojYUph2TKAau6SBtErXpXGC7E3gg4vGZMv9xFU/B6M= | github.com/twmb/franz-go/pkg/kadm v1.16.1 h1:IEkrhTljgLHJ0/hT/InhXGjPdmWfFvxp7o/MR7vJ8cw= | ||||||
| github.com/twmb/franz-go/pkg/kmsg v1.9.0/go.mod h1:CMbfazviCyY6HM0SXuG5t9vOwYDHRCSrJJyBAe5paqg= | github.com/twmb/franz-go/pkg/kadm v1.16.1/go.mod h1:Ue/ye1cc9ipsQFg7udFbbGiFNzQMqiH73fGC2y0rwyc= | ||||||
| go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw= | github.com/twmb/franz-go/pkg/kadm v1.17.1 h1:Bt02Y/RLgnFO2NP2HVP1kd2TFtGRiJZx+fSArjZDtpw= | ||||||
| go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I= | github.com/twmb/franz-go/pkg/kadm v1.17.1/go.mod h1:s4duQmrDbloVW9QTMXhs6mViTepze7JLG43xwPcAeTg= | ||||||
|  | github.com/twmb/franz-go/pkg/kmsg v1.11.2 h1:hIw75FpwcAjgeyfIGFqivAvwC5uNIOWRGvQgZhH4mhg= | ||||||
|  | github.com/twmb/franz-go/pkg/kmsg v1.11.2/go.mod h1:CFfkkLysDNmukPYhGzuUcDtf46gQSqCZHMW1T4Z+wDE= | ||||||
|  | github.com/twmb/franz-go/pkg/kmsg v1.12.0 h1:CbatD7ers1KzDNgJqPbKOq0Bz/WLBdsTH75wgzeVaPc= | ||||||
|  | github.com/twmb/franz-go/pkg/kmsg v1.12.0/go.mod h1:+DPt4NC8RmI6hqb8G09+3giKObE6uD2Eya6CfqBpeJY= | ||||||
|  | go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= | ||||||
|  | go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= | ||||||
| go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q= | go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q= | ||||||
| go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo= | go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo= | ||||||
| go.unistack.org/micro/v3 v3.11.37 h1:ZcpnXAYEMcAwmnVb5b7o8/PylGnILxXMHaUlRrPmRI0= | go.unistack.org/micro/v3 v3.11.45 h1:fjTLZYWgsVf9FIMZBxOg8ios2/tmyimnjZrsrxEUeXU= | ||||||
| go.unistack.org/micro/v3 v3.11.37/go.mod h1:POGU5hstnAT9LH70m8FalyQSNi2GfIew71K75JenIZk= | go.unistack.org/micro/v3 v3.11.45/go.mod h1:fDQ8Mu9wubaFP0L8hNQlpzHiEnWN0wbOlawN9HYo0N4= | ||||||
| golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= | go.unistack.org/micro/v3 v3.11.48 h1:lHJYSHU2z1TTcuswItGwG7cZXN6n04EFqY7lk/0gA7w= | ||||||
| golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= | go.unistack.org/micro/v3 v3.11.48/go.mod h1:fDQ8Mu9wubaFP0L8hNQlpzHiEnWN0wbOlawN9HYo0N4= | ||||||
| golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= | golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= | ||||||
| golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= | golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= | ||||||
| golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= | golang.org/x/net v0.45.0 h1:RLBg5JKixCy82FtLJpeNlVM0nrSqpCRYzVU1n8kj0tM= | ||||||
| golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= | golang.org/x/net v0.45.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= | ||||||
| golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= | golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= | ||||||
| golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= | golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= | ||||||
| google.golang.org/genproto/googleapis/rpc v0.0.0-20241216192217-9240e9c98484 h1:Z7FRVJPSMaHQxD0uXU8WdgFh8PseLM8Q8NzhnpMrBhQ= | golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= | ||||||
| google.golang.org/genproto/googleapis/rpc v0.0.0-20241216192217-9240e9c98484/go.mod h1:lcTa1sDdWEIHMWlITnIczmw5w60CF9ffkb8Z+DVmmjA= | golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= | ||||||
| google.golang.org/grpc v1.69.2 h1:U3S9QEtbXC0bYNvRtcoklF3xGtLViumSYxWykJS+7AU= | google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff h1:A90eA31Wq6HOMIQlLfzFwzqGKBTuaVztYu/g8sn+8Zc= | ||||||
| google.golang.org/grpc v1.69.2/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4= | google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= | ||||||
| google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk= | google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 h1:M1rk8KBnUsBDg1oPGHNCxG4vc1f49epmTO7xscSajMk= | ||||||
| google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= | google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= | ||||||
|  | google.golang.org/grpc v1.76.0 h1:UnVkv1+uMLYXoIz6o7chp59WfQUYA2ex/BXQ9rHZu7A= | ||||||
|  | google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c= | ||||||
|  | google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= | ||||||
|  | google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= | ||||||
| gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= | ||||||
| gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= | ||||||
| gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= | ||||||
|   | |||||||
							
								
								
									
										73
									
								
								hook_event.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										73
									
								
								hook_event.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,73 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  | 	"net" | ||||||
|  | 	"sync/atomic" | ||||||
|  | 	"time" | ||||||
|  |  | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	"go.unistack.org/micro/v3/logger" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | type hookEvent struct { | ||||||
|  | 	log          logger.Logger | ||||||
|  | 	connected    *atomic.Uint32 | ||||||
|  | 	fatalOnError bool | ||||||
|  | } | ||||||
|  |  | ||||||
|  | var ( | ||||||
|  | 	_ kgo.HookBrokerConnect           = &hookEvent{} | ||||||
|  | 	_ kgo.HookBrokerDisconnect        = &hookEvent{} | ||||||
|  | 	_ kgo.HookBrokerRead              = &hookEvent{} | ||||||
|  | 	_ kgo.HookBrokerWrite             = &hookEvent{} | ||||||
|  | 	_ kgo.HookGroupManageError        = &hookEvent{} | ||||||
|  | 	_ kgo.HookProduceRecordUnbuffered = &hookEvent{} | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnGroupManageError(err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnGroupManageError", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnBrokerConnect(_ kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnBrokerConnect", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnBrokerDisconnect(_ kgo.BrokerMetadata, _ net.Conn) {} | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnBrokerWrite(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnBrokerWrite", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnBrokerRead(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnBrokerRead", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnProduceRecordUnbuffered(_ *kgo.Record, err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnProduceRecordUnbuffered", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
							
								
								
									
										362
									
								
								hook_event_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										362
									
								
								hook_event_test.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,362 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  | 	"errors" | ||||||
|  | 	"io" | ||||||
|  | 	"net" | ||||||
|  | 	"os" | ||||||
|  | 	"testing" | ||||||
|  |  | ||||||
|  | 	"github.com/stretchr/testify/require" | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	"go.unistack.org/micro/v3/logger" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnGroupManageError(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnGroupManageError", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnGroupManageError(tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnBrokerConnect(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnBrokerConnect", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnBrokerConnect(kgo.BrokerMetadata{}, 0, nil, tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnBrokerWrite(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnBrokerWrite", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnBrokerWrite(kgo.BrokerMetadata{}, 0, 0, 0, 0, tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnBrokerRead(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnBrokerRead", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnBrokerRead(kgo.BrokerMetadata{}, 0, 0, 0, 0, tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnProduceRecordUnbuffered(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnProduceRecordUnbuffered", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnProduceRecordUnbuffered(&kgo.Record{}, tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // Mocks | ||||||
|  |  | ||||||
|  | type mockLogger struct { | ||||||
|  | 	errorIsCalled bool | ||||||
|  | 	errorMsg      string | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Init(...logger.Option) error { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Clone(...logger.Option) logger.Logger { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) V(logger.Level) bool { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Level(logger.Level) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Options() logger.Options { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Fields(...interface{}) logger.Logger { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Info(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Trace(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Debug(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Warn(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Error(ctx context.Context, msg string, args ...interface{}) { | ||||||
|  | 	m.errorIsCalled = true | ||||||
|  | 	m.errorMsg = msg | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Fatal(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Log(context.Context, logger.Level, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Name() string { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) String() string { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
							
								
								
									
										65
									
								
								kadmtest.go
									
									
									
									
									
								
							
							
						
						
									
										65
									
								
								kadmtest.go
									
									
									
									
									
								
							| @@ -1,65 +0,0 @@ | |||||||
| //go:build ignore |  | ||||||
|  |  | ||||||
| package main |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"context" |  | ||||||
| 	"fmt" |  | ||||||
| 	"os" |  | ||||||
| 	"time" |  | ||||||
|  |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kadm" |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kversion" |  | ||||||
|  |  | ||||||
| 	//"github.com/twmb/franz-go/pkg/sasl/scram" |  | ||||||
| 	"github.com/twmb/franz-go/pkg/sasl/plain" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| func die(msg string, args ...any) { |  | ||||||
| 	fmt.Fprintf(os.Stderr, msg, args...) |  | ||||||
| 	os.Exit(1) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func main() { |  | ||||||
| 	seeds := []string{"vm-kafka-ump01tn.mbrd.ru:9092", "vm-kafka-ump02tn.mbrd.ru:9092", "vm-kafka-ump03tn.mbrd.ru:9092"} |  | ||||||
|  |  | ||||||
| 	pass := "XXXXX" |  | ||||||
| 	user := "XXXXX" |  | ||||||
|  |  | ||||||
| 	var adminClient *kadm.Client |  | ||||||
| 	{ |  | ||||||
| 		client, err := kgo.NewClient( |  | ||||||
| 			kgo.SeedBrokers(seeds...), |  | ||||||
| 			// kgo.SASL((scram.Auth{User: user, Pass: pass}).AsSha512Mechanism()), |  | ||||||
| 			kgo.SASL((plain.Auth{User: user, Pass: pass}).AsMechanism()), |  | ||||||
|  |  | ||||||
| 			// Do not try to send requests newer than 2.4.0 to avoid breaking changes in the request struct. |  | ||||||
| 			// Sometimes there are breaking changes for newer versions where more properties are required to set. |  | ||||||
| 			kgo.MaxVersions(kversion.V2_4_0()), |  | ||||||
| 		) |  | ||||||
| 		if err != nil { |  | ||||||
| 			panic(err) |  | ||||||
| 		} |  | ||||||
| 		defer client.Close() |  | ||||||
|  |  | ||||||
| 		adminClient = kadm.NewClient(client) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |  | ||||||
| 	defer cancel() |  | ||||||
|  |  | ||||||
| 	dg, err := adminClient.DescribeGroups(ctx, "interestrate_loader") |  | ||||||
| 	if err != nil { |  | ||||||
| 		die("failed to describe group: %v", err) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	for _, m := range dg["interestrate_loader"].Members { |  | ||||||
| 		mc, _ := m.Assigned.AsConsumer() |  | ||||||
| 		for _, mt := range mc.Topics { |  | ||||||
| 			for _, p := range mt.Partitions { |  | ||||||
| 				fmt.Printf("client:%s\tpartitions: %d\n", m.ClientID, p) |  | ||||||
| 			} |  | ||||||
| 		} |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
							
								
								
									
										163
									
								
								kgo.go
									
									
									
									
									
								
							
							
						
						
									
										163
									
								
								kgo.go
									
									
									
									
									
								
							| @@ -6,13 +6,14 @@ import ( | |||||||
| 	"errors" | 	"errors" | ||||||
| 	"fmt" | 	"fmt" | ||||||
| 	"math/rand/v2" | 	"math/rand/v2" | ||||||
| 	"net/http" | 	"strconv" | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"sync" | 	"sync" | ||||||
| 	"sync/atomic" | 	"sync/atomic" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/google/uuid" | 	"github.com/google/uuid" | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kadm" | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	"github.com/twmb/franz-go/pkg/kmsg" | 	"github.com/twmb/franz-go/pkg/kmsg" | ||||||
| 	"go.unistack.org/micro/v3/broker" | 	"go.unistack.org/micro/v3/broker" | ||||||
| @@ -20,6 +21,7 @@ import ( | |||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v3/metadata" | ||||||
| 	"go.unistack.org/micro/v3/semconv" | 	"go.unistack.org/micro/v3/semconv" | ||||||
| 	"go.unistack.org/micro/v3/tracer" | 	"go.unistack.org/micro/v3/tracer" | ||||||
|  | 	mjitter "go.unistack.org/micro/v3/util/jitter" | ||||||
| 	mrand "go.unistack.org/micro/v3/util/rand" | 	mrand "go.unistack.org/micro/v3/util/rand" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| @@ -60,12 +62,14 @@ type Broker struct { | |||||||
| 	c         *kgo.Client | 	c         *kgo.Client | ||||||
| 	connected *atomic.Uint32 | 	connected *atomic.Uint32 | ||||||
|  |  | ||||||
|  | 	done chan struct{} | ||||||
|  |  | ||||||
| 	kopts []kgo.Opt | 	kopts []kgo.Opt | ||||||
| 	subs  []*Subscriber | 	subs  []*Subscriber | ||||||
|  |  | ||||||
| 	opts broker.Options | 	opts broker.Options | ||||||
|  | 	mu   sync.RWMutex | ||||||
|  |  | ||||||
| 	sync.RWMutex |  | ||||||
| 	init bool | 	init bool | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -110,10 +114,18 @@ func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, *ho | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	var fatalOnError bool | ||||||
|  | 	if k.opts.Context != nil { | ||||||
|  | 		if v, ok := k.opts.Context.Value(fatalOnErrorKey{}).(bool); ok && v { | ||||||
|  | 			fatalOnError = v | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	htracer := &hookTracer{group: group, clientID: clientID, tracer: k.opts.Tracer} | 	htracer := &hookTracer{group: group, clientID: clientID, tracer: k.opts.Tracer} | ||||||
| 	opts = append(opts, | 	opts = append(opts, | ||||||
| 		kgo.WithHooks(&hookMeter{meter: k.opts.Meter}), | 		kgo.WithHooks(&hookMeter{meter: k.opts.Meter}), | ||||||
| 		kgo.WithHooks(htracer), | 		kgo.WithHooks(htracer), | ||||||
|  | 		kgo.WithHooks(&hookEvent{log: k.opts.Logger, fatalOnError: fatalOnError, connected: k.connected}), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
| 	select { | 	select { | ||||||
| @@ -135,8 +147,28 @@ func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, *ho | |||||||
| 			} | 			} | ||||||
| 			return nil, nil, err | 			return nil, nil, err | ||||||
| 		} | 		} | ||||||
|  | 		k.connected.Store(1) | ||||||
|  |  | ||||||
|  | 		if fatalOnError { | ||||||
|  | 			go func() { | ||||||
|  | 				c := 3 | ||||||
|  | 				n := 0 | ||||||
|  | 				tc := mjitter.NewTicker(500*time.Millisecond, 1*time.Second) | ||||||
|  | 				defer tc.Stop() | ||||||
|  | 				for range tc.C { | ||||||
|  | 					if k.connected.Load() == 0 { | ||||||
|  | 						if n > c { | ||||||
|  | 							k.opts.Logger.Fatal(context.Background(), "broker fatal error") | ||||||
|  | 						} | ||||||
|  | 						n++ | ||||||
|  | 					} else { | ||||||
|  | 						n = 0 | ||||||
|  | 					} | ||||||
|  | 				} | ||||||
|  | 			}() | ||||||
|  | 		} | ||||||
|  | 		return c, htracer, nil | ||||||
| 	} | 	} | ||||||
| 	return c, htracer, nil |  | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *Broker) Connect(ctx context.Context) error { | func (k *Broker) Connect(ctx context.Context) error { | ||||||
| @@ -154,10 +186,72 @@ func (k *Broker) Connect(ctx context.Context) error { | |||||||
| 		return err | 		return err | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	k.Lock() | 	k.mu.Lock() | ||||||
| 	k.c = c | 	k.c = c | ||||||
| 	k.connected.Store(1) | 	k.connected.Store(1) | ||||||
| 	k.Unlock() | 	k.mu.Unlock() | ||||||
|  |  | ||||||
|  | 	exposeLag := false | ||||||
|  | 	if k.opts.Context != nil { | ||||||
|  | 		if v, ok := k.opts.Context.Value(exposeLagKey{}).(bool); ok && v { | ||||||
|  | 			exposeLag = v | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if exposeLag { | ||||||
|  | 		var mu sync.Mutex | ||||||
|  | 		var lastUpdate time.Time | ||||||
|  | 		type pl struct { | ||||||
|  | 			p string | ||||||
|  | 			l float64 | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		lag := make(map[string]map[string]pl) // topic => group => partition => lag | ||||||
|  | 		ac := kadm.NewClient(k.c) | ||||||
|  |  | ||||||
|  | 		updateStats := func() { | ||||||
|  | 			mu.Lock() | ||||||
|  | 			if time.Since(lastUpdate) < DefaultStatsInterval { | ||||||
|  | 				return | ||||||
|  | 			} | ||||||
|  | 			mu.Unlock() | ||||||
|  |  | ||||||
|  | 			k.mu.Lock() | ||||||
|  | 			groups := make([]string, 0, len(k.subs)) | ||||||
|  | 			for _, g := range k.subs { | ||||||
|  | 				groups = append(groups, g.opts.Group) | ||||||
|  | 			} | ||||||
|  | 			k.mu.Unlock() | ||||||
|  |  | ||||||
|  | 			dgls, err := ac.Lag(ctx, groups...) | ||||||
|  | 			if err != nil || !dgls.Ok() { | ||||||
|  | 				k.opts.Logger.Error(k.opts.Context, "kgo describe group lag error", err) | ||||||
|  | 				return | ||||||
|  | 			} | ||||||
|  |  | ||||||
|  | 			for gn, dgl := range dgls { | ||||||
|  | 				for tn, lmap := range dgl.Lag { | ||||||
|  | 					if _, ok := lag[tn]; !ok { | ||||||
|  | 						lag[tn] = make(map[string]pl) | ||||||
|  | 					} | ||||||
|  | 					for p, l := range lmap { | ||||||
|  | 						lag[tn][gn] = pl{p: strconv.Itoa(int(p)), l: float64(l.Lag)} | ||||||
|  | 					} | ||||||
|  | 				} | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		for tn, dg := range lag { | ||||||
|  | 			for gn, gl := range dg { | ||||||
|  | 				k.opts.Meter.Gauge(semconv.BrokerGroupLag, | ||||||
|  | 					func() float64 { updateStats(); return gl.l }, | ||||||
|  | 					"topic", tn, | ||||||
|  | 					"group", gn, | ||||||
|  | 					"partition", gl.p) | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
| @@ -175,8 +269,8 @@ func (k *Broker) Disconnect(ctx context.Context) error { | |||||||
| 	ctx, span = k.opts.Tracer.Start(ctx, "Disconnect") | 	ctx, span = k.opts.Tracer.Start(ctx, "Disconnect") | ||||||
| 	defer span.Finish() | 	defer span.Finish() | ||||||
|  |  | ||||||
| 	k.Lock() | 	k.mu.Lock() | ||||||
| 	defer k.Unlock() | 	defer k.mu.Unlock() | ||||||
| 	select { | 	select { | ||||||
| 	case <-nctx.Done(): | 	case <-nctx.Done(): | ||||||
| 		return nctx.Err() | 		return nctx.Err() | ||||||
| @@ -196,12 +290,13 @@ func (k *Broker) Disconnect(ctx context.Context) error { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	k.connected.Store(0) | 	k.connected.Store(0) | ||||||
|  | 	close(k.done) | ||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *Broker) Init(opts ...broker.Option) error { | func (k *Broker) Init(opts ...broker.Option) error { | ||||||
| 	k.Lock() | 	k.mu.Lock() | ||||||
| 	defer k.Unlock() | 	defer k.mu.Unlock() | ||||||
|  |  | ||||||
| 	if len(opts) == 0 && k.init { | 	if len(opts) == 0 && k.init { | ||||||
| 		return nil | 		return nil | ||||||
| @@ -249,18 +344,6 @@ func (k *Broker) Publish(ctx context.Context, topic string, msg *broker.Message, | |||||||
| } | } | ||||||
|  |  | ||||||
| func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { | func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { | ||||||
| 	k.Lock() |  | ||||||
| 	if k.connected.Load() == 0 { |  | ||||||
| 		c, _, err := k.connect(ctx, k.kopts...) |  | ||||||
| 		if err != nil { |  | ||||||
| 			k.Unlock() |  | ||||||
| 			return err |  | ||||||
| 		} |  | ||||||
| 		k.c = c |  | ||||||
| 		k.connected.Store(1) |  | ||||||
| 	} |  | ||||||
| 	k.Unlock() |  | ||||||
|  |  | ||||||
| 	options := broker.NewPublishOptions(opts...) | 	options := broker.NewPublishOptions(opts...) | ||||||
| 	records := make([]*kgo.Record, 0, len(msgs)) | 	records := make([]*kgo.Record, 0, len(msgs)) | ||||||
| 	var errs []string | 	var errs []string | ||||||
| @@ -279,14 +362,14 @@ func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...br | |||||||
|  |  | ||||||
| 	for _, msg := range msgs { | 	for _, msg := range msgs { | ||||||
| 		rec := &kgo.Record{Context: ctx, Key: key} | 		rec := &kgo.Record{Context: ctx, Key: key} | ||||||
|  |  | ||||||
| 		rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic) | 		rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic) | ||||||
| 		msg.Header.Del(metadata.HeaderTopic) | 		msg.Header.Del(metadata.HeaderTopic) | ||||||
|  |  | ||||||
| 		k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc() | 		k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc() | ||||||
| 		if options.BodyOnly || k.opts.Codec.String() == "noop" { | 		if options.BodyOnly || k.opts.Codec.String() == "noop" { | ||||||
| 			rec.Value = msg.Body | 			rec.Value = msg.Body | ||||||
| 			for k, v := range msg.Header { | 			setHeaders(rec, msg.Header) | ||||||
| 				rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: http.CanonicalHeaderKey(k), Value: []byte(v)}) |  | ||||||
| 			} |  | ||||||
| 		} else { | 		} else { | ||||||
| 			rec.Value, err = k.opts.Codec.Marshal(msg) | 			rec.Value, err = k.opts.Codec.Marshal(msg) | ||||||
| 			if err != nil { | 			if err != nil { | ||||||
| @@ -315,7 +398,9 @@ func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...br | |||||||
| 		return nil | 		return nil | ||||||
| 	} | 	} | ||||||
| 	ts := time.Now() | 	ts := time.Now() | ||||||
|  |  | ||||||
| 	results := k.c.ProduceSync(ctx, records...) | 	results := k.c.ProduceSync(ctx, records...) | ||||||
|  |  | ||||||
| 	te := time.Since(ts) | 	te := time.Since(ts) | ||||||
| 	for _, result := range results { | 	for _, result := range results { | ||||||
| 		k.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds()) | 		k.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds()) | ||||||
| @@ -374,13 +459,22 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	var fatalOnError bool | ||||||
|  | 	if k.opts.Context != nil { | ||||||
|  | 		if v, ok := k.opts.Context.Value(fatalOnErrorKey{}).(bool); ok && v { | ||||||
|  | 			fatalOnError = v | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	sub := &Subscriber{ | 	sub := &Subscriber{ | ||||||
| 		topic:     topic, | 		topic:        topic, | ||||||
| 		opts:      options, | 		opts:         options, | ||||||
| 		handler:   handler, | 		handler:      handler, | ||||||
| 		kopts:     k.opts, | 		kopts:        k.opts, | ||||||
| 		consumers: make(map[tp]*consumer), | 		consumers:    make(map[tp]*consumer), | ||||||
| 		done:      make(chan struct{}), | 		done:         make(chan struct{}), | ||||||
|  | 		fatalOnError: fatalOnError, | ||||||
|  | 		connected:    k.connected, | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	kopts := append(k.kopts, | 	kopts := append(k.kopts, | ||||||
| @@ -391,7 +485,9 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han | |||||||
| 		kgo.AutoCommitInterval(commitInterval), | 		kgo.AutoCommitInterval(commitInterval), | ||||||
| 		kgo.OnPartitionsAssigned(sub.assigned), | 		kgo.OnPartitionsAssigned(sub.assigned), | ||||||
| 		kgo.OnPartitionsRevoked(sub.revoked), | 		kgo.OnPartitionsRevoked(sub.revoked), | ||||||
|  | 		kgo.StopProducerOnDataLossDetected(), | ||||||
| 		kgo.OnPartitionsLost(sub.lost), | 		kgo.OnPartitionsLost(sub.lost), | ||||||
|  | 		kgo.AutoCommitCallback(sub.autocommit), | ||||||
| 		kgo.AutoCommitMarks(), | 		kgo.AutoCommitMarks(), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
| @@ -423,9 +519,9 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han | |||||||
|  |  | ||||||
| 	go sub.poll(ctx) | 	go sub.poll(ctx) | ||||||
|  |  | ||||||
| 	k.Lock() | 	k.mu.Lock() | ||||||
| 	k.subs = append(k.subs, sub) | 	k.subs = append(k.subs, sub) | ||||||
| 	k.Unlock() | 	k.mu.Unlock() | ||||||
| 	return sub, nil | 	return sub, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -452,7 +548,7 @@ func NewBroker(opts ...broker.Option) *Broker { | |||||||
| 		kgo.BlockRebalanceOnPoll(), | 		kgo.BlockRebalanceOnPoll(), | ||||||
| 		kgo.Balancers(kgo.CooperativeStickyBalancer()), | 		kgo.Balancers(kgo.CooperativeStickyBalancer()), | ||||||
| 		kgo.FetchIsolationLevel(kgo.ReadUncommitted()), | 		kgo.FetchIsolationLevel(kgo.ReadUncommitted()), | ||||||
| 		kgo.UnknownTopicRetries(0), | 		kgo.UnknownTopicRetries(1), | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	if options.Context != nil { | 	if options.Context != nil { | ||||||
| @@ -465,5 +561,6 @@ func NewBroker(opts ...broker.Option) *Broker { | |||||||
| 		connected: &atomic.Uint32{}, | 		connected: &atomic.Uint32{}, | ||||||
| 		opts:      options, | 		opts:      options, | ||||||
| 		kopts:     kopts, | 		kopts:     kopts, | ||||||
|  | 		done:      make(chan struct{}), | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|   | |||||||
							
								
								
									
										103
									
								
								kgo_test.go
									
									
									
									
									
								
							
							
						
						
									
										103
									
								
								kgo_test.go
									
									
									
									
									
								
							| @@ -2,7 +2,6 @@ package kgo_test | |||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"context" | 	"context" | ||||||
| 	"fmt" |  | ||||||
| 	"os" | 	"os" | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"sync/atomic" | 	"sync/atomic" | ||||||
| @@ -13,14 +12,15 @@ import ( | |||||||
| 	kgo "go.unistack.org/micro-broker-kgo/v3" | 	kgo "go.unistack.org/micro-broker-kgo/v3" | ||||||
| 	"go.unistack.org/micro/v3/broker" | 	"go.unistack.org/micro/v3/broker" | ||||||
| 	"go.unistack.org/micro/v3/logger" | 	"go.unistack.org/micro/v3/logger" | ||||||
|  | 	"go.unistack.org/micro/v3/logger/slog" | ||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v3/metadata" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var ( | var ( | ||||||
| 	msgcnt   = int64(12000000) | 	msgcnt   = int64(1200) | ||||||
| 	group    = "38" | 	group    = "38" | ||||||
| 	prefill  = false | 	prefill  = true | ||||||
| 	loglevel = logger.InfoLevel | 	loglevel = logger.DebugLevel | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var bm = &broker.Message{ | var bm = &broker.Message{ | ||||||
| @@ -28,7 +28,99 @@ var bm = &broker.Message{ | |||||||
| 	Body:   []byte(`"body"`), | 	Body:   []byte(`"body"`), | ||||||
| } | } | ||||||
|  |  | ||||||
|  | func TestFail(t *testing.T) { | ||||||
|  | 	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { | ||||||
|  | 		t.Skip() | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	logger.DefaultLogger = slog.NewLogger() | ||||||
|  | 	if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  | 	ctx := context.Background() | ||||||
|  |  | ||||||
|  | 	var addrs []string | ||||||
|  | 	if addr := os.Getenv("BROKER_ADDRS"); len(addr) == 0 { | ||||||
|  | 		addrs = []string{"127.0.0.1:9092"} | ||||||
|  | 	} else { | ||||||
|  | 		addrs = strings.Split(addr, ",") | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	b := kgo.NewBroker( | ||||||
|  | 		broker.Addrs(addrs...), | ||||||
|  | 		kgo.CommitInterval(5*time.Second), | ||||||
|  | 		kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024), | ||||||
|  | 			kg.AllowAutoTopicCreation(), | ||||||
|  | 		), | ||||||
|  | 	) | ||||||
|  |  | ||||||
|  | 	t.Logf("broker init") | ||||||
|  | 	if err := b.Init(); err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	t.Logf("broker connect") | ||||||
|  | 	if err := b.Connect(ctx); err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	defer func() { | ||||||
|  | 		t.Logf("broker disconnect") | ||||||
|  | 		if err := b.Disconnect(ctx); err != nil { | ||||||
|  | 			t.Fatal(err) | ||||||
|  | 		} | ||||||
|  | 	}() | ||||||
|  |  | ||||||
|  | 	t.Logf("broker health %v", b.Health()) | ||||||
|  | 	msgs := make([]*broker.Message, 0, msgcnt) | ||||||
|  | 	for i := int64(0); i < msgcnt; i++ { | ||||||
|  | 		msgs = append(msgs, bm) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, msg := range msgs { | ||||||
|  | 		t.Logf("broker publish") | ||||||
|  | 		if err := b.Publish(ctx, "test", msg); err != nil { | ||||||
|  | 			t.Fatal(err) | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | 	//	t.Skip() | ||||||
|  |  | ||||||
|  | 	idx := int64(0) | ||||||
|  | 	fn := func(msg broker.Event) error { | ||||||
|  | 		atomic.AddInt64(&idx, 1) | ||||||
|  | 		time.Sleep(500 * time.Millisecond) | ||||||
|  | 		t.Logf("ack") | ||||||
|  | 		return msg.Ack() | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	sub, err := b.Subscribe(ctx, "test", fn, | ||||||
|  | 		broker.SubscribeAutoAck(true), | ||||||
|  | 		broker.SubscribeGroup(group), | ||||||
|  | 		broker.SubscribeBodyOnly(true)) | ||||||
|  | 	if err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  | 	defer func() { | ||||||
|  | 		if err := sub.Unsubscribe(ctx); err != nil { | ||||||
|  | 			t.Fatal(err) | ||||||
|  | 		} | ||||||
|  | 	}() | ||||||
|  |  | ||||||
|  | 	for { | ||||||
|  | 		t.Logf("health check") | ||||||
|  | 		if !b.Health() { | ||||||
|  | 			t.Logf("health works") | ||||||
|  | 			break | ||||||
|  | 		} | ||||||
|  | 		time.Sleep(1 * time.Second) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
| func TestConnect(t *testing.T) { | func TestConnect(t *testing.T) { | ||||||
|  | 	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { | ||||||
|  | 		t.Skip() | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	var addrs []string | 	var addrs []string | ||||||
| 	ctx := context.TODO() | 	ctx := context.TODO() | ||||||
| 	b := kgo.NewBroker( | 	b := kgo.NewBroker( | ||||||
| @@ -67,6 +159,7 @@ func TestPubSub(t *testing.T) { | |||||||
| 		kgo.CommitInterval(5*time.Second), | 		kgo.CommitInterval(5*time.Second), | ||||||
| 		kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024)), | 		kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024)), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
| 	if err := b.Init(); err != nil { | 	if err := b.Init(); err != nil { | ||||||
| 		t.Fatal(err) | 		t.Fatal(err) | ||||||
| 	} | 	} | ||||||
| @@ -124,7 +217,7 @@ func TestPubSub(t *testing.T) { | |||||||
| 				if prc := atomic.LoadInt64(&idx); prc == msgcnt { | 				if prc := atomic.LoadInt64(&idx); prc == msgcnt { | ||||||
| 					close(done) | 					close(done) | ||||||
| 				} else { | 				} else { | ||||||
| 					fmt.Printf("processed %v\n", prc) | 					t.Logf("processed %v\n", prc) | ||||||
| 				} | 				} | ||||||
| 			case <-ticker.C: | 			case <-ticker.C: | ||||||
| 				close(done) | 				close(done) | ||||||
|   | |||||||
							
								
								
									
										32
									
								
								meter.go
									
									
									
									
									
								
							
							
						
						
									
										32
									
								
								meter.go
									
									
									
									
									
								
							| @@ -32,27 +32,27 @@ var ( | |||||||
| ) | ) | ||||||
|  |  | ||||||
| const ( | const ( | ||||||
| 	metricBrokerConnects    = "broker_connects_total" | 	metricBrokerConnects    = "micro_broker_connects_total" | ||||||
| 	metricBrokerDisconnects = "broker_disconnects_total" | 	metricBrokerDisconnects = "micro_broker_disconnects_total" | ||||||
|  |  | ||||||
| 	metricBrokerWriteErrors        = "broker_write_errors_total" | 	metricBrokerWriteErrors        = "micro_broker_write_errors_total" | ||||||
| 	metricBrokerWriteBytes         = "broker_write_bytes_total" | 	metricBrokerWriteBytes         = "micro_broker_write_bytes_total" | ||||||
| 	metricBrokerWriteWaitLatencies = "broker_write_wait_latencies" | 	metricBrokerWriteWaitLatencies = "micro_broker_write_wait_latencies" | ||||||
| 	metricBrokerWriteLatencies     = "broker_write_latencies" | 	metricBrokerWriteLatencies     = "micro_broker_write_latencies" | ||||||
|  |  | ||||||
| 	metricBrokerReadErrors        = "broker_read_errors_total" | 	metricBrokerReadErrors        = "micro_broker_read_errors_total" | ||||||
| 	metricBrokerReadBytes         = "broker_read_bytes_total" | 	metricBrokerReadBytes         = "micro_broker_read_bytes_total" | ||||||
| 	metricBrokerReadWaitLatencies = "broker_read_wait_latencies" | 	metricBrokerReadWaitLatencies = "micro_broker_read_wait_latencies" | ||||||
| 	metricBrokerReadLatencies     = "broker_read_latencies" | 	metricBrokerReadLatencies     = "micro_broker_read_latencies" | ||||||
|  |  | ||||||
| 	metricBrokerThrottleLatencies = "broker_throttle_latencies" | 	metricBrokerThrottleLatencies = "micro_broker_throttle_latencies" | ||||||
|  |  | ||||||
| 	metricBrokerProduceBytesCompressed   = "broker_produce_bytes_compressed_total" | 	metricBrokerProduceBytesCompressed   = "micro_broker_produce_bytes_compressed_total" | ||||||
| 	metricBrokerProduceBytesUncompressed = "broker_produce_bytes_uncompressed_total" | 	metricBrokerProduceBytesUncompressed = "micro_broker_produce_bytes_uncompressed_total" | ||||||
| 	metricBrokerFetchBytesCompressed     = "broker_consume_bytes_compressed_total" | 	metricBrokerFetchBytesCompressed     = "micro_broker_consume_bytes_compressed_total" | ||||||
| 	metricBrokerFetchBytesUncompressed   = "broker_consume_bytes_uncompressed_total" | 	metricBrokerFetchBytesUncompressed   = "micro_broker_consume_bytes_uncompressed_total" | ||||||
|  |  | ||||||
| 	metricBrokerGroupErrors = "broker_group_errors_total" | 	metricBrokerGroupErrors = "micro_broker_group_errors_total" | ||||||
|  |  | ||||||
| 	labelNode    = "node_id" | 	labelNode    = "node_id" | ||||||
| 	labelSuccess = "success" | 	labelSuccess = "success" | ||||||
|   | |||||||
							
								
								
									
										20
									
								
								options.go
									
									
									
									
									
								
							
							
						
						
									
										20
									
								
								options.go
									
									
									
									
									
								
							| @@ -15,7 +15,7 @@ var ( | |||||||
| 	DefaultCommitInterval = 5 * time.Second | 	DefaultCommitInterval = 5 * time.Second | ||||||
|  |  | ||||||
| 	// DefaultStatsInterval specifies how fast check consumer lag | 	// DefaultStatsInterval specifies how fast check consumer lag | ||||||
| 	DefaultStatsInterval = 5 * time.Second | 	DefaultStatsInterval = 30 * time.Second | ||||||
|  |  | ||||||
| 	// DefaultSubscribeMaxInflight specifies how much messages keep inflight | 	// DefaultSubscribeMaxInflight specifies how much messages keep inflight | ||||||
| 	DefaultSubscribeMaxInflight = 100 | 	DefaultSubscribeMaxInflight = 100 | ||||||
| @@ -72,6 +72,12 @@ func SubscribeOptions(opts ...kgo.Opt) broker.SubscribeOption { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|  | type fatalOnErrorKey struct{} | ||||||
|  |  | ||||||
|  | func FatalOnError(b bool) broker.Option { | ||||||
|  | 	return broker.SetOption(fatalOnErrorKey{}, b) | ||||||
|  | } | ||||||
|  |  | ||||||
| type clientIDKey struct{} | type clientIDKey struct{} | ||||||
|  |  | ||||||
| func ClientID(id string) broker.Option { | func ClientID(id string) broker.Option { | ||||||
| @@ -98,6 +104,11 @@ func SubscribeMaxInFlight(n int) broker.SubscribeOption { | |||||||
| 	return broker.SetSubscribeOption(subscribeMaxInflightKey{}, n) | 	return broker.SetSubscribeOption(subscribeMaxInflightKey{}, n) | ||||||
| } | } | ||||||
|  |  | ||||||
|  | // SubscribeMaxInFlight max queued messages | ||||||
|  | func SubscribeFatalOnError(b bool) broker.SubscribeOption { | ||||||
|  | 	return broker.SetSubscribeOption(fatalOnErrorKey{}, b) | ||||||
|  | } | ||||||
|  |  | ||||||
| type publishPromiseKey struct{} | type publishPromiseKey struct{} | ||||||
|  |  | ||||||
| // PublishPromise set the kafka promise func for Produce | // PublishPromise set the kafka promise func for Produce | ||||||
| @@ -109,3 +120,10 @@ func PublishPromise(fn func(*kgo.Record, error)) broker.PublishOption { | |||||||
| func ClientPublishPromise(fn func(*kgo.Record, error)) client.PublishOption { | func ClientPublishPromise(fn func(*kgo.Record, error)) client.PublishOption { | ||||||
| 	return client.SetPublishOption(publishPromiseKey{}, fn) | 	return client.SetPublishOption(publishPromiseKey{}, fn) | ||||||
| } | } | ||||||
|  |  | ||||||
|  | type exposeLagKey struct{} | ||||||
|  |  | ||||||
|  | // ExposeLag enabled subscriber lag via [meter.Meter] | ||||||
|  | func ExposeLag(b bool) broker.Option { | ||||||
|  | 	return broker.SetOption(exposeLagKey{}, b) | ||||||
|  | } | ||||||
|   | |||||||
							
								
								
									
										154
									
								
								subscriber.go
									
									
									
									
									
								
							
							
						
						
									
										154
									
								
								subscriber.go
									
									
									
									
									
								
							| @@ -5,10 +5,11 @@ import ( | |||||||
| 	"fmt" | 	"fmt" | ||||||
| 	"strconv" | 	"strconv" | ||||||
| 	"sync" | 	"sync" | ||||||
|  | 	"sync/atomic" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kadm" |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kmsg" | ||||||
| 	"go.unistack.org/micro/v3/broker" | 	"go.unistack.org/micro/v3/broker" | ||||||
| 	"go.unistack.org/micro/v3/logger" | 	"go.unistack.org/micro/v3/logger" | ||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v3/metadata" | ||||||
| @@ -24,13 +25,15 @@ type tp struct { | |||||||
| type consumer struct { | type consumer struct { | ||||||
| 	topic string | 	topic string | ||||||
|  |  | ||||||
| 	c *kgo.Client | 	c         *kgo.Client | ||||||
| 	htracer   *hookTracer | 	htracer   *hookTracer | ||||||
|  | 	connected *atomic.Uint32 | ||||||
|  |  | ||||||
|  | 	quit chan struct{} | ||||||
|  | 	done chan struct{} | ||||||
|  | 	recs chan kgo.FetchTopicPartition | ||||||
|  |  | ||||||
| 	handler broker.Handler | 	handler broker.Handler | ||||||
| 	quit    chan struct{} |  | ||||||
| 	done    chan struct{} |  | ||||||
| 	recs    chan kgo.FetchTopicPartition |  | ||||||
|  |  | ||||||
| 	kopts broker.Options | 	kopts broker.Options | ||||||
| 	opts  broker.SubscribeOptions | 	opts  broker.SubscribeOptions | ||||||
| @@ -39,18 +42,25 @@ type consumer struct { | |||||||
| } | } | ||||||
|  |  | ||||||
| type Subscriber struct { | type Subscriber struct { | ||||||
|  | 	topic string | ||||||
|  |  | ||||||
| 	consumers map[tp]*consumer | 	consumers map[tp]*consumer | ||||||
|  |  | ||||||
| 	c         *kgo.Client | 	c         *kgo.Client | ||||||
| 	htracer   *hookTracer | 	htracer   *hookTracer | ||||||
| 	topic     string | 	connected *atomic.Uint32 | ||||||
|  |  | ||||||
| 	handler broker.Handler | 	handler broker.Handler | ||||||
| 	done    chan struct{} |  | ||||||
| 	kopts   broker.Options | 	done chan struct{} | ||||||
| 	opts    broker.SubscribeOptions |  | ||||||
|  | 	kopts broker.Options | ||||||
|  | 	opts  broker.SubscribeOptions | ||||||
|  |  | ||||||
|  | 	closed       bool | ||||||
|  | 	fatalOnError bool | ||||||
|  |  | ||||||
| 	sync.RWMutex | 	sync.RWMutex | ||||||
| 	closed bool |  | ||||||
| } | } | ||||||
|  |  | ||||||
| func (s *Subscriber) Client() *kgo.Client { | func (s *Subscriber) Client() *kgo.Client { | ||||||
| @@ -86,46 +96,13 @@ func (s *Subscriber) Unsubscribe(ctx context.Context) error { | |||||||
|  |  | ||||||
| func (s *Subscriber) poll(ctx context.Context) { | func (s *Subscriber) poll(ctx context.Context) { | ||||||
| 	maxInflight := DefaultSubscribeMaxInflight | 	maxInflight := DefaultSubscribeMaxInflight | ||||||
|  |  | ||||||
| 	if s.opts.Context != nil { | 	if s.opts.Context != nil { | ||||||
| 		if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok { | 		if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok { | ||||||
| 			maxInflight = n | 			maxInflight = n | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	go func() { |  | ||||||
| 		ac := kadm.NewClient(s.c) |  | ||||||
| 		ticker := time.NewTicker(DefaultStatsInterval) |  | ||||||
|  |  | ||||||
| 		for { |  | ||||||
| 			select { |  | ||||||
| 			case <-ctx.Done(): |  | ||||||
| 				ticker.Stop() |  | ||||||
| 				return |  | ||||||
| 			case <-ticker.C: |  | ||||||
| 				dgls, err := ac.Lag(ctx, s.opts.Group) |  | ||||||
| 				if err != nil || !dgls.Ok() { |  | ||||||
| 					continue |  | ||||||
| 				} |  | ||||||
|  |  | ||||||
| 				dgl, ok := dgls[s.opts.Group] |  | ||||||
| 				if !ok { |  | ||||||
| 					continue |  | ||||||
| 				} |  | ||||||
| 				lmap, ok := dgl.Lag[s.topic] |  | ||||||
| 				if !ok { |  | ||||||
| 					continue |  | ||||||
| 				} |  | ||||||
|  |  | ||||||
| 				s.Lock() |  | ||||||
| 				for p, l := range lmap { |  | ||||||
| 					s.kopts.Meter.Counter(semconv.BrokerGroupLag, "topic", s.topic, "group", s.opts.Group, "partition", strconv.Itoa(int(p)), "lag", strconv.Itoa(int(l.Lag))) |  | ||||||
| 				} |  | ||||||
| 				s.Unlock() |  | ||||||
|  |  | ||||||
| 			} |  | ||||||
| 		} |  | ||||||
| 	}() |  | ||||||
|  |  | ||||||
| 	for { | 	for { | ||||||
| 		select { | 		select { | ||||||
| 		case <-ctx.Done(): | 		case <-ctx.Done(): | ||||||
| @@ -140,12 +117,16 @@ func (s *Subscriber) poll(ctx context.Context) { | |||||||
| 				return | 				return | ||||||
| 			} | 			} | ||||||
| 			fetches.EachError(func(t string, p int32, err error) { | 			fetches.EachError(func(t string, p int32, err error) { | ||||||
| 				s.kopts.Logger.Fatal(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err) | 				if kgo.IsRetryableBrokerErr(err) { | ||||||
|  | 					s.kopts.Logger.Error(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err) | ||||||
|  | 				} else { | ||||||
|  | 					s.kopts.Logger.Fatal(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err) | ||||||
|  | 				} | ||||||
| 			}) | 			}) | ||||||
|  |  | ||||||
| 			fetches.EachPartition(func(p kgo.FetchTopicPartition) { | 			fetches.EachPartition(func(p kgo.FetchTopicPartition) { | ||||||
| 				nTp := tp{p.Topic, p.Partition} | 				tps := tp{p.Topic, p.Partition} | ||||||
| 				s.consumers[nTp].recs <- p | 				s.consumers[tps].recs <- p | ||||||
| 			}) | 			}) | ||||||
| 			s.c.AllowRebalance() | 			s.c.AllowRebalance() | ||||||
| 		} | 		} | ||||||
| @@ -158,9 +139,12 @@ func (s *Subscriber) killConsumers(ctx context.Context, lost map[string][]int32) | |||||||
|  |  | ||||||
| 	for topic, partitions := range lost { | 	for topic, partitions := range lost { | ||||||
| 		for _, partition := range partitions { | 		for _, partition := range partitions { | ||||||
| 			nTp := tp{topic, partition} | 			tps := tp{topic, partition} | ||||||
| 			pc := s.consumers[nTp] | 			pc, ok := s.consumers[tps] | ||||||
| 			delete(s.consumers, nTp) | 			if !ok { | ||||||
|  | 				continue | ||||||
|  | 			} | ||||||
|  | 			delete(s.consumers, tps) | ||||||
| 			close(pc.quit) | 			close(pc.quit) | ||||||
| 			if s.kopts.Logger.V(logger.DebugLevel) { | 			if s.kopts.Logger.V(logger.DebugLevel) { | ||||||
| 				s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] waiting for work to finish topic %s partition %d", topic, partition)) | 				s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] waiting for work to finish topic %s partition %d", topic, partition)) | ||||||
| @@ -171,11 +155,21 @@ func (s *Subscriber) killConsumers(ctx context.Context, lost map[string][]int32) | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) autocommit(_ *kgo.Client, _ *kmsg.OffsetCommitRequest, _ *kmsg.OffsetCommitResponse, err error) { | ||||||
|  | 	if err != nil { | ||||||
|  | 		//		s.connected.Store(0) | ||||||
|  | 		if s.fatalOnError { | ||||||
|  | 			s.kopts.Logger.Fatal(context.TODO(), "kgo.AutoCommitCallback error", err) | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
| func (s *Subscriber) lost(ctx context.Context, _ *kgo.Client, lost map[string][]int32) { | func (s *Subscriber) lost(ctx context.Context, _ *kgo.Client, lost map[string][]int32) { | ||||||
| 	if s.kopts.Logger.V(logger.DebugLevel) { | 	if s.kopts.Logger.V(logger.ErrorLevel) { | ||||||
| 		s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] lost %#+v", lost)) | 		s.kopts.Logger.Error(ctx, fmt.Sprintf("[kgo] lost %#+v", lost)) | ||||||
| 	} | 	} | ||||||
| 	s.killConsumers(ctx, lost) | 	s.killConsumers(ctx, lost) | ||||||
|  | 	// s.connected.Store(0) | ||||||
| } | } | ||||||
|  |  | ||||||
| func (s *Subscriber) revoked(ctx context.Context, c *kgo.Client, revoked map[string][]int32) { | func (s *Subscriber) revoked(ctx context.Context, c *kgo.Client, revoked map[string][]int32) { | ||||||
| @@ -185,6 +179,7 @@ func (s *Subscriber) revoked(ctx context.Context, c *kgo.Client, revoked map[str | |||||||
| 	s.killConsumers(ctx, revoked) | 	s.killConsumers(ctx, revoked) | ||||||
| 	if err := c.CommitMarkedOffsets(ctx); err != nil { | 	if err := c.CommitMarkedOffsets(ctx); err != nil { | ||||||
| 		s.kopts.Logger.Error(ctx, "[kgo] revoked CommitMarkedOffsets error", err) | 		s.kopts.Logger.Error(ctx, "[kgo] revoked CommitMarkedOffsets error", err) | ||||||
|  | 		// s.connected.Store(0) | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -202,6 +197,7 @@ func (s *Subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[str | |||||||
| 				handler:   s.handler, | 				handler:   s.handler, | ||||||
| 				kopts:     s.kopts, | 				kopts:     s.kopts, | ||||||
| 				opts:      s.opts, | 				opts:      s.opts, | ||||||
|  | 				connected: s.connected, | ||||||
| 			} | 			} | ||||||
| 			s.Lock() | 			s.Lock() | ||||||
| 			s.consumers[tp{topic, partition}] = pc | 			s.consumers[tp{topic, partition}] = pc | ||||||
| @@ -243,16 +239,27 @@ func (pc *consumer) consume() { | |||||||
| 				for _, hdr := range record.Headers { | 				for _, hdr := range record.Headers { | ||||||
| 					p.msg.Header.Set(hdr.Key, string(hdr.Value)) | 					p.msg.Header.Set(hdr.Key, string(hdr.Value)) | ||||||
| 				} | 				} | ||||||
|  | 				p.msg.Header.Set("Micro-Offset", strconv.FormatInt(record.Offset, 10)) | ||||||
|  | 				p.msg.Header.Set("Micro-Partition", strconv.FormatInt(int64(record.Partition), 10)) | ||||||
|  | 				p.msg.Header.Set("Micro-Topic", record.Topic) | ||||||
|  | 				p.msg.Header.Set("Micro-Key", string(record.Key)) | ||||||
|  | 				p.msg.Header.Set("Micro-Timestamp", strconv.FormatInt(record.Timestamp.Unix(), 10)) | ||||||
| 				if pc.kopts.Codec.String() == "noop" { | 				if pc.kopts.Codec.String() == "noop" { | ||||||
| 					p.msg.Body = record.Value | 					p.msg.Body = record.Value | ||||||
| 				} else if pc.opts.BodyOnly { | 				} else if pc.opts.BodyOnly { | ||||||
| 					p.msg.Body = record.Value | 					p.msg.Body = record.Value | ||||||
| 				} else { | 				} else { | ||||||
| 					sp.AddEvent("codec unmarshal start") | 					if sp != nil { | ||||||
|  | 						sp.AddEvent("codec unmarshal start") | ||||||
|  | 					} | ||||||
| 					err := pc.kopts.Codec.Unmarshal(record.Value, p.msg) | 					err := pc.kopts.Codec.Unmarshal(record.Value, p.msg) | ||||||
| 					sp.AddEvent("codec unmarshal stop") | 					if sp != nil { | ||||||
|  | 						sp.AddEvent("codec unmarshal stop") | ||||||
|  | 					} | ||||||
| 					if err != nil { | 					if err != nil { | ||||||
| 						sp.SetStatus(tracer.SpanStatusError, err.Error()) | 						if sp != nil { | ||||||
|  | 							sp.SetStatus(tracer.SpanStatusError, err.Error()) | ||||||
|  | 						} | ||||||
| 						pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc() | 						pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc() | ||||||
| 						p.err = err | 						p.err = err | ||||||
| 						p.msg.Body = record.Value | 						p.msg.Body = record.Value | ||||||
| @@ -263,6 +270,7 @@ func (pc *consumer) consume() { | |||||||
| 								pc.c.MarkCommitRecords(record) | 								pc.c.MarkCommitRecords(record) | ||||||
| 							} else { | 							} else { | ||||||
| 								eventPool.Put(p) | 								eventPool.Put(p) | ||||||
|  | 								//								pc.connected.Store(0) | ||||||
| 								pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?") | 								pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?") | ||||||
| 								return | 								return | ||||||
| 							} | 							} | ||||||
| @@ -279,18 +287,27 @@ func (pc *consumer) consume() { | |||||||
| 						pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | 						pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | ||||||
| 						pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | 						pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | ||||||
| 						eventPool.Put(p) | 						eventPool.Put(p) | ||||||
|  | 						//						pc.connected.Store(0) | ||||||
| 						pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] Unmarshal err not handled wtf?") | 						pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] Unmarshal err not handled wtf?") | ||||||
| 						sp.Finish() | 						if sp != nil { | ||||||
|  | 							sp.Finish() | ||||||
|  | 						} | ||||||
| 						return | 						return | ||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
| 				sp.AddEvent("handler start") | 				if sp != nil { | ||||||
|  | 					sp.AddEvent("handler start") | ||||||
|  | 				} | ||||||
| 				err := pc.handler(p) | 				err := pc.handler(p) | ||||||
| 				sp.AddEvent("handler stop") | 				if sp != nil { | ||||||
|  | 					sp.AddEvent("handler stop") | ||||||
|  | 				} | ||||||
| 				if err == nil { | 				if err == nil { | ||||||
| 					pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "success").Inc() | 					pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "success").Inc() | ||||||
| 				} else { | 				} else { | ||||||
| 					sp.SetStatus(tracer.SpanStatusError, err.Error()) | 					if sp != nil { | ||||||
|  | 						sp.SetStatus(tracer.SpanStatusError, err.Error()) | ||||||
|  | 					} | ||||||
| 					pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc() | 					pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc() | ||||||
| 				} | 				} | ||||||
| 				pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec() | 				pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec() | ||||||
| @@ -299,9 +316,13 @@ func (pc *consumer) consume() { | |||||||
| 				} else if err != nil { | 				} else if err != nil { | ||||||
| 					p.err = err | 					p.err = err | ||||||
| 					if eh != nil { | 					if eh != nil { | ||||||
| 						sp.AddEvent("error handler start") | 						if sp != nil { | ||||||
|  | 							sp.AddEvent("error handler start") | ||||||
|  | 						} | ||||||
| 						_ = eh(p) | 						_ = eh(p) | ||||||
| 						sp.AddEvent("error handler stop") | 						if sp != nil { | ||||||
|  | 							sp.AddEvent("error handler stop") | ||||||
|  | 						} | ||||||
| 					} else { | 					} else { | ||||||
| 						if pc.kopts.Logger.V(logger.ErrorLevel) { | 						if pc.kopts.Logger.V(logger.ErrorLevel) { | ||||||
| 							pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: subscriber error", err) | 							pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: subscriber error", err) | ||||||
| @@ -316,12 +337,17 @@ func (pc *consumer) consume() { | |||||||
| 					pc.c.MarkCommitRecords(record) | 					pc.c.MarkCommitRecords(record) | ||||||
| 				} else { | 				} else { | ||||||
| 					eventPool.Put(p) | 					eventPool.Put(p) | ||||||
|  | 					//					pc.connected.Store(0) | ||||||
| 					pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?") | 					pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?") | ||||||
| 					sp.SetStatus(tracer.SpanStatusError, "ErrLostMessage") | 					if sp != nil { | ||||||
| 					sp.Finish() | 						sp.SetStatus(tracer.SpanStatusError, "ErrLostMessage") | ||||||
|  | 						sp.Finish() | ||||||
|  | 					} | ||||||
| 					return | 					return | ||||||
| 				} | 				} | ||||||
| 				sp.Finish() | 				if sp != nil { | ||||||
|  | 					sp.Finish() | ||||||
|  | 				} | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|   | |||||||
							
								
								
									
										23
									
								
								tracer.go
									
									
									
									
									
								
							
							
						
						
									
										23
									
								
								tracer.go
									
									
									
									
									
								
							| @@ -32,6 +32,9 @@ var ( | |||||||
| // the record's context, so it can be ended in the OnProduceRecordUnbuffered | // the record's context, so it can be ended in the OnProduceRecordUnbuffered | ||||||
| // hook. | // hook. | ||||||
| func (m *hookTracer) OnProduceRecordBuffered(r *kgo.Record) { | func (m *hookTracer) OnProduceRecordBuffered(r *kgo.Record) { | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
| 	// Set up span options. | 	// Set up span options. | ||||||
| 	attrs := []interface{}{ | 	attrs := []interface{}{ | ||||||
| 		messagingSystem, | 		messagingSystem, | ||||||
| @@ -68,7 +71,7 @@ func (m *hookTracer) OnProduceRecordBuffered(r *kgo.Record) { | |||||||
| 		r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...) | 		r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	setHeaders(r, omd) | 	setHeaders(r, omd, metadata.HeaderContentType) | ||||||
| } | } | ||||||
|  |  | ||||||
| // OnProduceRecordUnbuffered continues and ends the "publish" span for an | // OnProduceRecordUnbuffered continues and ends the "publish" span for an | ||||||
| @@ -77,6 +80,9 @@ func (m *hookTracer) OnProduceRecordBuffered(r *kgo.Record) { | |||||||
| // It sets attributes with values unset when producing and records any error | // It sets attributes with values unset when producing and records any error | ||||||
| // that occurred during the publish operation. | // that occurred during the publish operation. | ||||||
| func (m *hookTracer) OnProduceRecordUnbuffered(r *kgo.Record, err error) { | func (m *hookTracer) OnProduceRecordUnbuffered(r *kgo.Record, err error) { | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
| 	if span, ok := tracer.SpanFromContext(r.Context); ok { | 	if span, ok := tracer.SpanFromContext(r.Context); ok { | ||||||
| 		span.AddLabels( | 		span.AddLabels( | ||||||
| 			semconv.MessagingKafkaDestinationPartition(int(r.Partition)), | 			semconv.MessagingKafkaDestinationPartition(int(r.Partition)), | ||||||
| @@ -96,6 +102,9 @@ func (m *hookTracer) OnProduceRecordUnbuffered(r *kgo.Record, err error) { | |||||||
| // OnFetchRecordUnbuffered hook and can be used in downstream consumer | // OnFetchRecordUnbuffered hook and can be used in downstream consumer | ||||||
| // processing. | // processing. | ||||||
| func (m *hookTracer) OnFetchRecordBuffered(r *kgo.Record) { | func (m *hookTracer) OnFetchRecordBuffered(r *kgo.Record) { | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
| 	// Set up the span options. | 	// Set up the span options. | ||||||
| 	attrs := []interface{}{ | 	attrs := []interface{}{ | ||||||
| 		messagingSystem, | 		messagingSystem, | ||||||
| @@ -135,12 +144,15 @@ func (m *hookTracer) OnFetchRecordBuffered(r *kgo.Record) { | |||||||
| 		r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...) | 		r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	setHeaders(r, omd) | 	setHeaders(r, omd, metadata.HeaderContentType) | ||||||
| } | } | ||||||
|  |  | ||||||
| // OnFetchRecordUnbuffered continues and ends the "receive" span for an | // OnFetchRecordUnbuffered continues and ends the "receive" span for an | ||||||
| // unbuffered record. | // unbuffered record. | ||||||
| func (m *hookTracer) OnFetchRecordUnbuffered(r *kgo.Record, _ bool) { | func (m *hookTracer) OnFetchRecordUnbuffered(r *kgo.Record, _ bool) { | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
| 	span, _ := tracer.SpanFromContext(r.Context) | 	span, _ := tracer.SpanFromContext(r.Context) | ||||||
| 	span.Finish() | 	span.Finish() | ||||||
| } | } | ||||||
| @@ -155,6 +167,13 @@ func (m *hookTracer) OnFetchRecordUnbuffered(r *kgo.Record, _ bool) { | |||||||
| // not a record which has been created for producing, so call this at the start of each | // not a record which has been created for producing, so call this at the start of each | ||||||
| // iteration of your processing for the record. | // iteration of your processing for the record. | ||||||
| func (m *hookTracer) WithProcessSpan(r *kgo.Record) (context.Context, tracer.Span) { | func (m *hookTracer) WithProcessSpan(r *kgo.Record) (context.Context, tracer.Span) { | ||||||
|  | 	if r.Context == nil { | ||||||
|  | 		r.Context = context.Background() | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return r.Context, nil | ||||||
|  | 	} | ||||||
| 	// Set up the span options. | 	// Set up the span options. | ||||||
| 	attrs := []interface{}{ | 	attrs := []interface{}{ | ||||||
| 		messagingSystem, | 		messagingSystem, | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user