| 1 |
// Copyright 2019 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package kafkapubsub provides an implementation of pubsub for Kafka. |
| 16 |
// It requires a minimum Kafka version of 0.11.x for Header support. |
| 17 |
// Some functionality may work with earlier versions of Kafka. |
| 18 |
// |
| 19 |
// See https://kafka.apache.org/documentation.html#semantics for a discussion |
| 20 |
// of message semantics in Kafka. sarama.Config exposes many knobs that |
| 21 |
// can affect performance and semantics, so review and set them carefully. |
| 22 |
// |
| 23 |
// kafkapubsub does not support Message.Nack; Message.Nackable will return |
| 24 |
// false, and Message.Nack will panic if called. |
| 25 |
// |
| 26 |
// # URLs |
| 27 |
// |
| 28 |
// For pubsub.OpenTopic and pubsub.OpenSubscription, kafkapubsub registers |
| 29 |
// for the scheme "kafka". |
| 30 |
// The default URL opener will connect to a default set of Kafka brokers based |
| 31 |
// on the environment variable "KAFKA_BROKERS", expected to be a comma-delimited |
| 32 |
// set of server addresses. |
| 33 |
// To customize the URL opener, or for more details on the URL format, |
| 34 |
// see URLOpener. |
| 35 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 36 |
// |
| 37 |
// # Escaping |
| 38 |
// |
| 39 |
// Go CDK supports all UTF-8 strings. No escaping is required for Kafka. |
| 40 |
// Message metadata is supported through Kafka Headers, which allow arbitrary |
| 41 |
// []byte for both key and value. These are converted to string for use in |
| 42 |
// Message.Metadata. |
| 43 |
// |
| 44 |
// # As |
| 45 |
// |
| 46 |
// kafkapubsub exposes the following types for As: |
| 47 |
// - Topic: sarama.SyncProducer |
| 48 |
// - Subscription: sarama.ConsumerGroup, sarama.ConsumerGroupSession (may be nil during session renegotiation, and session may go stale at any time) |
| 49 |
// - Message: *sarama.ConsumerMessage |
| 50 |
// - Message.BeforeSend: *sarama.ProducerMessage |
| 51 |
// - Message.AfterSend: None |
| 52 |
// - Error: sarama.ConsumerError, sarama.ConsumerErrors, sarama.ProducerError, sarama.ProducerErrors, sarama.ConfigurationError, sarama.PacketDecodingError, sarama.PacketEncodingError, sarama.KError |
| 53 |
package kafkapubsub // import "gocloud.dev/pubsub/kafkapubsub" |
| 54 |
|
| 55 |
import ( |
| 56 |
"context" |
| 57 |
"errors" |
| 58 |
"fmt" |
| 59 |
"net/url" |
| 60 |
"os" |
| 61 |
"path" |
| 62 |
"reflect" |
| 63 |
"strings" |
| 64 |
"sync" |
| 65 |
"time" |
| 66 |
|
| 67 |
"github.com/IBM/sarama" |
| 68 |
"gocloud.dev/gcerrors" |
| 69 |
"gocloud.dev/pubsub" |
| 70 |
"gocloud.dev/pubsub/batcher" |
| 71 |
"gocloud.dev/pubsub/driver" |
| 72 |
) |
| 73 |
|
| 74 |
var sendBatcherOpts = &batcher.Options{ |
| 75 |
MaxBatchSize: 100, |
| 76 |
MaxHandlers: 100, // max concurrency for sends |
| 77 |
} |
| 78 |
|
| 79 |
var recvBatcherOpts = &batcher.Options{ |
| 80 |
// Concurrency doesn't make sense here. |
| 81 |
MaxBatchSize: 1, |
| 82 |
MaxHandlers: 1, |
| 83 |
} |
| 84 |
|
| 85 |
func init() { |
| 86 |
opener := new(defaultOpener) |
| 87 |
pubsub.DefaultURLMux().RegisterTopic(Scheme, opener) |
| 88 |
pubsub.DefaultURLMux().RegisterSubscription(Scheme, opener) |
| 89 |
} |
| 90 |
|
| 91 |
// defaultOpener create a default opener. |
| 92 |
type defaultOpener struct { |
| 93 |
init sync.Once |
| 94 |
opener *URLOpener |
| 95 |
err error |
| 96 |
} |
| 97 |
|
| 98 |
func (o *defaultOpener) defaultOpener() (*URLOpener, error) { |
| 99 |
o.init.Do(func() { |
| 100 |
brokerList := os.Getenv("KAFKA_BROKERS") |
| 101 |
if brokerList == "" { |
| 102 |
o.err = errors.New("KAFKA_BROKERS environment variable not set") |
| 103 |
return |
| 104 |
} |
| 105 |
brokers := strings.Split(brokerList, ",") |
| 106 |
for i, b := range brokers { |
| 107 |
brokers[i] = strings.TrimSpace(b) |
| 108 |
} |
| 109 |
o.opener = &URLOpener{ |
| 110 |
Brokers: brokers, |
| 111 |
Config: MinimalConfig(), |
| 112 |
} |
| 113 |
}) |
| 114 |
return o.opener, o.err |
| 115 |
} |
| 116 |
|
| 117 |
func (o *defaultOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) { |
| 118 |
opener, err := o.defaultOpener() |
| 119 |
if err != nil { |
| 120 |
return nil, fmt.Errorf("open topic %v: %v", u, err) |
| 121 |
} |
| 122 |
return opener.OpenTopicURL(ctx, u) |
| 123 |
} |
| 124 |
|
| 125 |
func (o *defaultOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) { |
| 126 |
opener, err := o.defaultOpener() |
| 127 |
if err != nil { |
| 128 |
return nil, fmt.Errorf("open subscription %v: %v", u, err) |
| 129 |
} |
| 130 |
return opener.OpenSubscriptionURL(ctx, u) |
| 131 |
} |
| 132 |
|
| 133 |
// Scheme is the URL scheme that kafkapubsub registers its URLOpeners under on pubsub.DefaultMux. |
| 134 |
const Scheme = "kafka" |
| 135 |
|
| 136 |
// URLOpener opens Kafka URLs like "kafka://mytopic" for topics and |
| 137 |
// "kafka://group?topic=mytopic" for subscriptions. |
| 138 |
// |
| 139 |
// For topics, the URL's host+path is used as the topic name, |
| 140 |
// and the "key_name" query parameter is used to extract the routing key |
| 141 |
// from metadata. |
| 142 |
// |
| 143 |
// For subscriptions, the URL's host+path is used as the group name, |
| 144 |
// and the "topic" query parameter(s) are used as the set of topics to |
| 145 |
// subscribe to. The "offset" parameter is available to subscribers to set |
| 146 |
// the Kafka consumer's initial offset. Where "oldest" starts consuming from |
| 147 |
// the oldest offset of the consumer group and "newest" starts consuming from |
| 148 |
// the most recent offset on the topic. |
| 149 |
type URLOpener struct { |
| 150 |
// Brokers is the slice of brokers in the Kafka cluster. |
| 151 |
Brokers []string |
| 152 |
// Config is the Sarama Config. |
| 153 |
// Config.Producer.Return.Success must be set to true. |
| 154 |
Config *sarama.Config |
| 155 |
|
| 156 |
// TopicOptions specifies the options to pass to OpenTopic. |
| 157 |
TopicOptions TopicOptions |
| 158 |
// SubscriptionOptions specifies the options to pass to OpenSubscription. |
| 159 |
SubscriptionOptions SubscriptionOptions |
| 160 |
} |
| 161 |
|
| 162 |
// OpenTopicURL opens a pubsub.Topic based on u. |
| 163 |
func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) { |
| 164 |
for param, value := range u.Query() { |
| 165 |
switch param { |
| 166 |
case "key_name": |
| 167 |
if len(value) != 1 || len(value[0]) == 0 { |
| 168 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param) |
| 169 |
} |
| 170 |
|
| 171 |
o.TopicOptions.KeyName = value[0] |
| 172 |
default: |
| 173 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param) |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
topicName := path.Join(u.Host, u.Path) |
| 178 |
return OpenTopic(o.Brokers, o.Config, topicName, &o.TopicOptions) |
| 179 |
} |
| 180 |
|
| 181 |
// OpenSubscriptionURL opens a pubsub.Subscription based on u. |
| 182 |
func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) { |
| 183 |
var topics []string |
| 184 |
for param, value := range u.Query() { |
| 185 |
switch param { |
| 186 |
case "topic": |
| 187 |
topics = value |
| 188 |
case "offset": |
| 189 |
if len(value) == 0 { |
| 190 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param) |
| 191 |
} |
| 192 |
|
| 193 |
offset := value[0] |
| 194 |
switch offset { |
| 195 |
case "oldest": |
| 196 |
o.Config.Consumer.Offsets.Initial = sarama.OffsetOldest |
| 197 |
case "newest": |
| 198 |
o.Config.Consumer.Offsets.Initial = sarama.OffsetNewest |
| 199 |
default: |
| 200 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, offset) |
| 201 |
} |
| 202 |
default: |
| 203 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param) |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
group := path.Join(u.Host, u.Path) |
| 208 |
return OpenSubscription(o.Brokers, o.Config, group, topics, &o.SubscriptionOptions) |
| 209 |
} |
| 210 |
|
| 211 |
// MinimalConfig returns a minimal sarama.Config. |
| 212 |
func MinimalConfig() *sarama.Config { |
| 213 |
config := sarama.NewConfig() |
| 214 |
config.Version = sarama.V0_11_0_0 // required for Headers |
| 215 |
config.Producer.Return.Successes = true // required for SyncProducer |
| 216 |
return config |
| 217 |
} |
| 218 |
|
| 219 |
type topic struct { |
| 220 |
producer sarama.SyncProducer |
| 221 |
topicName string |
| 222 |
opts TopicOptions |
| 223 |
} |
| 224 |
|
| 225 |
// TopicOptions contains configuration options for topics. |
| 226 |
type TopicOptions struct { |
| 227 |
// KeyName optionally sets the Message.Metadata key to use as the optional |
| 228 |
// Kafka message key. If set, and if a matching Message.Metadata key is found, |
| 229 |
// the value for that key will be used as the message key when sending to |
| 230 |
// Kafka, instead of being added to the message headers. |
| 231 |
KeyName string |
| 232 |
|
| 233 |
// BatcherOptions adds constraints to the default batching done for sends. |
| 234 |
BatcherOptions batcher.Options |
| 235 |
} |
| 236 |
|
| 237 |
// OpenTopic creates a pubsub.Topic that sends to a Kafka topic. |
| 238 |
// |
| 239 |
// It uses a sarama.SyncProducer to send messages. Producer options can |
| 240 |
// be configured in the Producer section of the sarama.Config: |
| 241 |
// https://godoc.org/github.com/IBM/sarama#Config. |
| 242 |
// |
| 243 |
// Config.Producer.Return.Success must be set to true. |
| 244 |
func OpenTopic(brokers []string, config *sarama.Config, topicName string, opts *TopicOptions) (*pubsub.Topic, error) { |
| 245 |
dt, err := openTopic(brokers, config, topicName, opts) |
| 246 |
if err != nil { |
| 247 |
return nil, err |
| 248 |
} |
| 249 |
bo := sendBatcherOpts.NewMergedOptions(&dt.opts.BatcherOptions) |
| 250 |
return pubsub.NewTopic(dt, bo), nil |
| 251 |
} |
| 252 |
|
| 253 |
// openTopic returns the driver for OpenTopic. This function exists so the test |
| 254 |
// harness can get the driver interface implementation if it needs to. |
| 255 |
func openTopic(brokers []string, config *sarama.Config, topicName string, opts *TopicOptions) (*topic, error) { |
| 256 |
if opts == nil { |
| 257 |
opts = &TopicOptions{} |
| 258 |
} |
| 259 |
producer, err := sarama.NewSyncProducer(brokers, config) |
| 260 |
if err != nil { |
| 261 |
return nil, err |
| 262 |
} |
| 263 |
return &topic{producer: producer, topicName: topicName, opts: *opts}, nil |
| 264 |
} |
| 265 |
|
| 266 |
// SendBatch implements driver.Topic.SendBatch. |
| 267 |
func (t *topic) SendBatch(ctx context.Context, dms []*driver.Message) error { |
| 268 |
// Convert the messages to a slice of sarama.ProducerMessage. |
| 269 |
ms := make([]*sarama.ProducerMessage, 0, len(dms)) |
| 270 |
for _, dm := range dms { |
| 271 |
var kafkaKey sarama.Encoder |
| 272 |
var headers []sarama.RecordHeader |
| 273 |
for k, v := range dm.Metadata { |
| 274 |
if k == t.opts.KeyName { |
| 275 |
// Use this key's value as the Kafka message key instead of adding it |
| 276 |
// to the headers. |
| 277 |
kafkaKey = sarama.ByteEncoder(v) |
| 278 |
} else { |
| 279 |
headers = append(headers, sarama.RecordHeader{Key: []byte(k), Value: []byte(v)}) |
| 280 |
} |
| 281 |
} |
| 282 |
pm := &sarama.ProducerMessage{ |
| 283 |
Topic: t.topicName, |
| 284 |
Key: kafkaKey, |
| 285 |
Value: sarama.ByteEncoder(dm.Body), |
| 286 |
Headers: headers, |
| 287 |
} |
| 288 |
if dm.BeforeSend != nil { |
| 289 |
asFunc := func(i any) bool { |
| 290 |
if p, ok := i.(**sarama.ProducerMessage); ok { |
| 291 |
*p = pm |
| 292 |
return true |
| 293 |
} |
| 294 |
return false |
| 295 |
} |
| 296 |
if err := dm.BeforeSend(asFunc); err != nil { |
| 297 |
return err |
| 298 |
} |
| 299 |
} |
| 300 |
ms = append(ms, pm) |
| 301 |
|
| 302 |
} |
| 303 |
err := t.producer.SendMessages(ms) |
| 304 |
if err != nil { |
| 305 |
return err |
| 306 |
} |
| 307 |
for _, dm := range dms { |
| 308 |
if dm.AfterSend != nil { |
| 309 |
asFunc := func(i any) bool { return false } |
| 310 |
if err := dm.AfterSend(asFunc); err != nil { |
| 311 |
return err |
| 312 |
} |
| 313 |
} |
| 314 |
} |
| 315 |
return nil |
| 316 |
} |
| 317 |
|
| 318 |
// Close implements io.Closer. |
| 319 |
func (t *topic) Close() error { |
| 320 |
return t.producer.Close() |
| 321 |
} |
| 322 |
|
| 323 |
// IsRetryable implements driver.Topic.IsRetryable. |
| 324 |
func (t *topic) IsRetryable(error) bool { |
| 325 |
return false |
| 326 |
} |
| 327 |
|
| 328 |
// As implements driver.Topic.As. |
| 329 |
func (t *topic) As(i any) bool { |
| 330 |
if p, ok := i.(*sarama.SyncProducer); ok { |
| 331 |
*p = t.producer |
| 332 |
return true |
| 333 |
} |
| 334 |
return false |
| 335 |
} |
| 336 |
|
| 337 |
// ErrorAs implements driver.Topic.ErrorAs. |
| 338 |
func (t *topic) ErrorAs(err error, i any) bool { |
| 339 |
return errorAs(err, i) |
| 340 |
} |
| 341 |
|
| 342 |
// ErrorCode implements driver.Topic.ErrorCode. |
| 343 |
func (t *topic) ErrorCode(err error) gcerrors.ErrorCode { |
| 344 |
return errorCode(err) |
| 345 |
} |
| 346 |
|
| 347 |
func errorCode(err error) gcerrors.ErrorCode { |
| 348 |
if pes, ok := err.(sarama.ProducerErrors); ok && len(pes) == 1 { |
| 349 |
return errorCode(pes[0]) |
| 350 |
} |
| 351 |
if pe, ok := err.(*sarama.ProducerError); ok { |
| 352 |
return errorCode(pe.Err) |
| 353 |
} |
| 354 |
if err == sarama.ErrUnknownTopicOrPartition { |
| 355 |
return gcerrors.NotFound |
| 356 |
} |
| 357 |
return gcerrors.Unknown |
| 358 |
} |
| 359 |
|
| 360 |
type subscription struct { |
| 361 |
opts SubscriptionOptions |
| 362 |
closeCh chan struct{} // closed when we've shut down |
| 363 |
joinCh chan struct{} // closed when we join for the first time |
| 364 |
cancel func() // cancels the background consumer |
| 365 |
closeErr error // fatal error detected by the background consumer |
| 366 |
consumerGroup sarama.ConsumerGroup |
| 367 |
|
| 368 |
mu sync.Mutex |
| 369 |
unacked []*ackInfo |
| 370 |
sess sarama.ConsumerGroupSession // current session, if any, used for marking offset updates |
| 371 |
expectedClaims int // # of expected claims for the current session, they should be added via ConsumeClaim |
| 372 |
claims []sarama.ConsumerGroupClaim // claims in the current session |
| 373 |
} |
| 374 |
|
| 375 |
// ackInfo stores info about a message and whether it has been acked. |
| 376 |
// It is used as the driver.AckID. |
| 377 |
type ackInfo struct { |
| 378 |
msg *sarama.ConsumerMessage |
| 379 |
acked bool |
| 380 |
} |
| 381 |
|
| 382 |
// SubscriptionOptions contains configuration for subscriptions. |
| 383 |
type SubscriptionOptions struct { |
| 384 |
// KeyName optionally sets the Message.Metadata key in which to store the |
| 385 |
// Kafka message key. If set, and if the Kafka message key is non-empty, |
| 386 |
// the key value will be stored in Message.Metadata under KeyName. |
| 387 |
KeyName string |
| 388 |
|
| 389 |
// WaitForJoin causes OpenSubscription to wait for up to WaitForJoin |
| 390 |
// to allow the client to join the consumer group. |
| 391 |
// Messages sent to the topic before the client joins the group |
| 392 |
// may not be received by this subscription. |
| 393 |
// OpenSubscription will succeed even if WaitForJoin elapses and |
| 394 |
// the subscription still hasn't been joined successfully. |
| 395 |
WaitForJoin time.Duration |
| 396 |
} |
| 397 |
|
| 398 |
// OpenSubscription creates a pubsub.Subscription that joins group, receiving |
| 399 |
// messages from topics. |
| 400 |
// |
| 401 |
// It uses a sarama.ConsumerGroup to receive messages. Consumer options can |
| 402 |
// be configured in the Consumer section of the sarama.Config: |
| 403 |
// https://godoc.org/github.com/IBM/sarama#Config. |
| 404 |
func OpenSubscription(brokers []string, config *sarama.Config, group string, topics []string, opts *SubscriptionOptions) (*pubsub.Subscription, error) { |
| 405 |
ds, err := openSubscription(brokers, config, group, topics, opts) |
| 406 |
if err != nil { |
| 407 |
return nil, err |
| 408 |
} |
| 409 |
return pubsub.NewSubscription(ds, recvBatcherOpts, nil), nil |
| 410 |
} |
| 411 |
|
| 412 |
// openSubscription returns the driver for OpenSubscription. This function |
| 413 |
// exists so the test harness can get the driver interface implementation if it |
| 414 |
// needs to. |
| 415 |
func openSubscription(brokers []string, config *sarama.Config, group string, topics []string, opts *SubscriptionOptions) (driver.Subscription, error) { |
| 416 |
if opts == nil { |
| 417 |
opts = &SubscriptionOptions{} |
| 418 |
} |
| 419 |
consumerGroup, err := sarama.NewConsumerGroup(brokers, group, config) |
| 420 |
if err != nil { |
| 421 |
return nil, err |
| 422 |
} |
| 423 |
// Create a cancelable context for the background goroutine that |
| 424 |
// consumes messages. |
| 425 |
ctx, cancel := context.WithCancel(context.Background()) |
| 426 |
joinCh := make(chan struct{}) |
| 427 |
ds := &subscription{ |
| 428 |
opts: *opts, |
| 429 |
consumerGroup: consumerGroup, |
| 430 |
closeCh: make(chan struct{}), |
| 431 |
joinCh: joinCh, |
| 432 |
cancel: cancel, |
| 433 |
} |
| 434 |
// Start a background consumer. It should run until ctx is cancelled |
| 435 |
// by Close, or until there's a fatal error (e.g., topic doesn't exist). |
| 436 |
// We're registering ds as our ConsumerGroupHandler, so sarama will |
| 437 |
// call [Setup, ConsumeClaim (possibly more than once), Cleanup] |
| 438 |
// repeatedly as the consumer group is rebalanced. |
| 439 |
// See https://godoc.org/github.com/IBM/sarama#ConsumerGroup. |
| 440 |
go func() { |
| 441 |
for { |
| 442 |
ds.closeErr = consumerGroup.Consume(ctx, topics, ds) |
| 443 |
if ds.closeErr != nil || ctx.Err() != nil { |
| 444 |
consumerGroup.Close() |
| 445 |
close(ds.closeCh) |
| 446 |
break |
| 447 |
} |
| 448 |
} |
| 449 |
}() |
| 450 |
if opts.WaitForJoin > 0 { |
| 451 |
// Best effort wait for first consumer group session. |
| 452 |
select { |
| 453 |
case <-joinCh: |
| 454 |
case <-ds.closeCh: |
| 455 |
case <-time.After(opts.WaitForJoin): |
| 456 |
} |
| 457 |
} |
| 458 |
return ds, nil |
| 459 |
} |
| 460 |
|
| 461 |
// Setup implements sarama.ConsumerGroupHandler.Setup. It is called whenever |
| 462 |
// a new session with the broker is starting. |
| 463 |
func (s *subscription) Setup(sess sarama.ConsumerGroupSession) error { |
| 464 |
// Record the current session. |
| 465 |
s.mu.Lock() |
| 466 |
defer s.mu.Unlock() |
| 467 |
s.sess = sess |
| 468 |
s.expectedClaims = 0 |
| 469 |
for _, claims := range sess.Claims() { |
| 470 |
s.expectedClaims += len(claims) |
| 471 |
} |
| 472 |
return nil |
| 473 |
} |
| 474 |
|
| 475 |
// Cleanup implements sarama.ConsumerGroupHandler.Cleanup. |
| 476 |
func (s *subscription) Cleanup(sarama.ConsumerGroupSession) error { |
| 477 |
// Clear the current session. |
| 478 |
s.mu.Lock() |
| 479 |
defer s.mu.Unlock() |
| 480 |
s.sess = nil |
| 481 |
s.expectedClaims = 0 |
| 482 |
s.claims = nil |
| 483 |
return nil |
| 484 |
} |
| 485 |
|
| 486 |
// ConsumeClaim implements sarama.ConsumerGroupHandler.ConsumeClaim. |
| 487 |
// This is where messages are actually delivered, via a channel. |
| 488 |
func (s *subscription) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { |
| 489 |
s.mu.Lock() |
| 490 |
s.claims = append(s.claims, claim) |
| 491 |
// Once all of the expected claims have registered, close joinCh to (possibly) wake up OpenSubscription. |
| 492 |
if s.joinCh != nil && len(s.claims) == s.expectedClaims { |
| 493 |
close(s.joinCh) |
| 494 |
s.joinCh = nil |
| 495 |
} |
| 496 |
s.mu.Unlock() |
| 497 |
<-sess.Context().Done() |
| 498 |
return nil |
| 499 |
} |
| 500 |
|
| 501 |
// ReceiveBatch implements driver.Subscription.ReceiveBatch. |
| 502 |
func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) { |
| 503 |
// Try to read maxMessages for up to 100ms before giving up. |
| 504 |
maxWaitCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) |
| 505 |
defer cancel() |
| 506 |
|
| 507 |
for { |
| 508 |
// We'll give up after maxWaitCtx is Done, or if s.closeCh is closed. |
| 509 |
// Otherwise, we want to pull a message from one of the channels in the |
| 510 |
// claim(s) we've been given. |
| 511 |
// |
| 512 |
// Note: we could multiplex this by ranging over each claim.Messages(), |
| 513 |
// writing the messages to a single ch, and then reading from that ch |
| 514 |
// here. However, this results in us reading messages from Kafka and |
| 515 |
// essentially queueing them here; when the session is closed for whatever |
| 516 |
// reason, those messages are lost, which may or may not be an issue |
| 517 |
// depending on the Kafka configuration being used. |
| 518 |
// |
| 519 |
// It seems safer to use reflect.Select to explicitly only get a single |
| 520 |
// message at a time, and hand it directly to the user. |
| 521 |
// |
| 522 |
// reflect.Select is essentially a "select" statement, but allows us to |
| 523 |
// build the cases dynamically. We need that because we need a case for |
| 524 |
// each of the claims in s.claims. |
| 525 |
s.mu.Lock() |
| 526 |
cases := make([]reflect.SelectCase, 0, len(s.claims)+2) |
| 527 |
// Add a case for s.closeCh being closed, at index = 0. |
| 528 |
cases = append(cases, reflect.SelectCase{ |
| 529 |
Dir: reflect.SelectRecv, |
| 530 |
Chan: reflect.ValueOf(s.closeCh), |
| 531 |
}) |
| 532 |
// Add a case for maxWaitCtx being Done, at index = 1. |
| 533 |
cases = append(cases, reflect.SelectCase{ |
| 534 |
Dir: reflect.SelectRecv, |
| 535 |
Chan: reflect.ValueOf(maxWaitCtx.Done()), |
| 536 |
}) |
| 537 |
// Add a case per claim, reading from the claim's Messages channel. |
| 538 |
for _, claim := range s.claims { |
| 539 |
cases = append(cases, reflect.SelectCase{ |
| 540 |
Dir: reflect.SelectRecv, |
| 541 |
Chan: reflect.ValueOf(claim.Messages()), |
| 542 |
}) |
| 543 |
} |
| 544 |
s.mu.Unlock() |
| 545 |
i, v, ok := reflect.Select(cases) |
| 546 |
if !ok { |
| 547 |
// The i'th channel was closed. |
| 548 |
switch i { |
| 549 |
case 0: // s.closeCh |
| 550 |
return nil, s.closeErr |
| 551 |
case 1: // maxWaitCtx |
| 552 |
// We've tried for a while to get a message, but didn't get any. |
| 553 |
// Return an empty slice; the portable type will call us back. |
| 554 |
return nil, ctx.Err() |
| 555 |
} |
| 556 |
// Otherwise, if one of the claim channels closed, we're probably ending |
| 557 |
// a session. Just keep trying. |
| 558 |
continue |
| 559 |
} |
| 560 |
msg := v.Interface().(*sarama.ConsumerMessage) |
| 561 |
|
| 562 |
// We've got a message! It should not be nil. |
| 563 |
// Read the metadata from msg.Headers. |
| 564 |
md := map[string]string{} |
| 565 |
for _, h := range msg.Headers { |
| 566 |
md[string(h.Key)] = string(h.Value) |
| 567 |
} |
| 568 |
// Add a metadata entry for the message key if appropriate. |
| 569 |
if len(msg.Key) > 0 && s.opts.KeyName != "" { |
| 570 |
md[s.opts.KeyName] = string(msg.Key) |
| 571 |
} |
| 572 |
ack := &ackInfo{msg: msg} |
| 573 |
var loggableID string |
| 574 |
if len(msg.Key) == 0 { |
| 575 |
loggableID = fmt.Sprintf("partition %d offset %d", msg.Partition, msg.Offset) |
| 576 |
} else { |
| 577 |
loggableID = string(msg.Key) |
| 578 |
} |
| 579 |
dm := &driver.Message{ |
| 580 |
LoggableID: loggableID, |
| 581 |
Body: msg.Value, |
| 582 |
Metadata: md, |
| 583 |
AckID: ack, |
| 584 |
AsFunc: func(i any) bool { |
| 585 |
if p, ok := i.(**sarama.ConsumerMessage); ok { |
| 586 |
*p = msg |
| 587 |
return true |
| 588 |
} |
| 589 |
return false |
| 590 |
}, |
| 591 |
} |
| 592 |
s.mu.Lock() |
| 593 |
defer s.mu.Unlock() |
| 594 |
s.unacked = append(s.unacked, ack) |
| 595 |
return []*driver.Message{dm}, nil |
| 596 |
} |
| 597 |
} |
| 598 |
|
| 599 |
// SendAcks implements driver.Subscription.SendAcks. |
| 600 |
func (s *subscription) SendAcks(ctx context.Context, ids []driver.AckID) error { |
| 601 |
s.mu.Lock() |
| 602 |
defer s.mu.Unlock() |
| 603 |
|
| 604 |
// Mark them all acked. |
| 605 |
for _, id := range ids { |
| 606 |
id.(*ackInfo).acked = true |
| 607 |
} |
| 608 |
if s.sess == nil { |
| 609 |
// We don't have a current session, so we can't send offset updates. |
| 610 |
// We'll just wait until next time and retry. |
| 611 |
return nil |
| 612 |
} |
| 613 |
// Mark all of the acked messages at the head of the slice. Since Kafka only |
| 614 |
// stores a single offset, we can't mark messages that aren't at the head; that |
| 615 |
// would move the offset past other as-yet-unacked messages. |
| 616 |
for len(s.unacked) > 0 && s.unacked[0].acked { |
| 617 |
s.sess.MarkMessage(s.unacked[0].msg, "") |
| 618 |
s.unacked = s.unacked[1:] |
| 619 |
} |
| 620 |
return nil |
| 621 |
} |
| 622 |
|
| 623 |
// CanNack implements driver.CanNack. |
| 624 |
func (s *subscription) CanNack() bool { |
| 625 |
// Nacking a single message doesn't make sense with the way Kafka maintains |
| 626 |
// offsets. |
| 627 |
return false |
| 628 |
} |
| 629 |
|
| 630 |
// SendNacks implements driver.Subscription.SendNacks. |
| 631 |
func (s *subscription) SendNacks(ctx context.Context, ids []driver.AckID) error { |
| 632 |
panic("unreachable") |
| 633 |
} |
| 634 |
|
| 635 |
// Close implements io.Closer. |
| 636 |
func (s *subscription) Close() error { |
| 637 |
// Cancel the ctx for the background goroutine and wait until it's done. |
| 638 |
s.cancel() |
| 639 |
<-s.closeCh |
| 640 |
return nil |
| 641 |
} |
| 642 |
|
| 643 |
// IsRetryable implements driver.Subscription.IsRetryable. |
| 644 |
func (*subscription) IsRetryable(error) bool { |
| 645 |
return false |
| 646 |
} |
| 647 |
|
| 648 |
// As implements driver.Subscription.As. |
| 649 |
func (s *subscription) As(i any) bool { |
| 650 |
if p, ok := i.(*sarama.ConsumerGroup); ok { |
| 651 |
*p = s.consumerGroup |
| 652 |
return true |
| 653 |
} |
| 654 |
if p, ok := i.(*sarama.ConsumerGroupSession); ok { |
| 655 |
s.mu.Lock() |
| 656 |
defer s.mu.Unlock() |
| 657 |
*p = s.sess |
| 658 |
return true |
| 659 |
} |
| 660 |
return false |
| 661 |
} |
| 662 |
|
| 663 |
// ErrorAs implements driver.Subscription.ErrorAs. |
| 664 |
func (s *subscription) ErrorAs(err error, i any) bool { |
| 665 |
return errorAs(err, i) |
| 666 |
} |
| 667 |
|
| 668 |
// ErrorCode implements driver.Subscription.ErrorCode. |
| 669 |
func (*subscription) ErrorCode(err error) gcerrors.ErrorCode { |
| 670 |
return errorCode(err) |
| 671 |
} |
| 672 |
|
| 673 |
func errorAs(err error, i any) bool { |
| 674 |
switch terr := err.(type) { |
| 675 |
case sarama.ConsumerError: |
| 676 |
if p, ok := i.(*sarama.ConsumerError); ok { |
| 677 |
*p = terr |
| 678 |
return true |
| 679 |
} |
| 680 |
case sarama.ConsumerErrors: |
| 681 |
if p, ok := i.(*sarama.ConsumerErrors); ok { |
| 682 |
*p = terr |
| 683 |
return true |
| 684 |
} |
| 685 |
case sarama.ProducerError: |
| 686 |
if p, ok := i.(*sarama.ProducerError); ok { |
| 687 |
*p = terr |
| 688 |
return true |
| 689 |
} |
| 690 |
case sarama.ProducerErrors: |
| 691 |
if p, ok := i.(*sarama.ProducerErrors); ok { |
| 692 |
*p = terr |
| 693 |
return true |
| 694 |
} |
| 695 |
case sarama.ConfigurationError: |
| 696 |
if p, ok := i.(*sarama.ConfigurationError); ok { |
| 697 |
*p = terr |
| 698 |
return true |
| 699 |
} |
| 700 |
case sarama.PacketDecodingError: |
| 701 |
if p, ok := i.(*sarama.PacketDecodingError); ok { |
| 702 |
*p = terr |
| 703 |
return true |
| 704 |
} |
| 705 |
case sarama.PacketEncodingError: |
| 706 |
if p, ok := i.(*sarama.PacketEncodingError); ok { |
| 707 |
*p = terr |
| 708 |
return true |
| 709 |
} |
| 710 |
case sarama.KError: |
| 711 |
if p, ok := i.(*sarama.KError); ok { |
| 712 |
*p = terr |
| 713 |
return true |
| 714 |
} |
| 715 |
} |
| 716 |
return false |
| 717 |
} |