Compare commits
	
		
			14 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| ffd10d7ea9 | |||
|  | c4f8de4aca | ||
| 63d82be92a | |||
| cced3b84c1 | |||
|  | 82c1bda50f | ||
| 4b0b70e7d0 | |||
|  | da88718e03 | ||
| aed304b7e3 | |||
| b796c43257 | |||
| b0691edf82 | |||
| d43b59f2f3 | |||
| f976516d6b | |||
| 8f5c03ad60 | |||
|  | 9e9c1434ff | 
| @@ -1,2 +1,2 @@ | ||||
| # micro-broker-kgo | ||||
|  | ||||
|  | ||||
|   | ||||
							
								
								
									
										10
									
								
								errors.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								errors.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,10 @@ | ||||
| package kgo | ||||
|  | ||||
| import ( | ||||
| 	"context" | ||||
| 	"errors" | ||||
| ) | ||||
|  | ||||
| func isContextError(err error) bool { | ||||
| 	return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) | ||||
| } | ||||
							
								
								
									
										18
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										18
									
								
								go.mod
									
									
									
									
									
								
							| @@ -1,23 +1,27 @@ | ||||
| module go.unistack.org/micro-broker-kgo/v4 | ||||
|  | ||||
| go 1.23.8 | ||||
| go 1.24.0 | ||||
|  | ||||
| require ( | ||||
| 	github.com/stretchr/testify v1.11.1 | ||||
| 	github.com/twmb/franz-go v1.19.5 | ||||
| 	github.com/twmb/franz-go/pkg/kadm v1.16.0 | ||||
| 	github.com/twmb/franz-go/pkg/kadm v1.16.1 | ||||
| 	github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3 | ||||
| 	github.com/twmb/franz-go/pkg/kmsg v1.11.2 | ||||
| 	go.opentelemetry.io/otel v1.36.0 | ||||
| 	go.unistack.org/micro/v4 v4.1.17 | ||||
| 	go.opentelemetry.io/otel v1.38.0 | ||||
| 	go.unistack.org/micro/v4 v4.1.21 | ||||
| ) | ||||
|  | ||||
| require ( | ||||
| 	github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect | ||||
| 	github.com/google/uuid v1.6.0 // indirect | ||||
| 	github.com/klauspost/compress v1.18.0 // indirect | ||||
| 	github.com/matoous/go-nanoid v1.5.1 // indirect | ||||
| 	github.com/pierrec/lz4/v4 v4.1.22 // indirect | ||||
| 	github.com/spf13/cast v1.9.2 // indirect | ||||
| 	github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect | ||||
| 	github.com/spf13/cast v1.10.0 // indirect | ||||
| 	go.unistack.org/micro-proto/v4 v4.1.0 // indirect | ||||
| 	golang.org/x/crypto v0.39.0 // indirect | ||||
| 	google.golang.org/protobuf v1.36.6 // indirect | ||||
| 	golang.org/x/crypto v0.43.0 // indirect | ||||
| 	google.golang.org/protobuf v1.36.10 // indirect | ||||
| 	gopkg.in/yaml.v3 v3.0.1 // indirect | ||||
| ) | ||||
|   | ||||
							
								
								
									
										43
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										43
									
								
								go.sum
									
									
									
									
									
								
							| @@ -20,39 +20,30 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI | ||||
