Compare commits
	
		
			14 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| d6e73a3419 | |||
| 969e459e3d | |||
|  | b2cd7d8b8e | ||
| 6d85d3ee41 | |||
| d0978fb314 | |||
|  | 0bd81d1253 | ||
| e34f57a515 | |||
| ccd912adb2 | |||
| db97b24904 | |||
| 7410408fc4 | |||
| 4d28a6ebb2 | |||
| f73d9d7347 | |||
| 53f72f1246 | |||
| ac454693a6 | 
							
								
								
									
										7
									
								
								.github/workflows/job_coverage.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										7
									
								
								.github/workflows/job_coverage.yml
									
									
									
									
										vendored
									
									
								
							| @@ -8,11 +8,12 @@ on: | |||||||
|       - '.gitea/**' |       - '.gitea/**' | ||||||
|   pull_request: |   pull_request: | ||||||
|     branches: [ main, v3, v4 ] |     branches: [ main, v3, v4 ] | ||||||
|  |   # Allows you to run this workflow manually from the Actions tab | ||||||
|  |   workflow_dispatch: | ||||||
|  |  | ||||||
| jobs: | jobs: | ||||||
|  |  | ||||||
|   build: |   build: | ||||||
|     if: github.server_url != 'https://github.com' |  | ||||||
|     runs-on: ubuntu-latest |     runs-on: ubuntu-latest | ||||||
|     steps: |     steps: | ||||||
|     - name: checkout code |     - name: checkout code | ||||||
| @@ -41,8 +42,8 @@ jobs: | |||||||
|       name: autocommit |       name: autocommit | ||||||
|       with: |       with: | ||||||
|         commit_message: Apply Code Coverage Badge |         commit_message: Apply Code Coverage Badge | ||||||
|         skip_fetch: false |         skip_fetch: true | ||||||
|         skip_checkout: false |         skip_checkout: true | ||||||
|         file_pattern: ./README.md |         file_pattern: ./README.md | ||||||
|  |  | ||||||
|     - name: push |     - name: push | ||||||
|   | |||||||
							
								
								
									
										2
									
								
								.github/workflows/job_lint.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.github/workflows/job_lint.yml
									
									
									
									
										vendored
									
									
								
							| @@ -24,6 +24,6 @@ jobs: | |||||||
|     - name: setup deps |     - name: setup deps | ||||||
|       run: go get -v ./... |       run: go get -v ./... | ||||||
|     - name: run lint |     - name: run lint | ||||||
|       uses: golangci/golangci-lint-action@v6 |       uses: https://github.com/golangci/golangci-lint-action@v6 | ||||||
|       with: |       with: | ||||||
|         version: 'latest' |         version: 'latest' | ||||||
|   | |||||||
							
								
								
									
										52
									
								
								.github/workflows/job_sync.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										52
									
								
								.github/workflows/job_sync.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,52 @@ | |||||||
|  | name: sync | ||||||
|  |  | ||||||
|  | on: | ||||||
|  |   schedule: | ||||||
|  |     - cron: '*/5 * * * *' | ||||||
|  |   # Allows you to run this workflow manually from the Actions tab | ||||||
|  |   workflow_dispatch: | ||||||
|  |  | ||||||
|  | jobs: | ||||||
|  |   sync: | ||||||
|  |     if: github.server_url == 'zhttps://github.com' | ||||||
|  |     runs-on: ubuntu-latest | ||||||
|  |     steps: | ||||||
|  |     - name: init | ||||||
|  |       run: | | ||||||
|  |         git config --global user.email "vtolstov <vtolstov@users.noreply.github.com>" | ||||||
|  |         git config --global user.name "github-actions[bot]" | ||||||
|  |         echo "machine git.unistack.org login vtolstov password ${{ secrets.TOKEN_GITEA }}" >> /root/.netrc | ||||||
|  |         echo "machine github.com login vtolstov password ${{ secrets.TOKEN_GITHUB }}" >> /root/.netrc | ||||||
|  |  | ||||||
|  |     - name: sync master | ||||||
|  |       run: | | ||||||
|  |         git clone --filter=blob:none --filter=tree:0 --branch master --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo | ||||||
|  |         cd repo | ||||||
|  |         git remote add --no-tags --fetch --track master upstream https://github.com/${GITHUB_REPOSITORY} | ||||||
|  |         git merge upstream/master | ||||||
|  |         git push upstream master --progress | ||||||
|  |         git push origin master --progress | ||||||
|  |         cd ../ | ||||||
|  |         rm -rf repo | ||||||
|  |  | ||||||
|  |     - name: sync v3 | ||||||
|  |       run: | | ||||||
|  |         git clone --filter=blob:none --filter=tree:0 --branch v3 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo | ||||||
|  |         cd repo | ||||||
|  |         git remote add --no-tags --fetch --track v3 upstream https://github.com/${GITHUB_REPOSITORY} | ||||||
|  |         git merge upstream/v3 | ||||||
|  |         git push upstream v3 --progress | ||||||
|  |         git push origin v3 --progress | ||||||
|  |         cd ../ | ||||||
|  |         rm -rf repo | ||||||
|  |  | ||||||
|  |     - name: sync v4 | ||||||
|  |       run: | | ||||||
|  |         git clone --filter=blob:none --filter=tree:0 --branch v4 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo | ||||||
|  |         cd repo | ||||||
|  |         git remote add --no-tags --fetch --track v4 upstream https://github.com/${GITHUB_REPOSITORY} | ||||||
|  |         git merge upstream/v4 | ||||||
|  |         git push upstream v4 --progress | ||||||
|  |         git push origin v4 --progress | ||||||
|  |         cd ../ | ||||||
|  |         rm -rf repo | ||||||
							
								
								
									
										6
									
								
								.github/workflows/job_tests.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										6
									
								
								.github/workflows/job_tests.yml
									
									
									
									
										vendored
									
									
								
							| @@ -32,19 +32,19 @@ jobs: | |||||||
|         go-version: 'stable' |         go-version: 'stable' | ||||||
|     - name: setup go work |     - name: setup go work | ||||||
|       env: |       env: | ||||||
|         GOWORK: ${{ github.workspace }}/go.work |         GOWORK: /workspace/${{ github.repository_owner }}/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: ${{ github.workspace }}/go.work |         GOWORK: /workspace/${{ github.repository_owner }}/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: ${{ github.workspace }}/go.work |         GOWORK: /workspace/${{ github.repository_owner }}/go.work | ||||||
|       run: | |       run: | | ||||||
|         cd micro-tests |         cd micro-tests | ||||||
|         go test -mod readonly -v ./... || true |         go test -mod readonly -v ./... || true | ||||||
|   | |||||||
							
								
								
									
										11
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										11
									
								
								README.md
									
									
									
									
									
								
							| @@ -1,9 +1,2 @@ | |||||||
| # broker-kgo | # micro-broker-kgo | ||||||
|  |  | ||||||
| TODO: |  | ||||||
|  |  | ||||||
| 1) экспортируем текущий оффсет для каждой партиции в группе |  | ||||||
| 2) экспортируем лаг для группы |  | ||||||
| 3) мониторим |  | ||||||
|    1) если есть лаг больше нуля |  | ||||||
|    2) если дельта оффсета за нужное нам время не  |  | ||||||
|   | |||||||
| @@ -7,13 +7,13 @@ import ( | |||||||
| 	"time" | 	"time" | ||||||
| 
 | 
 | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	"go.unistack.org/micro/v3/logger" | 	"go.unistack.org/micro/v4/logger" | ||||||
| ) | ) | ||||||
| 
 | 
 | ||||||
