Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DNM] use semaphore to control the call to async produce #3024

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion async_producer.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package sarama

import (
"context"
"encoding/binary"
"errors"
"fmt"
Expand All @@ -11,6 +12,7 @@ import (
"github.com/eapache/go-resiliency/breaker"
"github.com/eapache/queue"
"github.com/rcrowley/go-metrics"
"golang.org/x/sync/semaphore"
)

// AsyncProducer publishes Kafka messages using a non-blocking API. It routes messages
Expand Down Expand Up @@ -777,6 +779,7 @@ func (p *asyncProducer) newBrokerProducer(broker *Broker) *brokerProducer {
bridge = make(chan *produceSet)
pending = make(chan *brokerProducerResponse)
responses = make(chan *brokerProducerResponse)
weighted = semaphore.NewWeighted(int64(p.conf.Net.MaxOpenRequests))
)

bp := &brokerProducer{
Expand All @@ -790,13 +793,14 @@ func (p *asyncProducer) newBrokerProducer(broker *Broker) *brokerProducer {
}
go withRecover(bp.run)

ctx := context.Background()
// minimal bridge to make the network response `select`able
go withRecover(func() {
// Use a wait group to know if we still have in flight requests
var wg sync.WaitGroup

for set := range bridge {
request := set.buildRequest()
_ = weighted.Acquire(ctx, 1)

// Count the in flight requests to know when we can close the pending channel safely
wg.Add(1)
Expand All @@ -810,6 +814,7 @@ func (p *asyncProducer) newBrokerProducer(broker *Broker) *brokerProducer {
res: response,
}
wg.Done()
weighted.Release(1)
}
}(set)

Expand Down