fix(go): protect kafka message processing during shutdown
This commit is contained in:
70
go/vehicle-gateway/cmd/stat-writer/main_test.go
Normal file
70
go/vehicle-gateway/cmd/stat-writer/main_test.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/segmentio/kafka-go"
|
||||
|
||||
"lingniu-vehicle-ingest/go/vehicle-gateway/internal/envelope"
|
||||
)
|
||||
|
||||
func TestProcessStatMessageUsesUncancelledContextForAppendAndCommit(t *testing.T) {
|
||||
parent, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
env := envelope.FrameEnvelope{
|
||||
Protocol: envelope.ProtocolJT808,
|
||||
MessageID: "0x0200",
|
||||
Phone: "13307795425",
|
||||
EventTimeMS: 1782918600000,
|
||||
ReceivedAtMS: 1782918600000,
|
||||
ParseStatus: envelope.ParseOK,
|
||||
}
|
||||
payload, err := json.Marshal(env)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
appender := &contextCheckingStatAppender{}
|
||||
committer := &contextCheckingStatCommitter{}
|
||||
|
||||
processStatMessage(parent, discardStatLogger{}, appender, committer, kafka.Message{Value: payload})
|
||||
|
||||
if appender.ctxErr != nil {
|
||||
t.Fatalf("appender saw cancelled context: %v", appender.ctxErr)
|
||||
}
|
||||
if committer.ctxErr != nil {
|
||||
t.Fatalf("committer saw cancelled context: %v", committer.ctxErr)
|
||||
}
|
||||
if appender.count != 1 || committer.count != 1 {
|
||||
t.Fatalf("appends=%d commits=%d", appender.count, committer.count)
|
||||
}
|
||||
}
|
||||
|
||||
type contextCheckingStatAppender struct {
|
||||
ctxErr error
|
||||
count int
|
||||
}
|
||||
|
||||
func (a *contextCheckingStatAppender) Append(ctx context.Context, _ envelope.FrameEnvelope) error {
|
||||
a.ctxErr = ctx.Err()
|
||||
a.count++
|
||||
return a.ctxErr
|
||||
}
|
||||
|
||||
type contextCheckingStatCommitter struct {
|
||||
ctxErr error
|
||||
count int
|
||||
}
|
||||
|
||||
func (c *contextCheckingStatCommitter) CommitMessages(ctx context.Context, _ ...kafka.Message) error {
|
||||
c.ctxErr = ctx.Err()
|
||||
c.count++
|
||||
return c.ctxErr
|
||||
}
|
||||
|
||||
type discardStatLogger struct{}
|
||||
|
||||
func (discardStatLogger) Error(string, ...any) {}
|
||||
func (discardStatLogger) Warn(string, ...any) {}
|
||||
Reference in New Issue
Block a user