| type hookEvent struct { | type hookEvent struct { | ||||||
| 	log          logger.Logger | 	log          logger.Logger | ||||||
| 	connected    *atomic.Uint32 |  | ||||||
| 	fatalOnError bool | 	fatalOnError bool | ||||||
|  | 	connected    *atomic.Uint32 | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| var ( | var ( | ||||||
| @@ -26,48 +26,50 @@ var ( | |||||||
| ) | ) | ||||||
| 
 | 
 | ||||||
| func (m *hookEvent) OnGroupManageError(err error) { | func (m *hookEvent) OnGroupManageError(err error) { | ||||||
| 	switch { | 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | 		m.connected.Store(0) | ||||||
| 		return | 		if m.fatalOnError { | ||||||
| 	default: | 			m.log.Fatal(context.TODO(), "kgo.OnGroupManageError", err) | ||||||
| 		m.log.Error(context.TODO(), "kgo.OnGroupManageError", err) | 		} | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| func (m *hookEvent) OnBrokerConnect(_ kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) { | func (m *hookEvent) OnBrokerConnect(_ kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) { | ||||||
| 	switch { | 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | 		m.connected.Store(0) | ||||||
| 		return | 		if m.fatalOnError { | ||||||
| 	default: | 			m.log.Fatal(context.TODO(), "kgo.OnBrokerConnect", err) | ||||||
| 		m.log.Error(context.TODO(), "kgo.OnBrokerConnect", err) | 		} | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| func (m *hookEvent) OnBrokerDisconnect(_ kgo.BrokerMetadata, _ net.Conn) {} | func (m *hookEvent) OnBrokerDisconnect(_ kgo.BrokerMetadata, _ net.Conn) { | ||||||
|  | 	// m.connected.Store(0) | ||||||
|  | } | ||||||
| 
 | 
 | ||||||
| func (m *hookEvent) OnBrokerWrite(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | func (m *hookEvent) OnBrokerWrite(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | ||||||
| 	switch { | 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | 		m.connected.Store(0) | ||||||
| 		return | 		if m.fatalOnError { | ||||||
| 	default: | 			m.log.Fatal(context.TODO(), "kgo.OnBrokerWrite", err) | ||||||
| 		m.log.Error(context.TODO(), "kgo.OnBrokerWrite", err) | 		} | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| func (m *hookEvent) OnBrokerRead(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | func (m *hookEvent) OnBrokerRead(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | ||||||
| 	switch { | 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | 		m.connected.Store(0) | ||||||
| 		return | 		if m.fatalOnError { | ||||||
| 	default: | 			m.log.Fatal(context.TODO(), "kgo.OnBrokerRead", err) | ||||||
| 		m.log.Error(context.TODO(), "kgo.OnBrokerRead", err) | 		} | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| func (m *hookEvent) OnProduceRecordUnbuffered(_ *kgo.Record, err error) { | func (m *hookEvent) OnProduceRecordUnbuffered(_ *kgo.Record, err error) { | ||||||
| 	switch { | 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | 		m.connected.Store(0) | ||||||
| 		return | 		if m.fatalOnError { | ||||||
| 	default: | 			m.log.Fatal(context.TODO(), "kgo.OnProduceRecordUnbuffered", err) | ||||||
| 		m.log.Error(context.TODO(), "kgo.OnProduceRecordUnbuffered", err) | 		} | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
| @@ -6,7 +6,7 @@ import ( | |||||||
| 	"strings" | 	"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/v4/metadata" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| // RecordCarrier injects and extracts traces from a kgo.Record. | // RecordCarrier injects and extracts traces from a kgo.Record. | ||||||
| @@ -77,7 +77,7 @@ loop: | |||||||
| 		for i := 0; i < len(r.Headers); i++ { | 		for i := 0; i < len(r.Headers); i++ { | ||||||
| 			if strings.EqualFold(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(strings.Join(v, ",")) | ||||||
| 				continue loop | 				continue loop | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| @@ -85,7 +85,7 @@ loop: | |||||||
| 		// Key does not exist, append new header. | 		// Key does not exist, append new header. | ||||||
| 		r.Headers = append(r.Headers, kgo.RecordHeader{ | 		r.Headers = append(r.Headers, kgo.RecordHeader{ | ||||||
| 			Key:   k, | 			Key:   k, | ||||||
| 			Value: []byte(v), | 			Value: []byte(strings.Join(v, ",")), | ||||||
| 		}) | 		}) | ||||||
|  |  | ||||||
| 		seen[k] = struct{}{} | 		seen[k] = struct{}{} | ||||||
|   | |||||||
							
								
								
									
										10
									
								
								errors.go
									
									
									
									
									
								
							
							
						
						
									
										10
									
								
								errors.go
									
									
									
									
									
								
							| @@ -1,10 +0,0 @@ | |||||||
| package kgo |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"context" |  | ||||||
| 	"errors" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| func isContextError(err error) bool { |  | ||||||
| 	return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) |  | ||||||
| } |  | ||||||
							
								
								
									
										50
									
								
								event.go
									
									
									
									
									
								
							
							
						
						
									
										50
									
								
								event.go
									
									
									
									
									
								
							| @@ -1,50 +0,0 @@ | |||||||
| package kgo |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"context" |  | ||||||
| 	"sync" |  | ||||||
|  |  | ||||||
| 	"go.unistack.org/micro/v3/broker" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| type event struct { |  | ||||||
| 	msg *broker.Message |  | ||||||
| 	err error |  | ||||||
| 	ctx context.Context |  | ||||||
|  |  | ||||||
| 	topic string |  | ||||||
|  |  | ||||||
| 	sync.RWMutex |  | ||||||
| 	ack bool |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (p *event) Context() context.Context { |  | ||||||
| 	return p.ctx |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (p *event) Topic() string { |  | ||||||
| 	return p.topic |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (p *event) Message() *broker.Message { |  | ||||||
| 	return p.msg |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (p *event) Ack() error { |  | ||||||
| 	p.ack = true |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (p *event) Error() error { |  | ||||||
| 	return p.err |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (p *event) SetError(err error) { |  | ||||||
| 	p.err = err |  | ||||||
| } |  | ||||||
|  |  | ||||||
| var eventPool = sync.Pool{ |  | ||||||
| 	New: func() interface{} { |  | ||||||
| 		return &event{msg: &broker.Message{}} |  | ||||||
| 	}, |  | ||||||
| } |  | ||||||
							
								
								
									
										33
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										33
									
								
								go.mod
									
									
									
									
									
								
							| @@ -1,32 +1,23 @@ | |||||||
| module go.unistack.org/micro-broker-kgo/v3 | module go.unistack.org/micro-broker-kgo/v4 | ||||||
|  |  | ||||||
| go 1.24.0 | go 1.23.8 | ||||||
|  |  | ||||||
| toolchain go1.24.3 |  | ||||||
|  |  | ||||||
| require ( | require ( | ||||||
| 	github.com/google/uuid v1.6.0 | 	github.com/twmb/franz-go v1.19.1 | ||||||
| 	github.com/stretchr/testify v1.11.1 | 	github.com/twmb/franz-go/pkg/kadm v1.16.0 | ||||||
| 	github.com/twmb/franz-go v1.19.5 | 	github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3 | ||||||
| 	github.com/twmb/franz-go/pkg/kadm v1.16.1 |  | ||||||
| 	github.com/twmb/franz-go/pkg/kmsg v1.11.2 | 	github.com/twmb/franz-go/pkg/kmsg v1.11.2 | ||||||
| 	go.opentelemetry.io/otel v1.38.0 | 	go.opentelemetry.io/otel v1.35.0 | ||||||
| 	go.unistack.org/micro/v3 v3.11.45 | 	go.unistack.org/micro/v4 v4.1.14 | ||||||
| ) | ) | ||||||
|  |  | ||||||
| require ( | require ( | ||||||
| 	github.com/ash3in/uuidv8 v1.2.0 // indirect | 	github.com/google/uuid v1.6.0 // indirect | ||||||
| 	github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect |  | ||||||
| 	github.com/klauspost/compress v1.18.0 // indirect | 	github.com/klauspost/compress v1.18.0 // 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 | 	github.com/spf13/cast v1.8.0 // indirect | ||||||
| 	go.unistack.org/micro-proto/v3 v3.4.1 // indirect | 	go.unistack.org/micro-proto/v4 v4.1.0 // indirect | ||||||
| 	golang.org/x/crypto v0.43.0 // indirect | 	golang.org/x/crypto v0.38.0 // indirect | ||||||
| 	golang.org/x/sys v0.37.0 // indirect | 	google.golang.org/protobuf v1.36.6 // indirect | ||||||
| 	google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff // indirect |  | ||||||
| 	google.golang.org/grpc v1.76.0 // indirect |  | ||||||
| 	google.golang.org/protobuf v1.36.10 // indirect |  | ||||||
| 	gopkg.in/yaml.v3 v3.0.1 // indirect |  | ||||||
| ) | ) | ||||||
|   | |||||||
							
								
								
									
										60
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										60
									
								
								go.sum
									
									
									
									
									
								
							| @@ -1,12 +1,7 @@ | |||||||
| github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= |  | ||||||
| github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= |  | ||||||
| github.com/ash3in/uuidv8 v1.2.0 h1:2oogGdtCPwaVtyvPPGin4TfZLtOGE5F+W++E880G6SI= |  | ||||||
| github.com/ash3in/uuidv8 v1.2.0/go.mod h1:BnU0wJBxnzdEKmVg4xckBkD+VZuecTFTUP3M0dWgyY4= |  | ||||||
| github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= |  | ||||||
| github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= | ||||||
| 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/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= | ||||||
| github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= | ||||||
| github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= | ||||||
| github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= | 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= | ||||||
| @@ -21,42 +16,31 @@ github.com/matoous/go-nanoid v1.5.1 h1:aCjdvTyO9LLnTIi0fgdXhOPPvOHjpXN6Ik9DaNjIc | |||||||
| github.com/matoous/go-nanoid v1.5.1/go.mod h1:zyD2a71IubI24efhpvkJz+ZwfwagzgSO6UNiFsZKN7U= | github.com/matoous/go-nanoid v1.5.1/go.mod h1:zyD2a71IubI24efhpvkJz+ZwfwagzgSO6UNiFsZKN7U= | ||||||
| github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= | github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= | ||||||
| github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= | github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= | ||||||
| github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= |  | ||||||
| github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= | ||||||
| github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | ||||||
| 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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= | github.com/spf13/cast v1.8.0 h1:gEN9K4b8Xws4EX0+a0reLmhq8moKn7ntRlQYgjPeCDk= | ||||||
| github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= | github.com/spf13/cast v1.8.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= | ||||||
| github.com/twmb/franz-go v1.19.5 h1:W7+o8D0RsQsedqib71OVlLeZ0zI6CbFra7yTYhZTs5Y= | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= | ||||||
| github.com/twmb/franz-go v1.19.5/go.mod h1:4kFJ5tmbbl7asgwAGVuyG1ZMx0NNpYk7EqflvWfPCpM= | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= | ||||||
| github.com/twmb/franz-go/pkg/kadm v1.16.1 h1:IEkrhTljgLHJ0/hT/InhXGjPdmWfFvxp7o/MR7vJ8cw= | github.com/twmb/franz-go v1.19.1 h1:cOhDFUkGvUFHSQ7UYW6bO77BJa2fYEk5mA2AX+1NIdE= | ||||||
| github.com/twmb/franz-go/pkg/kadm v1.16.1/go.mod h1:Ue/ye1cc9ipsQFg7udFbbGiFNzQMqiH73fGC2y0rwyc= | github.com/twmb/franz-go v1.19.1/go.mod h1:4kFJ5tmbbl7asgwAGVuyG1ZMx0NNpYk7EqflvWfPCpM= | ||||||
|  | github.com/twmb/franz-go/pkg/kadm v1.16.0 h1:STMs1t5lYR5mR974PSiwNzE5TvsosByTp+rKXLOhAjE= | ||||||
|  | github.com/twmb/franz-go/pkg/kadm v1.16.0/go.mod h1:MUdcUtnf9ph4SFBLLA/XxE29rvLhWYLM9Ygb8dfSCvw= | ||||||
|  | github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3 h1:p24opKWPySAy8xSl8NqRgOv7Q+bX7kdrQirBVRJzQfo= | ||||||
|  | github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3/go.mod h1:7uQs3Ae6HkWT1Y9elMbqtAcNFCI0y6+iS+Phw49L49U= | ||||||
| github.com/twmb/franz-go/pkg/kmsg v1.11.2 h1:hIw75FpwcAjgeyfIGFqivAvwC5uNIOWRGvQgZhH4mhg= | 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.11.2/go.mod h1:CFfkkLysDNmukPYhGzuUcDtf46gQSqCZHMW1T4Z+wDE= | ||||||
| go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= | go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= | ||||||
| go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= | go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= | ||||||
| go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q= | go.unistack.org/micro-proto/v4 v4.1.0 h1:qPwL2n/oqh9RE3RTTDgt28XK3QzV597VugQPaw9lKUk= | ||||||
| go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo= | go.unistack.org/micro-proto/v4 v4.1.0/go.mod h1:ArmK7o+uFvxSY3dbJhKBBX4Pm1rhWdLEFf3LxBrMtec= | ||||||
| go.unistack.org/micro/v3 v3.11.45 h1:fjTLZYWgsVf9FIMZBxOg8ios2/tmyimnjZrsrxEUeXU= | go.unistack.org/micro/v4 v4.1.14 h1:6EotPq9kz/gaFb5YulHdKuuUwmj/7Hk44DpOlzh/A6k= | ||||||
| go.unistack.org/micro/v3 v3.11.45/go.mod h1:fDQ8Mu9wubaFP0L8hNQlpzHiEnWN0wbOlawN9HYo0N4= | go.unistack.org/micro/v4 v4.1.14/go.mod h1:xleO2M5Yxh4s6I+RUcLrEpUjobefh+71ctrdIfn7TUs= | ||||||
| golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= | golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= | ||||||
| golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= | golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= | ||||||
| golang.org/x/net v0.45.0 h1:RLBg5JKixCy82FtLJpeNlVM0nrSqpCRYzVU1n8kj0tM= | google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= | ||||||
| golang.org/x/net v0.45.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= | google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= | ||||||
| golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= |  | ||||||
| golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= |  | ||||||
| golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= |  | ||||||
| golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= |  | ||||||
| google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff h1:A90eA31Wq6HOMIQlLfzFwzqGKBTuaVztYu/g8sn+8Zc= |  | ||||||
| google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff/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 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= |  | ||||||
| gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= |  | ||||||
| gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= | ||||||
| gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | ||||||
|   | |||||||
| @@ -1,362 +0,0 @@ | |||||||
| 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") |  | ||||||
| } |  | ||||||
							
								
								
									
										337
									
								
								kgo.go
									
									
									
									
									
								
							
							
						
						
									
										337
									
								
								kgo.go
									
									
									
									
									
								
							| @@ -6,27 +6,32 @@ import ( | |||||||
| 	"errors" | 	"errors" | ||||||
| 	"fmt" | 	"fmt" | ||||||
| 	"math/rand/v2" | 	"math/rand/v2" | ||||||
| 	"strconv" |  | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"sync" | 	"sync" | ||||||
| 	"sync/atomic" | 	"sync/atomic" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"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/v4/broker" | ||||||
| 	"go.unistack.org/micro/v3/logger" | 	"go.unistack.org/micro/v4/codec" | ||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v4/logger" | ||||||
| 	"go.unistack.org/micro/v3/semconv" | 	"go.unistack.org/micro/v4/metadata" | ||||||
| 	"go.unistack.org/micro/v3/tracer" | 	"go.unistack.org/micro/v4/options" | ||||||
| 	mjitter "go.unistack.org/micro/v3/util/jitter" | 	"go.unistack.org/micro/v4/semconv" | ||||||
| 	mrand "go.unistack.org/micro/v3/util/rand" | 	"go.unistack.org/micro/v4/tracer" | ||||||
|  | 	"go.unistack.org/micro/v4/util/id" | ||||||
|  | 	mrand "go.unistack.org/micro/v4/util/rand" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var _ broker.Broker = (*Broker)(nil) | var _ broker.Broker = (*Broker)(nil) | ||||||
|  |  | ||||||
|  | var messagePool = sync.Pool{ | ||||||
|  | 	New: func() interface{} { | ||||||
|  | 		return &kgoMessage{} | ||||||
|  | 	}, | ||||||
|  | } | ||||||
|  |  | ||||||
| var ErrLostMessage = errors.New("message not marked for offsets commit and will be lost in next iteration") | var ErrLostMessage = errors.New("message not marked for offsets commit and will be lost in next iteration") | ||||||
|  |  | ||||||
| var DefaultRetryBackoffFn = func() func(int) time.Duration { | var DefaultRetryBackoffFn = func() func(int) time.Duration { | ||||||
| @@ -59,17 +64,17 @@ var DefaultRetryBackoffFn = func() func(int) time.Duration { | |||||||
| }() | }() | ||||||
|  |  | ||||||
| type Broker struct { | type Broker struct { | ||||||
|  | 	funcPublish   broker.FuncPublish | ||||||
|  | 	funcSubscribe broker.FuncSubscribe | ||||||
| 	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 | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -97,6 +102,72 @@ func (k *Broker) Client() *kgo.Client { | |||||||
| 	return k.c | 	return k.c | ||||||
| } | } | ||||||
|  |  | ||||||
|  | type kgoMessage struct { | ||||||
|  | 	c     codec.Codec | ||||||
|  | 	topic string | ||||||
|  | 	ctx   context.Context | ||||||
|  | 	body  []byte | ||||||
|  | 	hdr   metadata.Metadata | ||||||
|  | 	opts  broker.PublishOptions | ||||||
|  | 	ack   bool | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *kgoMessage) Ack() error { | ||||||
|  | 	m.ack = true | ||||||
|  | 	return nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *kgoMessage) Body() []byte { | ||||||
|  | 	return m.body | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *kgoMessage) Header() metadata.Metadata { | ||||||
|  | 	return m.hdr | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *kgoMessage) Context() context.Context { | ||||||
|  | 	return m.ctx | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *kgoMessage) Topic() string { | ||||||
|  | 	return "" | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *kgoMessage) Unmarshal(dst interface{}, opts ...codec.Option) error { | ||||||
|  | 	return m.c.Unmarshal(m.body, dst) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (b *Broker) newCodec(ct string) (codec.Codec, error) { | ||||||
|  | 	if idx := strings.IndexRune(ct, ';'); idx >= 0 { | ||||||
|  | 		ct = ct[:idx] | ||||||
|  | 	} | ||||||
|  | 	b.RLock() | ||||||
|  | 	c, ok := b.opts.Codecs[ct] | ||||||
|  | 	b.RUnlock() | ||||||
|  | 	if ok { | ||||||
|  | 		return c, nil | ||||||
|  | 	} | ||||||
|  | 	return nil, codec.ErrUnknownContentType | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (b *Broker) NewMessage(ctx context.Context, hdr metadata.Metadata, body interface{}, opts ...broker.PublishOption) (broker.Message, error) { | ||||||
|  | 	options := broker.NewPublishOptions(opts...) | ||||||
|  | 	if options.ContentType == "" { | ||||||
|  | 		options.ContentType = b.opts.ContentType | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	m := &kgoMessage{ctx: ctx, hdr: hdr, opts: options} | ||||||
|  | 	c, err := b.newCodec(m.opts.ContentType) | ||||||
|  | 	if err == nil { | ||||||
|  | 		m.body, err = c.Marshal(body) | ||||||
|  | 	} | ||||||
|  | 	if err != nil { | ||||||
|  | 		return nil, err | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return m, nil | ||||||
|  | } | ||||||
|  |  | ||||||
| func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, *hookTracer, error) { | func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, *hookTracer, error) { | ||||||
| 	var c *kgo.Client | 	var c *kgo.Client | ||||||
| 	var err error | 	var err error | ||||||
| @@ -148,25 +219,6 @@ 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) | 		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 | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
| @@ -186,72 +238,10 @@ func (k *Broker) Connect(ctx context.Context) error { | |||||||
| 		return err | 		return err | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	k.mu.Lock() | 	k.Lock() | ||||||
| 	k.c = c | 	k.c = c | ||||||
| 	k.connected.Store(1) | 	k.connected.Store(1) | ||||||
| 	k.mu.Unlock() | 	k.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 | ||||||
| } | } | ||||||
| @@ -269,8 +259,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.mu.Lock() | 	k.Lock() | ||||||
| 	defer k.mu.Unlock() | 	defer k.Unlock() | ||||||
| 	select { | 	select { | ||||||
| 	case <-nctx.Done(): | 	case <-nctx.Done(): | ||||||
| 		return nctx.Err() | 		return nctx.Err() | ||||||
| @@ -290,13 +280,12 @@ 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.mu.Lock() | 	k.Lock() | ||||||
| 	defer k.mu.Unlock() | 	defer k.Unlock() | ||||||
|  |  | ||||||
| 	if len(opts) == 0 && k.init { | 	if len(opts) == 0 && k.init { | ||||||
| 		return nil | 		return nil | ||||||
| @@ -325,6 +314,18 @@ func (k *Broker) Init(opts ...broker.Option) error { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	k.funcPublish = k.fnPublish | ||||||
|  | 	k.funcSubscribe = k.fnSubscribe | ||||||
|  |  | ||||||
|  | 	k.opts.Hooks.EachPrev(func(hook options.Hook) { | ||||||
|  | 		switch h := hook.(type) { | ||||||
|  | 		case broker.HookPublish: | ||||||
|  | 			k.funcPublish = h(k.funcPublish) | ||||||
|  | 		case broker.HookSubscribe: | ||||||
|  | 			k.funcSubscribe = h(k.funcSubscribe) | ||||||
|  | 		} | ||||||
|  | 	}) | ||||||
|  |  | ||||||
| 	k.init = true | 	k.init = true | ||||||
|  |  | ||||||
| 	return nil | 	return nil | ||||||
| @@ -334,83 +335,77 @@ func (k *Broker) Options() broker.Options { | |||||||
| 	return k.opts | 	return k.opts | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *Broker) BatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { | func (b *Broker) Publish(ctx context.Context, topic string, messages ...broker.Message) error { | ||||||
| 	return k.publish(ctx, msgs, opts...) | 	return b.funcPublish(ctx, topic, messages...) | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *Broker) Publish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error { | func (b *Broker) fnPublish(ctx context.Context, topic string, messages ...broker.Message) error { | ||||||
| 	msg.Header.Set(metadata.HeaderTopic, topic) | 	return b.publish(ctx, topic, messages...) | ||||||
| 	return k.publish(ctx, []*broker.Message{msg}, opts...) |  | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { | func (b *Broker) publish(ctx context.Context, topic string, messages ...broker.Message) error { | ||||||
| 	options := broker.NewPublishOptions(opts...) | 	records := make([]*kgo.Record, 0, len(messages)) | ||||||
| 	records := make([]*kgo.Record, 0, len(msgs)) |  | ||||||
| 	var errs []string | 	var errs []string | ||||||
| 	var err error |  | ||||||
| 	var key []byte | 	var key []byte | ||||||
| 	var promise func(*kgo.Record, error) | 	var promise func(*kgo.Record, error) | ||||||
|  |  | ||||||
| 	if options.Context != nil { | 	for _, msg := range messages { | ||||||
| 		if k, ok := options.Context.Value(publishKey{}).([]byte); ok && k != nil { | 		if mctx := msg.Context(); mctx != nil { | ||||||
|  | 			if k, ok := mctx.Value(publishKey{}).([]byte); ok && k != nil { | ||||||
| 				key = k | 				key = k | ||||||
| 			} | 			} | ||||||
| 		if p, ok := options.Context.Value(publishPromiseKey{}).(func(*kgo.Record, error)); ok && p != nil { | 			if p, ok := mctx.Value(publishPromiseKey{}).(func(*kgo.Record, error)); ok && p != nil { | ||||||
| 				promise = p | 				promise = p | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 	for _, msg := range msgs { | 		rec := &kgo.Record{ | ||||||
| 		rec := &kgo.Record{Context: ctx, Key: key} | 			Context: ctx, | ||||||
|  | 			Key:     key, | ||||||
| 		rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic) | 			Topic:   topic, | ||||||
| 		msg.Header.Del(metadata.HeaderTopic) | 			Value:   msg.Body(), | ||||||
|  |  | ||||||
| 		k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc() |  | ||||||
| 		if options.BodyOnly || k.opts.Codec.String() == "noop" { |  | ||||||
| 			rec.Value = msg.Body |  | ||||||
| 			setHeaders(rec, msg.Header) |  | ||||||
| 		} else { |  | ||||||
| 			rec.Value, err = k.opts.Codec.Marshal(msg) |  | ||||||
| 			if err != nil { |  | ||||||
| 				return err |  | ||||||
| 			} |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
|  | 		b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc() | ||||||
|  |  | ||||||
|  | 		setHeaders(rec, msg.Header()) | ||||||
|  |  | ||||||
| 		records = append(records, rec) | 		records = append(records, rec) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	if promise != nil { |  | ||||||
| 	ts := time.Now() | 	ts := time.Now() | ||||||
|  |  | ||||||
|  | 	if promise != nil { | ||||||
|  |  | ||||||
| 		for _, rec := range records { | 		for _, rec := range records { | ||||||
| 			k.c.Produce(ctx, rec, func(r *kgo.Record, err error) { | 			b.c.Produce(ctx, rec, func(r *kgo.Record, err error) { | ||||||
| 				te := time.Since(ts) | 				te := time.Since(ts) | ||||||
| 				k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Dec() | 				b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Dec() | ||||||
| 				k.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds()) | 				b.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds()) | ||||||
| 				k.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds()) | 				b.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds()) | ||||||
| 				if err != nil { | 				if err != nil { | ||||||
| 					k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "failure").Inc() | 					b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "failure").Inc() | ||||||
| 				} else { | 				} else { | ||||||
| 					k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "success").Inc() | 					b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "success").Inc() | ||||||
| 				} | 				} | ||||||
| 				promise(r, err) | 				promise(r, err) | ||||||
| 			}) | 			}) | ||||||
| 		} | 		} | ||||||
| 		return nil | 		return nil | ||||||
| 	} | 	} | ||||||
| 	ts := time.Now() |  | ||||||
|  |  | ||||||
| 	results := k.c.ProduceSync(ctx, records...) | 	results := b.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()) | 		b.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds()) | ||||||
| 		k.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds()) | 		b.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds()) | ||||||
| 		k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Dec() | 		b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Dec() | ||||||
| 		if result.Err != nil { | 		if result.Err != nil { | ||||||
| 			k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "failure").Inc() | 			b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "failure").Inc() | ||||||
| 			errs = append(errs, result.Err.Error()) | 			errs = append(errs, result.Err.Error()) | ||||||
| 		} else { | 		} else { | ||||||
| 			k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc() | 			b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc() | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -437,31 +432,54 @@ func (k *Broker) TopicExists(ctx context.Context, topic string) error { | |||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *Broker) BatchSubscribe(_ context.Context, _ string, _ broker.BatchHandler, _ ...broker.SubscribeOption) (broker.Subscriber, error) { | func (b *Broker) Subscribe(ctx context.Context, topic string, handler interface{}, opts ...broker.SubscribeOption) (broker.Subscriber, error) { | ||||||
| 	return nil, nil | 	return b.funcSubscribe(ctx, topic, handler, opts...) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (b *Broker) fnSubscribe(ctx context.Context, topic string, handler interface{}, opts ...broker.SubscribeOption) (broker.Subscriber, error) { | ||||||
|  | 	if err := broker.IsValidHandler(handler); err != nil { | ||||||
|  | 		return nil, err | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { |  | ||||||
| 	options := broker.NewSubscribeOptions(opts...) | 	options := broker.NewSubscribeOptions(opts...) | ||||||
|  |  | ||||||
|  | 	switch handler.(type) { | ||||||
|  | 	default: | ||||||
|  | 		return nil, broker.ErrInvalidHandler | ||||||
|  | 	case func(broker.Message) error: | ||||||
|  | 		break | ||||||
|  | 	case func([]broker.Message) error: | ||||||
|  | 		break | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	if options.Group == "" { | 	if options.Group == "" { | ||||||
| 		uid, err := uuid.NewRandom() | 		uid, err := id.New() | ||||||
| 		if err != nil { | 		if err != nil { | ||||||
| 			return nil, err | 			return nil, err | ||||||
| 		} | 		} | ||||||
| 		options.Group = uid.String() | 		options.Group = uid | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	commitInterval := DefaultCommitInterval | 	commitInterval := DefaultCommitInterval | ||||||
| 	if k.opts.Context != nil { | 	if b.opts.Context != nil { | ||||||
| 		if v, ok := k.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 { | 		if v, ok := b.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 { | ||||||
| 			commitInterval = v | 			commitInterval = v | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	var messagePool bool | ||||||
| 	var fatalOnError bool | 	var fatalOnError bool | ||||||
| 	if k.opts.Context != nil { | 	if b.opts.Context != nil { | ||||||
| 		if v, ok := k.opts.Context.Value(fatalOnErrorKey{}).(bool); ok && v { | 		if v, ok := b.opts.Context.Value(fatalOnErrorKey{}).(bool); ok && v { | ||||||
|  | 			fatalOnError = v | ||||||
|  | 		} | ||||||
|  | 		if v, ok := b.opts.Context.Value(subscribeMessagePoolKey{}).(bool); ok && v { | ||||||
|  | 			messagePool = v | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if options.Context != nil { | ||||||
|  | 		if v, ok := options.Context.Value(fatalOnErrorKey{}).(bool); ok && v { | ||||||
| 			fatalOnError = v | 			fatalOnError = v | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
| @@ -470,14 +488,15 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han | |||||||
| 		topic:        topic, | 		topic:        topic, | ||||||
| 		opts:         options, | 		opts:         options, | ||||||
| 		handler:      handler, | 		handler:      handler, | ||||||
| 		kopts:        k.opts, | 		kopts:        b.opts, | ||||||
| 		consumers:    make(map[tp]*consumer), | 		consumers:    make(map[tp]*consumer), | ||||||
| 		done:         make(chan struct{}), | 		done:         make(chan struct{}), | ||||||
| 		fatalOnError: fatalOnError, | 		fatalOnError: fatalOnError, | ||||||
| 		connected:    k.connected, | 		connected:    b.connected, | ||||||
|  | 		messagePool:  messagePool, | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	kopts := append(k.kopts, | 	kopts := append(b.kopts, | ||||||
| 		kgo.ConsumerGroup(options.Group), | 		kgo.ConsumerGroup(options.Group), | ||||||
| 		kgo.ConsumeTopics(topic), | 		kgo.ConsumeTopics(topic), | ||||||
| 		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), | 		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), | ||||||
| @@ -497,7 +516,7 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	c, htracer, err := k.connect(ctx, kopts...) | 	c, htracer, err := b.connect(ctx, kopts...) | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return nil, err | 		return nil, err | ||||||
| 	} | 	} | ||||||
| @@ -519,9 +538,10 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han | |||||||
|  |  | ||||||
| 	go sub.poll(ctx) | 	go sub.poll(ctx) | ||||||
|  |  | ||||||
| 	k.mu.Lock() | 	b.Lock() | ||||||
| 	k.subs = append(k.subs, sub) | 	b.subs = append(b.subs, sub) | ||||||
| 	k.mu.Unlock() | 	b.Unlock() | ||||||
|  |  | ||||||
| 	return sub, nil | 	return sub, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -561,6 +581,5 @@ func NewBroker(opts ...broker.Option) *Broker { | |||||||
| 		connected: &atomic.Uint32{}, | 		connected: &atomic.Uint32{}, | ||||||
| 		opts:      options, | 		opts:      options, | ||||||
| 		kopts:     kopts, | 		kopts:     kopts, | ||||||
| 		done:      make(chan struct{}), |  | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|   | |||||||
							
								
								
									
										117
									
								
								kgo_test.go
									
									
									
									
									
								
							
							
						
						
									
										117
									
								
								kgo_test.go
									
									
									
									
									
								
							| @@ -2,54 +2,51 @@ package kgo_test | |||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"context" | 	"context" | ||||||
| 	"os" |  | ||||||
| 	"strings" |  | ||||||
| 	"sync/atomic" | 	"sync/atomic" | ||||||
| 	"testing" | 	"testing" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kfake" | ||||||
| 	kg "github.com/twmb/franz-go/pkg/kgo" | 	kg "github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	kgo "go.unistack.org/micro-broker-kgo/v3" | 	kgo "go.unistack.org/micro-broker-kgo/v4" | ||||||
| 	"go.unistack.org/micro/v3/broker" | 	"go.unistack.org/micro/v4/broker" | ||||||
| 	"go.unistack.org/micro/v3/logger" | 	"go.unistack.org/micro/v4/codec" | ||||||
| 	"go.unistack.org/micro/v3/logger/slog" | 	"go.unistack.org/micro/v4/logger" | ||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v4/logger/slog" | ||||||
|  | 	"go.unistack.org/micro/v4/metadata" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var ( | var ( | ||||||
| 	msgcnt   = int64(1200) | 	msgcnt   = int64(1200) | ||||||
| 	group    = "38" | 	group    = "38" | ||||||
| 	prefill  = true | 	prefill  = true | ||||||
| 	loglevel = logger.DebugLevel | 	loglevel = logger.ErrorLevel | ||||||
|  | 	cluster  *kfake.Cluster | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var bm = &broker.Message{ | func TestMain(m *testing.M) { | ||||||
| 	Header: map[string]string{"hkey": "hval", metadata.HeaderTopic: "test"}, | 	cluster = kfake.MustCluster( | ||||||
| 	Body:   []byte(`"body"`), | 		kfake.AllowAutoTopicCreation(), | ||||||
|  | 	) | ||||||
|  | 	defer cluster.Close() | ||||||
|  | 	m.Run() | ||||||
| } | } | ||||||
|  |  | ||||||
| func TestFail(t *testing.T) { | func TestFail(t *testing.T) { | ||||||
| 	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { |  | ||||||
| 		t.Skip() |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	logger.DefaultLogger = slog.NewLogger() | 	logger.DefaultLogger = slog.NewLogger() | ||||||
| 	if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil { | 	if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil { | ||||||
| 		t.Fatal(err) | 		t.Fatal(err) | ||||||
| 	} | 	} | ||||||
| 	ctx := context.Background() | 	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( | 	b := kgo.NewBroker( | ||||||
| 		broker.Addrs(addrs...), | 		broker.ContentType("application/octet-stream"), | ||||||
|  | 		broker.Codec("application/octet-stream", codec.NewCodec()), | ||||||
|  | 		broker.Addrs(cluster.ListenAddrs()...), | ||||||
| 		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), | ||||||
| 			kg.AllowAutoTopicCreation(), | 			kg.AllowAutoTopicCreation(), | ||||||
| 		), | 		), | ||||||
| 	) | 	) | ||||||
| @@ -72,24 +69,30 @@ func TestFail(t *testing.T) { | |||||||
| 	}() | 	}() | ||||||
|  |  | ||||||
| 	t.Logf("broker health %v", b.Health()) | 	t.Logf("broker health %v", b.Health()) | ||||||
| 	msgs := make([]*broker.Message, 0, msgcnt) | 	msgs := make([]broker.Message, 0, msgcnt) | ||||||
| 	for i := int64(0); i < msgcnt; i++ { | 	for i := int64(0); i < msgcnt; i++ { | ||||||
| 		msgs = append(msgs, bm) | 		m, err := b.NewMessage(ctx, metadata.Pairs("hkey", "hval"), []byte(`test`)) | ||||||
|  | 		if err != nil { | ||||||
|  | 			t.Fatal(err) | ||||||
|  | 		} | ||||||
|  | 		msgs = append(msgs, m) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	go func() { | ||||||
| 		for _, msg := range msgs { | 		for _, msg := range msgs { | ||||||
| 		t.Logf("broker publish") | 			//		t.Logf("broker publish") | ||||||
| 			if err := b.Publish(ctx, "test", msg); err != nil { | 			if err := b.Publish(ctx, "test", msg); err != nil { | ||||||
| 				t.Fatal(err) | 				t.Fatal(err) | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
|  | 	}() | ||||||
| 	//	t.Skip() | 	//	t.Skip() | ||||||
|  |  | ||||||
| 	idx := int64(0) | 	idx := int64(0) | ||||||
| 	fn := func(msg broker.Event) error { | 	fn := func(msg broker.Message) error { | ||||||
| 		atomic.AddInt64(&idx, 1) | 		atomic.AddInt64(&idx, 1) | ||||||
| 		time.Sleep(500 * time.Millisecond) | 		time.Sleep(100 * time.Millisecond) | ||||||
| 		t.Logf("ack") | 		// t.Logf("ack") | ||||||
| 		return msg.Ack() | 		return msg.Ack() | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -100,6 +103,7 @@ func TestFail(t *testing.T) { | |||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		t.Fatal(err) | 		t.Fatal(err) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	defer func() { | 	defer func() { | ||||||
| 		if err := sub.Unsubscribe(ctx); err != nil { | 		if err := sub.Unsubscribe(ctx); err != nil { | ||||||
| 			t.Fatal(err) | 			t.Fatal(err) | ||||||
| @@ -112,21 +116,26 @@ func TestFail(t *testing.T) { | |||||||
| 			t.Logf("health works") | 			t.Logf("health works") | ||||||
| 			break | 			break | ||||||
| 		} | 		} | ||||||
| 		time.Sleep(1 * time.Second) | 		t.Logf("health sleep") | ||||||
|  | 		time.Sleep(100 * time.Millisecond) | ||||||
|  | 		if err := b.Disconnect(ctx); err != nil { | ||||||
|  | 			t.Fatal(err) | ||||||
|  | 		} | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| func TestConnect(t *testing.T) { | func TestConnect(t *testing.T) { | ||||||
| 	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { |  | ||||||
| 		t.Skip() |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	var addrs []string |  | ||||||
| 	ctx := context.TODO() | 	ctx := context.TODO() | ||||||
| 	b := kgo.NewBroker( | 	b := kgo.NewBroker( | ||||||
| 		broker.Addrs(addrs...), | 		broker.ContentType("application/octet-stream"), | ||||||
|  | 		broker.Codec("application/octet-stream", codec.NewCodec()), | ||||||
|  | 		broker.Addrs(cluster.ListenAddrs()...), | ||||||
| 		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), | ||||||
|  | 			kg.AllowAutoTopicCreation(), | ||||||
|  | 		), | ||||||
| 	) | 	) | ||||||
| 	if err := b.Init(); err != nil { | 	if err := b.Init(); err != nil { | ||||||
| 		t.Fatal(err) | 		t.Fatal(err) | ||||||
| @@ -138,26 +147,21 @@ func TestConnect(t *testing.T) { | |||||||
| } | } | ||||||
|  |  | ||||||
| func TestPubSub(t *testing.T) { | func TestPubSub(t *testing.T) { | ||||||
| 	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { |  | ||||||
| 		t.Skip() |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil { | 	if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil { | ||||||
| 		t.Fatal(err) | 		t.Fatal(err) | ||||||
| 	} | 	} | ||||||
| 	ctx := context.Background() | 	ctx := context.Background() | ||||||
|  |  | ||||||
| 	var addrs []string |  | ||||||
| 	if addr := os.Getenv("BROKER_ADDRS"); len(addr) == 0 { |  | ||||||
| 		addrs = []string{"127.0.0.1:29091", "127.0.0.2:29092", "127.0.0.3:29093"} |  | ||||||
| 	} else { |  | ||||||
| 		addrs = strings.Split(addr, ",") |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	b := kgo.NewBroker( | 	b := kgo.NewBroker( | ||||||
| 		broker.Addrs(addrs...), | 		broker.ContentType("application/octet-stream"), | ||||||
|  | 		broker.Codec("application/octet-stream", codec.NewCodec()), | ||||||
|  | 		broker.Addrs(cluster.ListenAddrs()...), | ||||||
| 		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), | ||||||
|  | 			kg.AllowAutoTopicCreation(), | ||||||
|  | 		), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
| 	if err := b.Init(); err != nil { | 	if err := b.Init(); err != nil { | ||||||
| @@ -174,19 +178,20 @@ func TestPubSub(t *testing.T) { | |||||||
| 		} | 		} | ||||||
| 	}() | 	}() | ||||||
| 	if prefill { | 	if prefill { | ||||||
| 		msgs := make([]*broker.Message, 0, msgcnt) | 		msgs := make([]broker.Message, 0, msgcnt) | ||||||
| 		for i := int64(0); i < msgcnt; i++ { | 		for i := int64(0); i < msgcnt; i++ { | ||||||
| 			msgs = append(msgs, bm) | 			m, _ := b.NewMessage(ctx, metadata.Pairs("hkey", "hval"), []byte(`test`)) | ||||||
|  | 			msgs = append(msgs, m) | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		if err := b.BatchPublish(ctx, msgs); err != nil { | 		if err := b.Publish(ctx, "test", msgs...); err != nil { | ||||||
| 			t.Fatal(err) | 			t.Fatal(err) | ||||||
| 		} | 		} | ||||||
| 		//	t.Skip() | 		//	t.Skip() | ||||||
| 	} | 	} | ||||||
| 	done := make(chan bool, 1) | 	done := make(chan bool, 1) | ||||||
| 	idx := int64(0) | 	idx := int64(0) | ||||||
| 	fn := func(msg broker.Event) error { | 	fn := func(msg broker.Message) error { | ||||||
| 		atomic.AddInt64(&idx, 1) | 		atomic.AddInt64(&idx, 1) | ||||||
| 		// time.Sleep(200 * time.Millisecond) | 		// time.Sleep(200 * time.Millisecond) | ||||||
| 		return msg.Ack() | 		return msg.Ack() | ||||||
| @@ -217,7 +222,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 { | ||||||
| 					t.Logf("processed %v\n", prc) | 					t.Logf("processed %v of %v\n", prc, msgcnt) | ||||||
| 				} | 				} | ||||||
| 			case <-ticker.C: | 			case <-ticker.C: | ||||||
| 				close(done) | 				close(done) | ||||||
|   | |||||||
| @@ -4,7 +4,7 @@ import ( | |||||||
| 	"context" | 	"context" | ||||||
|  |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	"go.unistack.org/micro/v3/logger" | 	"go.unistack.org/micro/v4/logger" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type mlogger struct { | type mlogger struct { | ||||||
|   | |||||||
							
								
								
									
										34
									
								
								meter.go
									
									
									
									
									
								
							
							
						
						
									
										34
									
								
								meter.go
									
									
									
									
									
								
							| @@ -6,7 +6,7 @@ import ( | |||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	"go.unistack.org/micro/v3/meter" | 	"go.unistack.org/micro/v4/meter" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type hookMeter struct { | type hookMeter struct { | ||||||
| @@ -32,27 +32,27 @@ var ( | |||||||
| ) | ) | ||||||
|  |  | ||||||
| const ( | const ( | ||||||
| 	metricBrokerConnects    = "micro_broker_connects_total" | 	metricBrokerConnects    = "broker_connects_total" | ||||||
| 	metricBrokerDisconnects = "micro_broker_disconnects_total" | 	metricBrokerDisconnects = "broker_disconnects_total" | ||||||
|  |  | ||||||
| 	metricBrokerWriteErrors        = "micro_broker_write_errors_total" | 	metricBrokerWriteErrors        = "broker_write_errors_total" | ||||||
| 	metricBrokerWriteBytes         = "micro_broker_write_bytes_total" | 	metricBrokerWriteBytes         = "broker_write_bytes_total" | ||||||
| 	metricBrokerWriteWaitLatencies = "micro_broker_write_wait_latencies" | 	metricBrokerWriteWaitLatencies = "broker_write_wait_latencies" | ||||||
| 	metricBrokerWriteLatencies     = "micro_broker_write_latencies" | 	metricBrokerWriteLatencies     = "broker_write_latencies" | ||||||
|  |  | ||||||
| 	metricBrokerReadErrors        = "micro_broker_read_errors_total" | 	metricBrokerReadErrors        = "broker_read_errors_total" | ||||||
| 	metricBrokerReadBytes         = "micro_broker_read_bytes_total" | 	metricBrokerReadBytes         = "broker_read_bytes_total" | ||||||
| 	metricBrokerReadWaitLatencies = "micro_broker_read_wait_latencies" | 	metricBrokerReadWaitLatencies = "broker_read_wait_latencies" | ||||||
| 	metricBrokerReadLatencies     = "micro_broker_read_latencies" | 	metricBrokerReadLatencies     = "broker_read_latencies" | ||||||
|  |  | ||||||
| 	metricBrokerThrottleLatencies = "micro_broker_throttle_latencies" | 	metricBrokerThrottleLatencies = "broker_throttle_latencies" | ||||||
|  |  | ||||||
| 	metricBrokerProduceBytesCompressed   = "micro_broker_produce_bytes_compressed_total" | 	metricBrokerProduceBytesCompressed   = "broker_produce_bytes_compressed_total" | ||||||
| 	metricBrokerProduceBytesUncompressed = "micro_broker_produce_bytes_uncompressed_total" | 	metricBrokerProduceBytesUncompressed = "broker_produce_bytes_uncompressed_total" | ||||||
| 	metricBrokerFetchBytesCompressed     = "micro_broker_consume_bytes_compressed_total" | 	metricBrokerFetchBytesCompressed     = "broker_consume_bytes_compressed_total" | ||||||
| 	metricBrokerFetchBytesUncompressed   = "micro_broker_consume_bytes_uncompressed_total" | 	metricBrokerFetchBytesUncompressed   = "broker_consume_bytes_uncompressed_total" | ||||||
|  |  | ||||||
| 	metricBrokerGroupErrors = "micro_broker_group_errors_total" | 	metricBrokerGroupErrors = "broker_group_errors_total" | ||||||
|  |  | ||||||
| 	labelNode    = "node_id" | 	labelNode    = "node_id" | ||||||
| 	labelSuccess = "success" | 	labelSuccess = "success" | ||||||
|   | |||||||
							
								
								
									
										23
									
								
								options.go
									
									
									
									
									
								
							
							
						
						
									
										23
									
								
								options.go
									
									
									
									
									
								
							| @@ -5,8 +5,7 @@ import ( | |||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	"go.unistack.org/micro/v3/broker" | 	"go.unistack.org/micro/v4/broker" | ||||||
| 	"go.unistack.org/micro/v3/client" |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var ( | var ( | ||||||
| @@ -15,7 +14,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 = 30 * time.Second | 	DefaultStatsInterval = 5 * time.Second | ||||||
|  |  | ||||||
| 	// DefaultSubscribeMaxInflight specifies how much messages keep inflight | 	// DefaultSubscribeMaxInflight specifies how much messages keep inflight | ||||||
| 	DefaultSubscribeMaxInflight = 100 | 	DefaultSubscribeMaxInflight = 100 | ||||||
| @@ -35,11 +34,6 @@ func PublishKey(key []byte) broker.PublishOption { | |||||||
| 	return broker.SetPublishOption(publishKey{}, key) | 	return broker.SetPublishOption(publishKey{}, key) | ||||||
| } | } | ||||||
|  |  | ||||||
| // ClientPublishKey set the kafka message key (client option) |  | ||||||
| func ClientPublishKey(key []byte) client.PublishOption { |  | ||||||
| 	return client.SetPublishOption(publishKey{}, key) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type optionsKey struct{} | type optionsKey struct{} | ||||||
|  |  | ||||||
| // Options pass additional options to broker | // Options pass additional options to broker | ||||||
| @@ -116,14 +110,9 @@ func PublishPromise(fn func(*kgo.Record, error)) broker.PublishOption { | |||||||
| 	return broker.SetPublishOption(publishPromiseKey{}, fn) | 	return broker.SetPublishOption(publishPromiseKey{}, fn) | ||||||
| } | } | ||||||
|  |  | ||||||
| // ClientPublishKey set the kafka message key (client option) | type subscribeMessagePoolKey struct{} | ||||||
| func ClientPublishPromise(fn func(*kgo.Record, error)) client.PublishOption { |  | ||||||
| 	return client.SetPublishOption(publishPromiseKey{}, fn) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type exposeLagKey struct{} | // SubscribeMessagePool optionaly enabled/disable message pool | ||||||
|  | func SubscribeMessagePool(b bool) broker.SubscribeOption { | ||||||
| // ExposeLag enabled subscriber lag via [meter.Meter] | 	return broker.SetSubscribeOption(subscribeMessagePoolKey{}, b) | ||||||
| func ExposeLag(b bool) broker.Option { |  | ||||||
| 	return broker.SetOption(exposeLagKey{}, b) |  | ||||||
| } | } | ||||||
|   | |||||||
							
								
								
									
										227
									
								
								subscriber.go
									
									
									
									
									
								
							
							
						
						
									
										227
									
								
								subscriber.go
									
									
									
									
									
								
							| @@ -3,17 +3,19 @@ package kgo | |||||||
| import ( | import ( | ||||||
| 	"context" | 	"context" | ||||||
| 	"fmt" | 	"fmt" | ||||||
|  | 	"strconv" | ||||||
| 	"sync" | 	"sync" | ||||||
| 	"sync/atomic" | 	"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" | 	"github.com/twmb/franz-go/pkg/kmsg" | ||||||
| 	"go.unistack.org/micro/v3/broker" | 	"go.unistack.org/micro/v4/broker" | ||||||
| 	"go.unistack.org/micro/v3/logger" | 	"go.unistack.org/micro/v4/logger" | ||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v4/metadata" | ||||||
| 	"go.unistack.org/micro/v3/semconv" | 	"go.unistack.org/micro/v4/semconv" | ||||||
| 	"go.unistack.org/micro/v3/tracer" | 	"go.unistack.org/micro/v4/tracer" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type tp struct { | type tp struct { | ||||||
| @@ -23,43 +25,34 @@ 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{} | 	quit        chan struct{} | ||||||
| 	done        chan struct{} | 	done        chan struct{} | ||||||
| 	recs        chan kgo.FetchTopicPartition | 	recs        chan kgo.FetchTopicPartition | ||||||
|  |  | ||||||
| 	handler broker.Handler |  | ||||||
|  |  | ||||||
| 	kopts       broker.Options | 	kopts       broker.Options | ||||||
| 	opts  broker.SubscribeOptions |  | ||||||
|  |  | ||||||
| 	partition   int32 | 	partition   int32 | ||||||
|  | 	opts        broker.SubscribeOptions | ||||||
|  | 	handler     interface{} | ||||||
|  | 	connected   *atomic.Uint32 | ||||||
|  | 	messagePool bool | ||||||
| } | } | ||||||
|  |  | ||||||
| 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 | ||||||
| 	connected *atomic.Uint32 | 	topic       string | ||||||
|  | 	messagePool bool | ||||||
| 	handler broker.Handler | 	handler     interface{} | ||||||
|  |  | ||||||
| 	done        chan struct{} | 	done        chan struct{} | ||||||
|  |  | ||||||
| 	kopts       broker.Options | 	kopts       broker.Options | ||||||
| 	opts        broker.SubscribeOptions | 	opts        broker.SubscribeOptions | ||||||
|  |  | ||||||
|  | 	connected *atomic.Uint32 | ||||||
|  | 	sync.RWMutex | ||||||
| 	closed       bool | 	closed       bool | ||||||
| 	fatalOnError bool | 	fatalOnError bool | ||||||
|  |  | ||||||
| 	sync.RWMutex |  | ||||||
| } | } | ||||||
|  |  | ||||||
| func (s *Subscriber) Client() *kgo.Client { | func (s *Subscriber) Client() *kgo.Client { | ||||||
| @@ -95,13 +88,46 @@ 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))).Set(uint64(l.Lag)) | ||||||
|  | 				} | ||||||
|  | 				s.Unlock() | ||||||
|  |  | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  | 	}() | ||||||
|  |  | ||||||
| 	for { | 	for { | ||||||
| 		select { | 		select { | ||||||
| 		case <-ctx.Done(): | 		case <-ctx.Done(): | ||||||
| @@ -116,16 +142,17 @@ 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) { | ||||||
| 				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) | 				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) { | ||||||
| 				tps := tp{p.Topic, p.Partition} | 				tps := tp{p.Topic, p.Partition} | ||||||
| 				s.consumers[tps].recs <- p | 				s.Lock() | ||||||
|  | 				c := s.consumers[tps] | ||||||
|  | 				s.Unlock() | ||||||
|  | 				if c != nil { | ||||||
|  | 					c.recs <- p | ||||||
|  | 				} | ||||||
| 			}) | 			}) | ||||||
| 			s.c.AllowRebalance() | 			s.c.AllowRebalance() | ||||||
| 		} | 		} | ||||||
| @@ -139,11 +166,15 @@ 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 { | ||||||
| 			tps := tp{topic, partition} | 			tps := tp{topic, partition} | ||||||
|  | 			s.Lock() | ||||||
| 			pc, ok := s.consumers[tps] | 			pc, ok := s.consumers[tps] | ||||||
|  | 			s.Unlock() | ||||||
| 			if !ok { | 			if !ok { | ||||||
| 				continue | 				continue | ||||||
| 			} | 			} | ||||||
|  | 			s.Lock() | ||||||
| 			delete(s.consumers, tps) | 			delete(s.consumers, tps) | ||||||
|  | 			s.Unlock() | ||||||
| 			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)) | ||||||
| @@ -194,6 +225,7 @@ func (s *Subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[str | |||||||
| 				done:        make(chan struct{}), | 				done:        make(chan struct{}), | ||||||
| 				recs:        make(chan kgo.FetchTopicPartition, 100), | 				recs:        make(chan kgo.FetchTopicPartition, 100), | ||||||
| 				handler:     s.handler, | 				handler:     s.handler, | ||||||
|  | 				messagePool: s.messagePool, | ||||||
| 				kopts:       s.kopts, | 				kopts:       s.kopts, | ||||||
| 				opts:        s.opts, | 				opts:        s.opts, | ||||||
| 				connected:   s.connected, | 				connected:   s.connected, | ||||||
| @@ -207,16 +239,15 @@ func (s *Subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[str | |||||||
| } | } | ||||||
|  |  | ||||||
| func (pc *consumer) consume() { | func (pc *consumer) consume() { | ||||||
|  | 	var err error | ||||||
|  |  | ||||||
| 	defer close(pc.done) | 	defer close(pc.done) | ||||||
| 	if pc.kopts.Logger.V(logger.DebugLevel) { | 	if pc.kopts.Logger.V(logger.DebugLevel) { | ||||||
| 		pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("starting, topic %s partition %d", pc.topic, pc.partition)) | 		pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("starting, topic %s partition %d", pc.topic, pc.partition)) | ||||||
| 		defer pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("killing, topic %s partition %d", pc.topic, pc.partition)) | 		defer pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("killing, topic %s partition %d", pc.topic, pc.partition)) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	eh := pc.kopts.ErrorHandler | 	var pm *kgoMessage | ||||||
| 	if pc.opts.ErrorHandler != nil { |  | ||||||
| 		eh = pc.opts.ErrorHandler |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	for { | 	for { | ||||||
| 		select { | 		select { | ||||||
| @@ -227,116 +258,54 @@ func (pc *consumer) consume() { | |||||||
| 				ctx, sp := pc.htracer.WithProcessSpan(record) | 				ctx, sp := pc.htracer.WithProcessSpan(record) | ||||||
| 				ts := time.Now() | 				ts := time.Now() | ||||||
| 				pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Inc() | 				pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Inc() | ||||||
| 				p := eventPool.Get().(*event) |  | ||||||
| 				p.msg.Header = nil | 				if pc.messagePool { | ||||||
| 				p.msg.Body = nil | 					pm = messagePool.Get().(*kgoMessage) | ||||||
| 				p.topic = record.Topic |  | ||||||
| 				p.err = nil |  | ||||||
| 				p.ack = false |  | ||||||
| 				p.msg.Header = metadata.New(len(record.Headers)) |  | ||||||
| 				p.ctx = ctx |  | ||||||
| 				for _, hdr := range record.Headers { |  | ||||||
| 					p.msg.Header.Set(hdr.Key, string(hdr.Value)) |  | ||||||
| 				} |  | ||||||
| 				if pc.kopts.Codec.String() == "noop" { |  | ||||||
| 					p.msg.Body = record.Value |  | ||||||
| 				} else if pc.opts.BodyOnly { |  | ||||||
| 					p.msg.Body = record.Value |  | ||||||
| 				} else { | 				} else { | ||||||
| 					if sp != nil { | 					pm = &kgoMessage{} | ||||||
| 						sp.AddEvent("codec unmarshal start") |  | ||||||
| 				} | 				} | ||||||
| 					err := pc.kopts.Codec.Unmarshal(record.Value, p.msg) | 				pm.body = record.Value | ||||||
| 					if sp != nil { | 				pm.topic = record.Topic | ||||||
| 						sp.AddEvent("codec unmarshal stop") | 				pm.ack = false | ||||||
|  | 				pm.hdr = metadata.New(len(record.Headers)) | ||||||
|  | 				pm.ctx = ctx | ||||||
|  | 				for _, hdr := range record.Headers { | ||||||
|  | 					pm.hdr.Set(hdr.Key, string(hdr.Value)) | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
|  | 				switch h := pc.handler.(type) { | ||||||
|  | 				case func(broker.Message) error: | ||||||
|  | 					err = h(pm) | ||||||
|  | 				case func([]broker.Message) error: | ||||||
|  | 					err = h([]broker.Message{pm}) | ||||||
|  | 				} | ||||||
|  |  | ||||||
|  | 				pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec() | ||||||
| 				if err != nil { | 				if err != nil { | ||||||
| 					if sp != nil { | 					if sp != nil { | ||||||
| 						sp.SetStatus(tracer.SpanStatusError, err.Error()) | 						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 | 				} else if pc.opts.AutoAck { | ||||||
| 						p.msg.Body = record.Value | 					pm.ack = true | ||||||
| 						if eh != nil { | 				} | ||||||
| 							_ = eh(p) |  | ||||||
| 							pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec() | 				te := time.Since(ts) | ||||||
| 							if p.ack { | 				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()) | ||||||
|  |  | ||||||
|  | 				ack := pm.ack | ||||||
|  | 				if pc.messagePool { | ||||||
|  | 					messagePool.Put(p) | ||||||
|  | 				} | ||||||
|  | 				if ack { | ||||||
| 					pc.c.MarkCommitRecords(record) | 					pc.c.MarkCommitRecords(record) | ||||||
| 				} else { | 				} else { | ||||||
| 								eventPool.Put(p) |  | ||||||
| 								//								pc.connected.Store(0) |  | ||||||
| 								pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?") |  | ||||||
| 								return |  | ||||||
| 							} |  | ||||||
| 							eventPool.Put(p) |  | ||||||
| 							te := time.Since(ts) |  | ||||||
| 							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()) |  | ||||||
| 							continue |  | ||||||
| 						} else { |  | ||||||
| 							pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: unmarshal error", err) |  | ||||||
| 						} |  | ||||||
| 						te := time.Since(ts) |  | ||||||
| 						pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec() |  | ||||||
| 						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()) |  | ||||||
| 						eventPool.Put(p) |  | ||||||
| 						//						pc.connected.Store(0) |  | ||||||
| 						pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] Unmarshal err not handled wtf?") |  | ||||||
| 					if sp != nil { | 					if sp != nil { | ||||||
| 						sp.Finish() | 						sp.Finish() | ||||||
| 					} | 					} | ||||||
| 						return |  | ||||||
| 					} |  | ||||||
| 				} |  | ||||||
| 				if sp != nil { |  | ||||||
| 					sp.AddEvent("handler start") |  | ||||||
| 				} |  | ||||||
| 				err := pc.handler(p) |  | ||||||
| 				if sp != nil { |  | ||||||
| 					sp.AddEvent("handler stop") |  | ||||||
| 				} |  | ||||||
| 				if err == nil { |  | ||||||
| 					pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "success").Inc() |  | ||||||
| 				} else { |  | ||||||
| 					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.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec() |  | ||||||
| 				if err == nil && pc.opts.AutoAck { |  | ||||||
| 					p.ack = true |  | ||||||
| 				} else if err != nil { |  | ||||||
| 					p.err = err |  | ||||||
| 					if eh != nil { |  | ||||||
| 						if sp != nil { |  | ||||||
| 							sp.AddEvent("error handler start") |  | ||||||
| 						} |  | ||||||
| 						_ = eh(p) |  | ||||||
| 						if sp != nil { |  | ||||||
| 							sp.AddEvent("error handler stop") |  | ||||||
| 						} |  | ||||||
| 					} else { |  | ||||||
| 						if pc.kopts.Logger.V(logger.ErrorLevel) { |  | ||||||
| 							pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: subscriber error", err) |  | ||||||
| 						} |  | ||||||
| 					} |  | ||||||
| 				} |  | ||||||
| 				te := time.Since(ts) |  | ||||||
| 				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()) |  | ||||||
| 				if p.ack { |  | ||||||
| 					eventPool.Put(p) |  | ||||||
| 					pc.c.MarkCommitRecords(record) |  | ||||||
| 				} else { |  | ||||||
| 					eventPool.Put(p) |  | ||||||
| 					//					pc.connected.Store(0) | 					//					pc.connected.Store(0) | ||||||
| 					pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?") | 					pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] message not commited") | ||||||
| 					if sp != nil { |  | ||||||
| 						sp.SetStatus(tracer.SpanStatusError, "ErrLostMessage") |  | ||||||
| 						sp.Finish() |  | ||||||
| 					} |  | ||||||
| 					return | 					return | ||||||
| 				} | 				} | ||||||
| 				if sp != nil { | 				if sp != nil { | ||||||
|   | |||||||
| @@ -6,8 +6,8 @@ import ( | |||||||
|  |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	semconv "go.opentelemetry.io/otel/semconv/v1.18.0" | 	semconv "go.opentelemetry.io/otel/semconv/v1.18.0" | ||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v4/metadata" | ||||||
| 	"go.unistack.org/micro/v3/tracer" | 	"go.unistack.org/micro/v4/tracer" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type hookTracer struct { | type hookTracer struct { | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user