| github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | ||||
| 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/spf13/cast v1.8.0 h1:gEN9K4b8Xws4EX0+a0reLmhq8moKn7ntRlQYgjPeCDk= | ||||
| github.com/spf13/cast v1.8.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= | ||||
| github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= | ||||
| github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= | ||||
| github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= | ||||
| github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= | ||||
| github.com/twmb/franz-go v1.19.1 h1:cOhDFUkGvUFHSQ7UYW6bO77BJa2fYEk5mA2AX+1NIdE= | ||||
| github.com/twmb/franz-go v1.19.1/go.mod h1:4kFJ5tmbbl7asgwAGVuyG1ZMx0NNpYk7EqflvWfPCpM= | ||||
| github.com/twmb/franz-go v1.19.4 h1:0ktflzm5YU7+YYdie8RQWFcU9uDJ03xLefplO1iMwO4= | ||||
| github.com/twmb/franz-go v1.19.4/go.mod h1:4kFJ5tmbbl7asgwAGVuyG1ZMx0NNpYk7EqflvWfPCpM= | ||||
| github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= | ||||
| github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= | ||||
| github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= | ||||
| github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= | ||||
| github.com/twmb/franz-go v1.19.5 h1:W7+o8D0RsQsedqib71OVlLeZ0zI6CbFra7yTYhZTs5Y= | ||||
| github.com/twmb/franz-go v1.19.5/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/kadm v1.16.1 h1:IEkrhTljgLHJ0/hT/InhXGjPdmWfFvxp7o/MR7vJ8cw= | ||||
| github.com/twmb/franz-go/pkg/kadm v1.16.1/go.mod h1:Ue/ye1cc9ipsQFg7udFbbGiFNzQMqiH73fGC2y0rwyc= | ||||
| 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/go.mod h1:CFfkkLysDNmukPYhGzuUcDtf46gQSqCZHMW1T4Z+wDE= | ||||
| go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= | ||||
| go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= | ||||
| go.opentelemetry.io/otel v1.36.0 h1:UumtzIklRBY6cI/lllNZlALOF5nNIzJVb16APdvgTXg= | ||||
| go.opentelemetry.io/otel v1.36.0/go.mod h1:/TcFMXYjyRNh8khOAO9ybYkqaDBb/70aVwkNML4pP8E= | ||||
| go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= | ||||
| go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= | ||||
| go.unistack.org/micro-proto/v4 v4.1.0 h1:qPwL2n/oqh9RE3RTTDgt28XK3QzV597VugQPaw9lKUk= | ||||
| go.unistack.org/micro-proto/v4 v4.1.0/go.mod h1:ArmK7o+uFvxSY3dbJhKBBX4Pm1rhWdLEFf3LxBrMtec= | ||||
| go.unistack.org/micro/v4 v4.1.14 h1:6EotPq9kz/gaFb5YulHdKuuUwmj/7Hk44DpOlzh/A6k= | ||||
| go.unistack.org/micro/v4 v4.1.14/go.mod h1:xleO2M5Yxh4s6I+RUcLrEpUjobefh+71ctrdIfn7TUs= | ||||
| go.unistack.org/micro/v4 v4.1.17 h1:26QDtRSYVpozYuassyvLP4sEQRo3dxgD3sVILRXmIPo= | ||||
| go.unistack.org/micro/v4 v4.1.17/go.mod h1:xleO2M5Yxh4s6I+RUcLrEpUjobefh+71ctrdIfn7TUs= | ||||
| golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= | ||||
| golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= | ||||
| golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= | ||||
| golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= | ||||
| google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= | ||||
| google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= | ||||
| go.unistack.org/micro/v4 v4.1.21 h1:F9PrbI1BhXSDS0FopwcO5wWrT2Xh38w9VhVZZBHjfg8= | ||||
| go.unistack.org/micro/v4 v4.1.21/go.mod h1:nlBXTbx0rQrSZX4HPp2m57PHmpuGPWUd0O+jpUIiPto= | ||||
| golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= | ||||
| golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= | ||||
| 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/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | ||||
|   | ||||
| @@ -26,50 +26,83 @@ var ( | ||||
| ) | ||||
| 
 | ||||
