From 54061b88c70d29a2db01b1d8c3fdc16989cfe0a0 Mon Sep 17 00:00:00 2001 From: Vivcharyk Myroslav Date: Fri, 3 May 2024 16:07:43 +0200 Subject: [PATCH] Added basic structure. --- check.go | 123 +++++++++++++++++++++++++++ config.go | 9 ++ examples/simple/Dockerfile | 26 ++++++ examples/simple/docker-compose.yml | 29 +++++++ examples/simple/main.go | 128 +++++++++++++++++++++++++++++ go.mod | 28 ++++++- go.sum | 100 +++++++++++++++++++++- main.go | 7 -- state.go | 1 + tracker.go | 46 +++++++++++ 10 files changed, 484 insertions(+), 13 deletions(-) create mode 100644 check.go create mode 100644 config.go create mode 100644 examples/simple/Dockerfile create mode 100644 examples/simple/docker-compose.yml create mode 100644 examples/simple/main.go delete mode 100644 main.go create mode 100644 state.go create mode 100644 tracker.go diff --git a/check.go b/check.go new file mode 100644 index 0000000..abc6656 --- /dev/null +++ b/check.go @@ -0,0 +1,123 @@ +package saramahealth + +import ( + "context" + "github.com/IBM/sarama" + "github.com/pkg/errors" + "log/slog" +) + +type HealthMonitor interface { + Track(ctx context.Context, msg *sarama.ConsumerMessage) error + Release(ctx context.Context, topic string, partition int32) error + Healthy(ctx context.Context) (bool, error) +} + +type State struct { + stateMap map[string]map[int32]int64 +} + +type HealthCheckerImpl struct { + topics []string + client sarama.Client + tracker *Tracker + latestState *State + prevState *State + logger *slog.Logger +} + +func NewHealthChecker(cfg Config) (*HealthCheckerImpl, error) { + client, err := sarama.NewClient(cfg.Brokers, cfg.SaramaConfig) + if err != nil { + return nil, errors.Wrap(err, "failed to create sarama client") + } + + return &HealthCheckerImpl{ + client: client, + tracker: NewTracker(), + topics: cfg.Topics, + prevState: nil, + }, nil +} + +func (h *HealthCheckerImpl) Healthy(ctx context.Context) (bool, error) { + latestState := &State{stateMap: make(map[string]map[int32]int64)} + + for _, topic := range h.topics { + latestOffset, err := h.getLatestOffset(topic) + if err != nil { + return false, err + } + + latestState.stateMap[topic] = latestOffset + } + + currentState := h.tracker.CurrentOffsets() + if h.prevState == nil { + h.prevState = &State{stateMap: currentState} + + return true, nil + } + + // check if the current state equals to the latest state + // return true only if the current state equals to the latest state + // otherwise go to the next check + + var topicRes bool + for topic := range currentState { + for partition := range currentState[topic] { + if currentState[topic][partition] == latestState.stateMap[topic][partition] { + topicRes = true + } + } + } + + if topicRes { + return true, nil + } + + // check if the current state is greater than the previous state + // return true only if the current state is greater than the previous state for all topics and partitions + // otherwise return false + + for topic := range currentState { + for partition := range currentState[topic] { + if currentState[topic][partition] <= h.prevState.stateMap[topic][partition] { + return false, nil + } + } + } + + return true, nil +} + +func (h *HealthCheckerImpl) Track(ctx context.Context, msg *sarama.ConsumerMessage) error { + h.tracker.Track(msg) + + return nil +} + +func (h *HealthCheckerImpl) Release(ctx context.Context, topic string, partition int32) error { + h.tracker.Reset(topic, partition) + + return nil +} + +func (h *HealthCheckerImpl) getLatestOffset(topic string) (map[int32]int64, error) { + var offsets = make(map[int32]int64) + + partitions, err := h.client.Partitions(topic) + if err != nil { + return offsets, err + } + + for _, partition := range partitions { + offset, err := h.client.GetOffset(topic, partition, sarama.OffsetNewest) + if err != nil { + return offsets, err + } + offsets[partition] = offset - 1 // subtract 1 to get the latest offset, not the next offset + } + + return offsets, nil +} diff --git a/config.go b/config.go new file mode 100644 index 0000000..dbd3c0c --- /dev/null +++ b/config.go @@ -0,0 +1,9 @@ +package saramahealth + +import "github.com/IBM/sarama" + +type Config struct { + Brokers []string + Topics []string + SaramaConfig *sarama.Config +} diff --git a/examples/simple/Dockerfile b/examples/simple/Dockerfile new file mode 100644 index 0000000..aa35286 --- /dev/null +++ b/examples/simple/Dockerfile @@ -0,0 +1,26 @@ +# Start from the latest golang base image +FROM golang:1.22 + +# Add Maintainer Info +LABEL maintainer="myroslavvivcharyk" + +# Set the Current Working Directory inside the container +WORKDIR /app + +# Copy go mod and sum files +COPY go.mod go.sum ./ + +# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed +RUN go mod download + +# Copy the source from the current directory to the Working Directory inside the container +COPY . . + +# Build the Go app +RUN go build -o main . + +# Expose port 8080 to the outside world +EXPOSE 8080 + +# Command to run the executable +CMD ["./main"] \ No newline at end of file diff --git a/examples/simple/docker-compose.yml b/examples/simple/docker-compose.yml new file mode 100644 index 0000000..8446d52 --- /dev/null +++ b/examples/simple/docker-compose.yml @@ -0,0 +1,29 @@ +version: '3.8' + +name: sarama-health-simple + +services: + kafka: + image: confluentinc/confluent-local:7.6.0 + hostname: broker + container_name: broker + ports: + - "8082:8082" + - "9092:9092" + - "9101:9101" + environment: + KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092' + KAFKA_CONTROLLER_QUORUM_VOTERS: '1@broker:29093' + KAFKA_LISTENERS: 'PLAINTEXT://broker:29092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:9092' + KAFKA_NUM_PARTITIONS: '${KAFKA_NUM_PARTITIONS:-3}' + healthcheck: + test: [ "CMD", "nc", "-vz", "broker", "29092" ] + interval: 3s + timeout: 5s + retries: 3 + networks: + - sarame-health-simple-network + +networks: + sarame-health-simple-network: + driver: bridge \ No newline at end of file diff --git a/examples/simple/main.go b/examples/simple/main.go new file mode 100644 index 0000000..5553295 --- /dev/null +++ b/examples/simple/main.go @@ -0,0 +1,128 @@ +package main + +import ( + "context" + "fmt" + "github.com/IBM/sarama" + saramahealth "github.com/vmyroslav/sarama-health" + "log" + "net/http" +) + +func main() { + config := sarama.NewConfig() + config.Version = sarama.V3_0_1_0 + config.Consumer.Return.Errors = true + config.Consumer.Group.Rebalance.Strategy = sarama.BalanceStrategyRoundRobin + + // Create a new consumer group + group, err := sarama.NewConsumerGroup([]string{"localhost:9092"}, "my-consumer-group", config) + if err != nil { + log.Panicf("Error creating consumer group: %v", err) + } + defer func() { + if err := group.Close(); err != nil { + log.Panicf("Error closing consumer group: %v", err) + } + }() + + healhMonitor, err := saramahealth.NewHealthChecker(saramahealth.Config{ + Brokers: []string{"localhost:9092"}, + Topics: []string{"my-topic"}, + SaramaConfig: config, + }) + + if err != nil { + log.Panicf("Error creating health monitor: %v", err) + } + + // Consumer group handler + ctx := context.Background() + consumer := Consumer{ + healthMonitor: healhMonitor, + } + + // Consume messages + go func() { + for { + err := group.Consume(ctx, []string{"my-topic"}, &consumer) + if err != nil { + log.Printf("Error from consumer: %v", err) + } + if ctx.Err() != nil { + return + } + consumer.ready = make(chan bool) + } + }() + + // Start HTTP server + http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { + isOk, err := healhMonitor.Healthy(context.Background()) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if !isOk { + http.Error(w, "Not OK", http.StatusServiceUnavailable) + return + } + + fmt.Fprintln(w, "OK") + }) + + go func() { + if err := http.ListenAndServe(":8083", nil); err != nil { + log.Fatalf("Failed to start HTTP server: %v", err) + } + }() + + <-consumer.ready // Await till the consumer has been set up + log.Println("Sarama consumer up and running!...") +} + +// Consumer represents a Sarama consumer group consumer +type Consumer struct { + ready chan bool + healthMonitor *saramahealth.HealthCheckerImpl +} + +// Setup is run at the beginning of a new session, before ConsumeClaim +func (consumer *Consumer) Setup(sarama.ConsumerGroupSession) error { + return nil +} + +// Cleanup is run at the end of a session, once all ConsumeClaim goroutines have exited +func (consumer *Consumer) Cleanup(sarama.ConsumerGroupSession) error { + return nil +} + +// ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages(). +func (consumer *Consumer) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { + ctx := session.Context() + + for { + select { + case <-ctx.Done(): + println("done") + + consumer.healthMonitor.Release(ctx, claim.Topic(), claim.Partition()) + return nil + case message, ok := <-claim.Messages(): + if !ok { + return nil + } + + err := consumer.healthMonitor.Track(ctx, message) + if err != nil { + println(err.Error()) + } + + if string(message.Value) == "fail" { + return fmt.Errorf("error") + } + + session.MarkMessage(message, "") + } + } +} diff --git a/go.mod b/go.mod index 34381d1..7390afa 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,29 @@ -module home-bartender-back +module github.com/vmyroslav/sarama-health go 1.22 -require github.com/vmyroslav/home-lib v0.1.0 // indirect +require ( + github.com/IBM/sarama v1.43.2 + github.com/pkg/errors v0.9.1 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/eapache/go-resiliency v1.6.0 // indirect + github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect + github.com/eapache/queue v1.1.0 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/hashicorp/errwrap v1.0.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/go-uuid v1.0.3 // indirect + github.com/jcmturner/aescts/v2 v2.0.0 // indirect + github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect + github.com/jcmturner/gofork v1.7.6 // indirect + github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect + github.com/jcmturner/rpc/v2 v2.0.3 // indirect + github.com/klauspost/compress v1.17.8 // indirect + github.com/pierrec/lz4/v4 v4.1.21 // indirect + github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect + golang.org/x/crypto v0.22.0 // indirect + golang.org/x/net v0.24.0 // indirect +) diff --git a/go.sum b/go.sum index 511de29..d69ba9d 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,96 @@ -github.com/vmyroslav/home-lib v0.0.0-20231113100224-567b61697473 h1:k26CnMh1z7duzbKO8Pvw/jXHmJ2+R5w4G5kmRfXC86c= -github.com/vmyroslav/home-lib v0.0.0-20231113100224-567b61697473/go.mod h1:+8aMxDeF9QZCA+r3lCnAd0o3V3oq7b5rTs5WhzNGTjE= -github.com/vmyroslav/home-lib v0.1.0 h1:rd7AHHcbH5eWveW3XDfLh+6gDY/604dmJl7CNGQHzgM= -github.com/vmyroslav/home-lib v0.1.0/go.mod h1:YqjLu07ymd+i53pztQXD43T8nrROg5CTe1eQyGTYbd8= +github.com/IBM/sarama v1.43.2 h1:HABeEqRUh32z8yzY2hGB/j8mHSzC/HA9zlEjqFNCzSw= +github.com/IBM/sarama v1.43.2/go.mod h1:Kyo4WkF24Z+1nz7xeVUFWIuKVV8RS3wM8mkvPKMdXFQ= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/eapache/go-resiliency v1.6.0 h1:CqGDTLtpwuWKn6Nj3uNUdflaq+/kIPsg0gfNzHton30= +github.com/eapache/go-resiliency v1.6.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= +github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4ALJ04o5Qqpdz8XLIpNA3WM/iSIXqxtqo7UGVws= +github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3/go.mod h1:YvSRo5mw33fLEx1+DlK6L2VV43tJt5Eyel9n9XBcR+0= +github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= +github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= +github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8= +github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= +github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo= +github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= +github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg= +github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= +github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o= +github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= +github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8= +github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= +github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= +github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= +github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= +github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ= +github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go deleted file mode 100644 index 9dea239..0000000 --- a/main.go +++ /dev/null @@ -1,7 +0,0 @@ -package main - -import "fmt" - -func main() { - fmt.Println("Hello, playground") -} diff --git a/state.go b/state.go new file mode 100644 index 0000000..7f5cacc --- /dev/null +++ b/state.go @@ -0,0 +1 @@ +package saramahealth diff --git a/tracker.go b/tracker.go new file mode 100644 index 0000000..c07b7fe --- /dev/null +++ b/tracker.go @@ -0,0 +1,46 @@ +package saramahealth + +import ( + "github.com/IBM/sarama" + "sync" +) + +type Tracker struct { + topicPartitionOffsets map[string]map[int32]int64 //todo: change to sync.Map + mu sync.RWMutex +} + +func NewTracker() *Tracker { + top := make(map[string]map[int32]int64) + + return &Tracker{topicPartitionOffsets: top} +} + +func (t *Tracker) Track(m *sarama.ConsumerMessage) { + t.mu.Lock() + defer t.mu.Unlock() + + if _, ok := t.topicPartitionOffsets[m.Topic]; !ok { + t.topicPartitionOffsets[m.Topic] = make(map[int32]int64) + } + + t.topicPartitionOffsets[m.Topic][m.Partition] = m.Offset +} + +func (t *Tracker) CurrentOffsets() map[string]map[int32]int64 { + t.mu.RLock() + defer t.mu.RUnlock() + + return t.topicPartitionOffsets +} + +func (t *Tracker) Reset(topic string, partition int32) { + t.mu.Lock() + defer t.mu.Unlock() + + if _, ok := t.topicPartitionOffsets[topic]; !ok { + t.topicPartitionOffsets[topic] = make(map[int32]int64) + } + + t.topicPartitionOffsets[topic][partition] = 0 +}