| func (m *hookEvent) OnGroupManageError(err error) { | ||||
| 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||
| 		m.connected.Store(0) | ||||
| 	switch { | ||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||
| 		return | ||||
| 	default: | ||||
| 		ctx := context.TODO() | ||||
| 		logMsg := "kgo.OnGroupManageError" | ||||
| 
 | ||||
| 		if m.fatalOnError { | ||||
| 			m.log.Fatal(context.TODO(), "kgo.OnGroupManageError", err) | ||||
| 			m.log.Fatal(ctx, logMsg, err) | ||||
| 		} else { | ||||
| 			m.log.Error(ctx, logMsg, err) | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func (m *hookEvent) OnBrokerConnect(_ kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) { | ||||
| 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||
| 		m.connected.Store(0) | ||||
| 	switch { | ||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||
| 		return | ||||
| 	default: | ||||
| 		ctx := context.TODO() | ||||
| 		logMsg := "kgo.OnBrokerConnect" | ||||
| 
 | ||||
| 		if m.fatalOnError { | ||||
| 			m.log.Fatal(context.TODO(), "kgo.OnBrokerConnect", err) | ||||
| 			m.log.Fatal(ctx, logMsg, err) | ||||
| 		} else { | ||||
| 			m.log.Error(ctx, logMsg, err) | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func (m *hookEvent) OnBrokerDisconnect(_ kgo.BrokerMetadata, _ net.Conn) { | ||||
| 	// m.connected.Store(0) | ||||
| } | ||||
| func (m *hookEvent) OnBrokerDisconnect(_ kgo.BrokerMetadata, _ net.Conn) {} | ||||
| 
 | ||||
| func (m *hookEvent) OnBrokerWrite(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | ||||
| 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||
| 		m.connected.Store(0) | ||||
| 	switch { | ||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||
| 		return | ||||
| 	default: | ||||
| 		ctx := context.TODO() | ||||
| 		logMsg := "kgo.OnBrokerWrite" | ||||
| 
 | ||||
| 		if m.fatalOnError { | ||||
| 			m.log.Fatal(context.TODO(), "kgo.OnBrokerWrite", err) | ||||
| 			m.log.Fatal(ctx, logMsg, err) | ||||
| 		} else { | ||||
| 			m.log.Error(ctx, logMsg, err) | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func (m *hookEvent) OnBrokerRead(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | ||||
| 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||
| 		m.connected.Store(0) | ||||
| 	switch { | ||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||
| 		return | ||||
| 	default: | ||||
| 		ctx := context.TODO() | ||||
| 		logMsg := "kgo.OnBrokerRead" | ||||
| 
 | ||||
| 		if m.fatalOnError { | ||||
| 			m.log.Fatal(context.TODO(), "kgo.OnBrokerRead", err) | ||||
| 			m.log.Fatal(ctx, logMsg, err) | ||||
| 		} else { | ||||
| 			m.log.Error(ctx, logMsg, err) | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func (m *hookEvent) OnProduceRecordUnbuffered(_ *kgo.Record, err error) { | ||||
| 	if err != nil && !kgo.IsRetryableBrokerErr(err) { | ||||
| 		m.connected.Store(0) | ||||
| 	switch { | ||||
| 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||
| 		return | ||||
| 	default: | ||||
| 		ctx := context.TODO() | ||||
| 		logMsg := "kgo.OnProduceRecordUnbuffered" | ||||
| 
 | ||||
| 		if m.fatalOnError { | ||||
| 			m.log.Fatal(context.TODO(), "kgo.OnProduceRecordUnbuffered", err) | ||||
| 			m.log.Fatal(ctx, logMsg, err) | ||||
| 		} else { | ||||
| 			m.log.Error(ctx, logMsg, err) | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										471
									
								
								hook_event_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										471
									
								
								hook_event_test.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,471 @@ | ||||
| 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/v4/logger" | ||||
| ) | ||||
|  | ||||
| func TestHookEvent_OnGroupManageError(t *testing.T) { | ||||
| 	tests := []struct { | ||||
| 		name                  string | ||||
| 		inputErr              error | ||||
| 		fatalOnError          bool | ||||
| 		expectedErrorIsCalled bool | ||||
| 		expectedErrorMsg      string | ||||
| 		expectedFatalIsCalled bool | ||||
| 		expectedFatalMsg      string | ||||
| 	}{ | ||||
| 		{ | ||||
| 			name:                  "error is nil", | ||||
| 			inputErr:              nil, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context canceled", | ||||
| 			inputErr:              context.Canceled, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context deadline exceeded", | ||||
| 			inputErr:              context.DeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: deadline exceeded (os package)", | ||||
| 			inputErr:              os.ErrDeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: EOF (io package)", | ||||
| 			inputErr:              io.EOF, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: closed network connection (net package)", | ||||
| 			inputErr:              net.ErrClosed, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (non-fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          false, | ||||
| 			expectedErrorIsCalled: true, | ||||
| 			expectedErrorMsg:      "kgo.OnGroupManageError", | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          true, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: true, | ||||
| 			expectedFatalMsg:      "kgo.OnGroupManageError", | ||||
| 		}, | ||||
| 	} | ||||
|  | ||||
| 	for _, tt := range tests { | ||||
| 		t.Run(tt.name, func(t *testing.T) { | ||||
| 			log := &mockLogger{} | ||||
| 			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError} | ||||
| 			he.OnGroupManageError(tt.inputErr) | ||||
| 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||
| 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||
| 			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled) | ||||
| 			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg) | ||||
| 		}) | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func TestHookEvent_OnBrokerConnect(t *testing.T) { | ||||
| 	tests := []struct { | ||||
| 		name                  string | ||||
| 		inputErr              error | ||||
| 		fatalOnError          bool | ||||
| 		expectedErrorIsCalled bool | ||||
| 		expectedErrorMsg      string | ||||
| 		expectedFatalIsCalled bool | ||||
| 		expectedFatalMsg      string | ||||
| 	}{ | ||||
| 		{ | ||||
| 			name:                  "error is nil", | ||||
| 			inputErr:              nil, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context canceled", | ||||
| 			inputErr:              context.Canceled, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context deadline exceeded", | ||||
| 			inputErr:              context.DeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: deadline exceeded (os package)", | ||||
| 			inputErr:              os.ErrDeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: EOF (io package)", | ||||
| 			inputErr:              io.EOF, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: closed network connection (net package)", | ||||
| 			inputErr:              net.ErrClosed, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (non-fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          false, | ||||
| 			expectedErrorIsCalled: true, | ||||
| 			expectedErrorMsg:      "kgo.OnBrokerConnect", | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          true, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: true, | ||||
| 			expectedFatalMsg:      "kgo.OnBrokerConnect", | ||||
| 		}, | ||||
| 	} | ||||
|  | ||||
| 	for _, tt := range tests { | ||||
| 		t.Run(tt.name, func(t *testing.T) { | ||||
| 			log := &mockLogger{} | ||||
| 			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError} | ||||
| 			he.OnBrokerConnect(kgo.BrokerMetadata{}, 0, nil, tt.inputErr) | ||||
| 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||
| 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||
| 			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled) | ||||
| 			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg) | ||||
| 		}) | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func TestHookEvent_OnBrokerWrite(t *testing.T) { | ||||
| 	tests := []struct { | ||||
| 		name                  string | ||||
| 		inputErr              error | ||||
| 		fatalOnError          bool | ||||
| 		expectedErrorIsCalled bool | ||||
| 		expectedErrorMsg      string | ||||
| 		expectedFatalIsCalled bool | ||||
| 		expectedFatalMsg      string | ||||
| 	}{ | ||||
| 		{ | ||||
| 			name:                  "error is nil", | ||||
| 			inputErr:              nil, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context canceled", | ||||
| 			inputErr:              context.Canceled, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context deadline exceeded", | ||||
| 			inputErr:              context.DeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: deadline exceeded (os package)", | ||||
| 			inputErr:              os.ErrDeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: EOF (io package)", | ||||
| 			inputErr:              io.EOF, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: closed network connection (net package)", | ||||
| 			inputErr:              net.ErrClosed, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (non-fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          false, | ||||
| 			expectedErrorIsCalled: true, | ||||
| 			expectedErrorMsg:      "kgo.OnBrokerWrite", | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          true, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: true, | ||||
| 			expectedFatalMsg:      "kgo.OnBrokerWrite", | ||||
| 		}, | ||||
| 	} | ||||
|  | ||||
| 	for _, tt := range tests { | ||||
| 		t.Run(tt.name, func(t *testing.T) { | ||||
| 			log := &mockLogger{} | ||||
| 			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError} | ||||
| 			he.OnBrokerWrite(kgo.BrokerMetadata{}, 0, 0, 0, 0, tt.inputErr) | ||||
| 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||
| 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||
| 			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled) | ||||
| 			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg) | ||||
| 		}) | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func TestHookEvent_OnBrokerRead(t *testing.T) { | ||||
| 	tests := []struct { | ||||
| 		name                  string | ||||
| 		inputErr              error | ||||
| 		fatalOnError          bool | ||||
| 		expectedErrorIsCalled bool | ||||
| 		expectedErrorMsg      string | ||||
| 		expectedFatalIsCalled bool | ||||
| 		expectedFatalMsg      string | ||||
| 	}{ | ||||
| 		{ | ||||
| 			name:                  "error is nil", | ||||
| 			inputErr:              nil, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context canceled", | ||||
| 			inputErr:              context.Canceled, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context deadline exceeded", | ||||
| 			inputErr:              context.DeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: deadline exceeded (os package)", | ||||
| 			inputErr:              os.ErrDeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: EOF (io package)", | ||||
| 			inputErr:              io.EOF, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: closed network connection (net package)", | ||||
| 			inputErr:              net.ErrClosed, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (non-fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          false, | ||||
| 			expectedErrorIsCalled: true, | ||||
| 			expectedErrorMsg:      "kgo.OnBrokerRead", | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          true, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: true, | ||||
| 			expectedFatalMsg:      "kgo.OnBrokerRead", | ||||
| 		}, | ||||
| 	} | ||||
|  | ||||
| 	for _, tt := range tests { | ||||
| 		t.Run(tt.name, func(t *testing.T) { | ||||
| 			log := &mockLogger{} | ||||
| 			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError} | ||||
| 			he.OnBrokerRead(kgo.BrokerMetadata{}, 0, 0, 0, 0, tt.inputErr) | ||||
| 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||
| 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||
| 			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled) | ||||
| 			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg) | ||||
| 		}) | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func TestHookEvent_OnProduceRecordUnbuffered(t *testing.T) { | ||||
| 	tests := []struct { | ||||
| 		name                  string | ||||
| 		inputErr              error | ||||
| 		fatalOnError          bool | ||||
| 		expectedErrorIsCalled bool | ||||
| 		expectedErrorMsg      string | ||||
| 		expectedFatalIsCalled bool | ||||
| 		expectedFatalMsg      string | ||||
| 	}{ | ||||
| 		{ | ||||
| 			name:                  "error is nil", | ||||
| 			inputErr:              nil, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context canceled", | ||||
| 			inputErr:              context.Canceled, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "context deadline exceeded", | ||||
| 			inputErr:              context.DeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: deadline exceeded (os package)", | ||||
| 			inputErr:              os.ErrDeadlineExceeded, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: EOF (io package)", | ||||
| 			inputErr:              io.EOF, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "retryable error: closed network connection (net package)", | ||||
| 			inputErr:              net.ErrClosed, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (non-fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          false, | ||||
| 			expectedErrorIsCalled: true, | ||||
| 			expectedErrorMsg:      "kgo.OnProduceRecordUnbuffered", | ||||
| 			expectedFatalIsCalled: false, | ||||
| 		}, | ||||
| 		{ | ||||
| 			name:                  "some error (fatal)", | ||||
| 			inputErr:              errors.New("some error"), | ||||
| 			fatalOnError:          true, | ||||
| 			expectedErrorIsCalled: false, | ||||
| 			expectedFatalIsCalled: true, | ||||
| 			expectedFatalMsg:      "kgo.OnProduceRecordUnbuffered", | ||||
| 		}, | ||||
| 	} | ||||
|  | ||||
| 	for _, tt := range tests { | ||||
| 		t.Run(tt.name, func(t *testing.T) { | ||||
| 			log := &mockLogger{} | ||||
| 			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError} | ||||
| 			he.OnProduceRecordUnbuffered(&kgo.Record{}, tt.inputErr) | ||||
| 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||
| 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||
| 			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled) | ||||
| 			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg) | ||||
| 		}) | ||||
| 	} | ||||
| } | ||||
|  | ||||
| // Mocks | ||||
|  | ||||
| type mockLogger struct { | ||||
| 	errorIsCalled bool | ||||
| 	errorMsg      string | ||||
|  | ||||
| 	fatalIsCalled bool | ||||
| 	fatalMsg      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(ctx context.Context, msg string, args ...interface{}) { | ||||
| 	m.fatalIsCalled = true | ||||
| 	m.fatalMsg = msg | ||||
| } | ||||
|  | ||||
| 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") | ||||
| } | ||||
							
								
								
									
										158
									
								
								kgo.go
									
									
									
									
									
								
							
							
						
						
									
										158
									
								
								kgo.go
									
									
									
									
									
								
							| @@ -6,11 +6,13 @@ import ( | ||||
| 	"errors" | ||||
| 	"fmt" | ||||
| 	"math/rand/v2" | ||||
| 	"strconv" | ||||
| 	"strings" | ||||
| 	"sync" | ||||
| 	"sync/atomic" | ||||
| 	"time" | ||||
|  | ||||
| 	"github.com/twmb/franz-go/pkg/kadm" | ||||
| 	"github.com/twmb/franz-go/pkg/kgo" | ||||
| 	"github.com/twmb/franz-go/pkg/kmsg" | ||||
| 	"go.unistack.org/micro/v4/broker" | ||||
| @@ -156,7 +158,7 @@ func (b *Broker) NewMessage(ctx context.Context, hdr metadata.Metadata, body int | ||||
| 		options.ContentType = b.opts.ContentType | ||||
| 	} | ||||
|  | ||||
| 	m := &kgoMessage{ctx: ctx, hdr: hdr, opts: options} | ||||
| 	m := &kgoMessage{ctx: ctx, hdr: hdr.Copy(), opts: options} | ||||
| 	c, err := b.newCodec(m.opts.ContentType) | ||||
| 	if err == nil { | ||||
| 		m.body, err = c.Marshal(body) | ||||
| @@ -165,6 +167,8 @@ func (b *Broker) NewMessage(ctx context.Context, hdr metadata.Metadata, body int | ||||
| 		return nil, err | ||||
| 	} | ||||
|  | ||||
| 	m.hdr.Set(metadata.HeaderContentType, m.opts.ContentType) | ||||
|  | ||||
| 	return m, nil | ||||
| } | ||||
|  | ||||
| @@ -243,6 +247,68 @@ func (k *Broker) Connect(ctx context.Context) error { | ||||
| 	k.connected.Store(1) | ||||
| 	k.mu.Unlock() | ||||
|  | ||||
| 	exposeLag := false | ||||
| 	if k.opts.Context != nil { | ||||
| 		if v, ok := k.opts.Context.Value(exposeLagKey{}).(bool); ok && v { | ||||
| 			exposeLag = v | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	if exposeLag { | ||||
| 		var mu sync.Mutex | ||||
| 		var lastUpdate time.Time | ||||
| 		type pl struct { | ||||
| 			p string | ||||
| 			l float64 | ||||
| 		} | ||||
|  | ||||
| 		lag := make(map[string]map[string]pl) // topic => group => partition => lag | ||||
| 		ac := kadm.NewClient(k.c) | ||||
|  | ||||
| 		updateStats := func() { | ||||
| 			mu.Lock() | ||||
| 			if time.Since(lastUpdate) < DefaultStatsInterval { | ||||
| 				return | ||||
| 			} | ||||
| 			mu.Unlock() | ||||
|  | ||||
| 			k.mu.Lock() | ||||
| 			groups := make([]string, 0, len(k.subs)) | ||||
| 			for _, g := range k.subs { | ||||
| 				groups = append(groups, g.opts.Group) | ||||
| 			} | ||||
| 			k.mu.Unlock() | ||||
|  | ||||
| 			dgls, err := ac.Lag(ctx, groups...) | ||||
| 			if err != nil || !dgls.Ok() { | ||||
| 				k.opts.Logger.Error(k.opts.Context, "kgo describe group lag error", err) | ||||
| 				return | ||||
| 			} | ||||
|  | ||||
| 			for gn, dgl := range dgls { | ||||
| 				for tn, lmap := range dgl.Lag { | ||||
| 					if _, ok := lag[tn]; !ok { | ||||
| 						lag[tn] = make(map[string]pl) | ||||
| 					} | ||||
| 					for p, l := range lmap { | ||||
| 						lag[tn][gn] = pl{p: strconv.Itoa(int(p)), l: float64(l.Lag)} | ||||
| 					} | ||||
| 				} | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		for tn, dg := range lag { | ||||
| 			for gn, gl := range dg { | ||||
| 				k.opts.Meter.Gauge(semconv.BrokerGroupLag, | ||||
| 					func() float64 { updateStats(); return gl.l }, | ||||
| 					"topic", tn, | ||||
| 					"group", gn, | ||||
| 					"partition", gl.p) | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 	} | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @@ -344,40 +410,44 @@ func (b *Broker) fnPublish(ctx context.Context, topic string, messages ...broker | ||||
| } | ||||
|  | ||||
| func (b *Broker) publish(ctx context.Context, topic string, messages ...broker.Message) error { | ||||
| 	records := make([]*kgo.Record, 0, len(messages)) | ||||
| 	var errs []string | ||||
| 	var key []byte | ||||
| 	var promise func(*kgo.Record, error) | ||||
| 	var records []*kgo.Record | ||||
|  | ||||
| 	for _, msg := range messages { | ||||
| 		if mctx := msg.Context(); mctx != nil { | ||||
| 			if k, ok := mctx.Value(messageKey{}).([]byte); ok && k != nil { | ||||
| 				key = k | ||||
| 			} | ||||
| 			if p, ok := mctx.Value(messagePromiseKey{}).(func(*kgo.Record, error)); ok && p != nil { | ||||
| 				promise = p | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		rec := &kgo.Record{ | ||||
| 			Context: ctx, | ||||
| 			Key:     key, | ||||
| 			Context: msg.Context(), | ||||
| 			Topic:   topic, | ||||
| 			Value:   msg.Body(), | ||||
| 		} | ||||
|  | ||||
| 		b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc() | ||||
| 		var promise func(*kgo.Record, error) | ||||
| 		if rec.Context != nil { | ||||
| 			if k, ok := rec.Context.Value(messageKey{}).([]byte); ok && k != nil { | ||||
| 				rec.Key = k | ||||
| 			} | ||||
| 			if p, ok := rec.Context.Value(messagePromiseKey{}).(func(*kgo.Record, error)); ok && p != nil { | ||||
| 				promise = p | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		kmsg, ok := msg.(*kgoMessage) | ||||
| 		if !ok { | ||||
| 			continue | ||||
| 		} | ||||
| 		if kmsg.opts.Context != nil { | ||||
| 			if k, ok := kmsg.opts.Context.Value(messageKey{}).([]byte); ok && k != nil { | ||||
| 				rec.Key = k | ||||
| 			} | ||||
| 			if p, ok := kmsg.opts.Context.Value(messagePromiseKey{}).(func(*kgo.Record, error)); ok && p != nil { | ||||
| 				promise = p | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		setHeaders(rec, msg.Header()) | ||||
|  | ||||
| 		records = append(records, rec) | ||||
| 	} | ||||
|  | ||||
| 	ts := time.Now() | ||||
|  | ||||
| 	if promise != nil { | ||||
|  | ||||
| 		for _, rec := range records { | ||||
| 		if promise != nil { | ||||
| 			ts := time.Now() | ||||
| 			b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc() | ||||
| 			b.c.Produce(ctx, rec, func(r *kgo.Record, err error) { | ||||
| 				te := time.Since(ts) | ||||
| 				b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Dec() | ||||
| @@ -390,27 +460,33 @@ func (b *Broker) publish(ctx context.Context, topic string, messages ...broker.M | ||||
| 				} | ||||
| 				promise(r, err) | ||||
| 			}) | ||||
| 		} | ||||
| 		return nil | ||||
| 	} | ||||
|  | ||||
| 	results := b.c.ProduceSync(ctx, records...) | ||||
|  | ||||
| 	te := time.Since(ts) | ||||
| 	for _, result := range results { | ||||
| 		b.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "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()) | ||||
| 		b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Dec() | ||||
| 		if result.Err != nil { | ||||
| 			b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "failure").Inc() | ||||
| 			errs = append(errs, result.Err.Error()) | ||||
| 			continue | ||||
| 		} else { | ||||
| 			b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc() | ||||
| 			records = append(records, rec) | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	if len(errs) > 0 { | ||||
| 		return fmt.Errorf("publish error: %s", strings.Join(errs, "\n")) | ||||
| 	if len(records) > 0 { | ||||
| 		var errs []string | ||||
| 		ts := time.Now() | ||||
| 		b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", topic, "topic", topic).Set(uint64(len(records))) | ||||
| 		results := b.c.ProduceSync(ctx, records...) | ||||
| 		te := time.Since(ts) | ||||
| 		for _, result := range results { | ||||
| 			b.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "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()) | ||||
| 			b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Dec() | ||||
| 			if result.Err != nil { | ||||
| 				b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "failure").Inc() | ||||
| 				errs = append(errs, result.Err.Error()) | ||||
| 			} else { | ||||
| 				b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc() | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if len(errs) > 0 { | ||||
| 			return fmt.Errorf("publish error: %s", strings.Join(errs, "\n")) | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	return nil | ||||
|   | ||||
| @@ -81,7 +81,7 @@ func TestFail(t *testing.T) { | ||||
| 	go func() { | ||||
| 		for _, msg := range msgs { | ||||
| 			//		t.Logf("broker publish") | ||||
| 			if err := b.Publish(ctx, "test", msg); err != nil { | ||||
| 			if err := b.Publish(ctx, "test.fail", msg); err != nil { | ||||
| 				t.Fatal(err) | ||||
| 			} | ||||
| 		} | ||||
| @@ -96,7 +96,7 @@ func TestFail(t *testing.T) { | ||||
| 		return msg.Ack() | ||||
| 	} | ||||
|  | ||||
| 	sub, err := b.Subscribe(ctx, "test", fn, | ||||
| 	sub, err := b.Subscribe(ctx, "test.fail", fn, | ||||
| 		broker.SubscribeAutoAck(true), | ||||
| 		broker.SubscribeGroup(group), | ||||
| 		broker.SubscribeBodyOnly(true)) | ||||
| @@ -184,7 +184,7 @@ func TestPubSub(t *testing.T) { | ||||
| 			msgs = append(msgs, m) | ||||
| 		} | ||||
|  | ||||
| 		if err := b.Publish(ctx, "test", msgs...); err != nil { | ||||
| 		if err := b.Publish(ctx, "test.pubsub", msgs...); err != nil { | ||||
| 			t.Fatal(err) | ||||
| 		} | ||||
| 		//	t.Skip() | ||||
| @@ -197,7 +197,7 @@ func TestPubSub(t *testing.T) { | ||||
| 		return msg.Ack() | ||||
| 	} | ||||
|  | ||||
| 	sub, err := b.Subscribe(ctx, "test", fn, | ||||
| 	sub, err := b.Subscribe(ctx, "test.pubsub", fn, | ||||
| 		broker.SubscribeAutoAck(true), | ||||
| 		broker.SubscribeGroup(group), | ||||
| 		broker.SubscribeBodyOnly(true)) | ||||
|   | ||||
| @@ -14,7 +14,7 @@ var ( | ||||
| 	DefaultCommitInterval = 5 * time.Second | ||||
|  | ||||
| 	// DefaultStatsInterval specifies how fast check consumer lag | ||||
| 	DefaultStatsInterval = 5 * time.Second | ||||
| 	DefaultStatsInterval = 30 * time.Second | ||||
|  | ||||
| 	// DefaultSubscribeMaxInflight specifies how much messages keep inflight | ||||
| 	DefaultSubscribeMaxInflight = 100 | ||||
| @@ -116,3 +116,10 @@ type subscribeMessagePoolKey struct{} | ||||
| func SubscribeMessagePool(b bool) broker.SubscribeOption { | ||||
| 	return broker.SetSubscribeOption(subscribeMessagePoolKey{}, b) | ||||
| } | ||||
|  | ||||
| type exposeLagKey struct{} | ||||
|  | ||||
| // ExposeLag enabled subscriber lag via [meter.Meter] | ||||
| func ExposeLag(b bool) broker.Option { | ||||
| 	return broker.SetOption(exposeLagKey{}, b) | ||||
| } | ||||
|   | ||||
| @@ -8,7 +8,6 @@ import ( | ||||
| 	"sync/atomic" | ||||
| 	"time" | ||||
|  | ||||
| 	"github.com/twmb/franz-go/pkg/kadm" | ||||
| 	"github.com/twmb/franz-go/pkg/kgo" | ||||
| 	"github.com/twmb/franz-go/pkg/kmsg" | ||||
| 	"go.unistack.org/micro/v4/broker" | ||||
| @@ -39,16 +38,15 @@ type consumer struct { | ||||
| } | ||||
|  | ||||
| type Subscriber struct { | ||||
| 	consumers   map[tp]*consumer | ||||
| 	c           *kgo.Client | ||||
| 	htracer     *hookTracer | ||||
| 	topic       string | ||||
| 	messagePool bool | ||||
| 	handler     interface{} | ||||
| 	done        chan struct{} | ||||
| 	kopts       broker.Options | ||||
| 	opts        broker.SubscribeOptions | ||||
|  | ||||
| 	consumers    map[tp]*consumer | ||||
| 	c            *kgo.Client | ||||
| 	htracer      *hookTracer | ||||
| 	topic        string | ||||
| 	messagePool  bool | ||||
| 	handler      interface{} | ||||
| 	done         chan struct{} | ||||
| 	kopts        broker.Options | ||||
| 	opts         broker.SubscribeOptions | ||||
| 	connected    *atomic.Uint32 | ||||
| 	mu           sync.RWMutex | ||||
| 	closed       bool | ||||
| @@ -88,46 +86,13 @@ func (s *Subscriber) Unsubscribe(ctx context.Context) error { | ||||
|  | ||||
| func (s *Subscriber) poll(ctx context.Context) { | ||||
| 	maxInflight := DefaultSubscribeMaxInflight | ||||
|  | ||||
| 	if s.opts.Context != nil { | ||||
| 		if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok { | ||||
| 			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.mu.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.mu.Unlock() | ||||
|  | ||||
| 			} | ||||
| 		} | ||||
| 	}() | ||||
|  | ||||
| 	for { | ||||
| 		select { | ||||
| 		case <-ctx.Done(): | ||||
| @@ -142,7 +107,11 @@ func (s *Subscriber) poll(ctx context.Context) { | ||||
| 				return | ||||
| 			} | ||||
| 			fetches.EachError(func(t string, p int32, err error) { | ||||
| 				s.kopts.Logger.Fatal(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err) | ||||
| 				if kgo.IsRetryableBrokerErr(err) { | ||||
| 					s.kopts.Logger.Error(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err) | ||||
| 				} else { | ||||
| 					s.kopts.Logger.Fatal(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err) | ||||
| 				} | ||||
| 			}) | ||||
|  | ||||
| 			fetches.EachPartition(func(p kgo.FetchTopicPartition) { | ||||
| @@ -272,7 +241,11 @@ func (pc *consumer) consume() { | ||||
| 				for _, hdr := range record.Headers { | ||||
| 					pm.hdr.Set(hdr.Key, string(hdr.Value)) | ||||
| 				} | ||||
|  | ||||
| 				pm.hdr.Set("Micro-Offset", strconv.FormatInt(record.Offset, 10)) | ||||
| 				pm.hdr.Set("Micro-Partition", strconv.FormatInt(int64(record.Partition), 10)) | ||||
| 				pm.hdr.Set("Micro-Topic", record.Topic) | ||||
| 				pm.hdr.Set("Micro-Key", string(record.Key)) | ||||
| 				pm.hdr.Set("Micro-Timestamp", strconv.FormatInt(record.Timestamp.Unix(), 10)) | ||||
| 				switch h := pc.handler.(type) { | ||||
| 				case func(broker.Message) error: | ||||
| 					err = h(pm) | ||||
|   | ||||
		Reference in New Issue
	
	Block a user