feat(events): add idempotent Kafka event consumer runtime

This commit is contained in:
shira committed 2026-10-06 03:59:57 +03:00
1 parent 565ef8d4f5
commit 3adb0ef9e4
47 files changed
+5018 -105

No files matched your search

+28
View File
@@ -59,6 +59,24 @@ type Config struct {
RelayStatementTimeout time.Duration
RelayBackoffInitial time.Duration
RelayBackoffMax time.Duration
// ConsumerEnabled runs the registered event consumers next to the HTTP
// servers.
ConsumerEnabled bool
// ConsumerGroupPrefix and a consumer name form the consumer group ID.
ConsumerGroupPrefix string
ConsumerMaxAttempts int
ConsumerBackoffInitial time.Duration
ConsumerBackoffMax time.Duration
// ConsumerHandlerTimeout bounds one consumer transaction.
ConsumerHandlerTimeout time.Duration
ConsumerMaxPollRecords int
ConsumerCommitTimeout time.Duration
// ConsumerShutdownGrace bounds the record in progress after shutdown
// begins.
ConsumerShutdownGrace time.Duration
// ConsumerRebalanceTimeout is the Kafka rebalance timeout of every
// consumer group member.
ConsumerRebalanceTimeout time.Duration
// EmailProvider selects the only active mail transport. Settings of the
// other transports are not loaded.
EmailProvider EmailProvider
@@ -118,6 +136,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
if err := config.loadRelay(lookup); err != nil {
return Config{}, err
}
if err := config.loadConsumer(lookup); err != nil {
return Config{}, err
}
if err := config.loadMail(lookup); err != nil {
return Config{}, err
}
@@ -183,6 +204,11 @@ func (config Config) Validate() error {
if config.ShutdownTimeout <= 0 {
return errors.New("Config.Validate - SHUTDOWN_TIMEOUT must be positive")
}
// The consumer shutdown grace is checked against SHUTDOWN_TIMEOUT, so it
// follows that check.
if err := config.ValidateConsumer(); err != nil {
return err
}
switch config.LogLevel {
case "debug", "info", "warn", "error":
default:
@@ -207,6 +233,8 @@ func DatabaseURLFromEnv(lookup LookupEnv) string {
// boolOrDefault accepts only "true" or "false", ignoring case and surrounding
// spaces. strconv.ParseBool would also accept 1, t, and similar shorthands,
// which are easy to mistype in deployment files.
//
//nolint:unparam // Every setting names its own default; that all current defaults are true is a coincidence.
func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) {
value, ok := lookup(key)
if !ok {
+169
View File
@@ -0,0 +1,169 @@
package config
import (
"errors"
"fmt"
"strings"
"time"
)
const (
// The consumer runtime runs by default. It starts a consumer only for a
// registered handler, and none is registered yet.
defaultConsumerEnabled = true
// defaultConsumerGroupPrefix is joined with a consumer name by a dot to
// form the Kafka consumer group ID, for example "lincodex.<consumer>".
defaultConsumerGroupPrefix = "lincodex"
// maxConsumerGroupPrefixLength leaves room for the consumer name in the
// group ID, which the code limits to 64 characters.
maxConsumerGroupPrefixLength = 128
// defaultConsumerMaxAttempts bounds the handler attempts for one event
// before it is dead-lettered.
defaultConsumerMaxAttempts = 5
maxConsumerMaxAttempts = 20
// The wait after a failed attempt starts at the initial delay, doubles
// per consecutive failure, and stops growing at the maximum.
defaultConsumerBackoffInitial = 500 * time.Millisecond
defaultConsumerBackoffMax = 10 * time.Second
maxConsumerBackoff = 5 * time.Minute
// defaultConsumerHandlerTimeout bounds one transaction: the dedup marker,
// the handler, and the commit. It keeps the worst case of one record
// below the default rebalance timeout; see validateConsumerRebalance.
defaultConsumerHandlerTimeout = 5 * time.Second
minConsumerHandlerTimeout = 100 * time.Millisecond
maxConsumerHandlerTimeout = 5 * time.Minute
// defaultConsumerMaxPollRecords bounds the records of one poll, which a
// consumer processes while it holds group rebalancing.
defaultConsumerMaxPollRecords = 100
maxConsumerMaxPollRecords = 10000
// defaultConsumerCommitTimeout bounds one offset commit.
defaultConsumerCommitTimeout = 5 * time.Second
minConsumerCommitTimeout = 100 * time.Millisecond
maxConsumerCommitTimeout = time.Minute
// defaultConsumerShutdownGrace is how long the record in progress may
// continue after shutdown begins.
defaultConsumerShutdownGrace = 5 * time.Second
// defaultConsumerRebalanceTimeout is the franz-go and Kafka default,
// set explicitly so the budget check below uses the real value.
defaultConsumerRebalanceTimeout = time.Minute
minConsumerRebalanceTimeout = 10 * time.Second
maxConsumerRebalanceTimeout = 30 * time.Minute
// consumerRebalanceMargin covers the poll, the heartbeat that notices
// the rebalance, and scheduling, on top of the worst case of one record.
consumerRebalanceMargin = 5 * time.Second
)
func (config *Config) loadConsumer(lookup LookupEnv) error {
var err error
if config.ConsumerEnabled, err = boolOrDefault(lookup, "CONSUMER_ENABLED", defaultConsumerEnabled); err != nil {
return err
}
config.ConsumerGroupPrefix = strings.TrimSpace(valueOrDefault(lookup, "CONSUMER_GROUP_PREFIX", defaultConsumerGroupPrefix))
if config.ConsumerMaxAttempts, err = intOrDefault(lookup, "CONSUMER_MAX_ATTEMPTS", defaultConsumerMaxAttempts); err != nil {
return err
}
if config.ConsumerBackoffInitial, err = durationOrDefault(lookup, "CONSUMER_BACKOFF_INITIAL", defaultConsumerBackoffInitial); err != nil {
return err
}
if config.ConsumerBackoffMax, err = durationOrDefault(lookup, "CONSUMER_BACKOFF_MAX", defaultConsumerBackoffMax); err != nil {
return err
}
if config.ConsumerHandlerTimeout, err = durationOrDefault(lookup, "CONSUMER_HANDLER_TIMEOUT", defaultConsumerHandlerTimeout); err != nil {
return err
}
if config.ConsumerMaxPollRecords, err = intOrDefault(lookup, "CONSUMER_MAX_POLL_RECORDS", defaultConsumerMaxPollRecords); err != nil {
return err
}
if config.ConsumerCommitTimeout, err = durationOrDefault(lookup, "CONSUMER_COMMIT_TIMEOUT", defaultConsumerCommitTimeout); err != nil {
return err
}
if config.ConsumerShutdownGrace, err = durationOrDefault(lookup, "CONSUMER_SHUTDOWN_GRACE", defaultConsumerShutdownGrace); err != nil {
return err
}
config.ConsumerRebalanceTimeout, err = durationOrDefault(lookup, "CONSUMER_REBALANCE_TIMEOUT", defaultConsumerRebalanceTimeout)
return err
}
// ValidateConsumer checks the consumer settings even when consumers are
// disabled, so enabling them later cannot surface an old mistake.
func (config Config) ValidateConsumer() error {
// A group ID allows any characters, but the prefix also appears in logs
// and broker ACLs, so it follows the topic name rules.
if len(config.ConsumerGroupPrefix) > maxConsumerGroupPrefixLength || !kafkaTopicNamePattern.MatchString(config.ConsumerGroupPrefix) {
return fmt.Errorf("Config.ValidateConsumer - CONSUMER_GROUP_PREFIX must be 1 to %d letters, digits, dots, underscores, or hyphens", maxConsumerGroupPrefixLength)
}
if err := config.validateConsumerRetries(); err != nil {
return err
}
if err := config.validateConsumerTimeouts(); err != nil {
return err
}
return config.validateConsumerRebalance()
}
func (config Config) validateConsumerRetries() error {
if config.ConsumerMaxAttempts < 1 || config.ConsumerMaxAttempts > maxConsumerMaxAttempts {
return fmt.Errorf("Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS must be between 1 and %d", maxConsumerMaxAttempts)
}
if config.ConsumerBackoffInitial <= 0 {
return errors.New("Config.ValidateConsumer - CONSUMER_BACKOFF_INITIAL must be positive")
}
if config.ConsumerBackoffMax < config.ConsumerBackoffInitial || config.ConsumerBackoffMax > maxConsumerBackoff {
return fmt.Errorf("Config.ValidateConsumer - CONSUMER_BACKOFF_MAX must be between CONSUMER_BACKOFF_INITIAL and %s", maxConsumerBackoff)
}
if config.ConsumerMaxPollRecords < 1 || config.ConsumerMaxPollRecords > maxConsumerMaxPollRecords {
return fmt.Errorf("Config.ValidateConsumer - CONSUMER_MAX_POLL_RECORDS must be between 1 and %d", maxConsumerMaxPollRecords)
}
return nil
}
func (config Config) validateConsumerTimeouts() error {
if config.ConsumerHandlerTimeout < minConsumerHandlerTimeout || config.ConsumerHandlerTimeout > maxConsumerHandlerTimeout {
return fmt.Errorf("Config.ValidateConsumer - CONSUMER_HANDLER_TIMEOUT must be between %s and %s", minConsumerHandlerTimeout, maxConsumerHandlerTimeout)
}
if config.ConsumerCommitTimeout < minConsumerCommitTimeout || config.ConsumerCommitTimeout > maxConsumerCommitTimeout {
return fmt.Errorf("Config.ValidateConsumer - CONSUMER_COMMIT_TIMEOUT must be between %s and %s", minConsumerCommitTimeout, maxConsumerCommitTimeout)
}
// The grace runs while the HTTP servers drain, so it must fit in the
// shutdown budget of the process.
if config.ConsumerShutdownGrace <= 0 || config.ConsumerShutdownGrace > config.ShutdownTimeout {
return errors.New("Config.ValidateConsumer - CONSUMER_SHUTDOWN_GRACE must be positive and at most SHUTDOWN_TIMEOUT")
}
return nil
}
// validateConsumerRebalance keeps the slowest record below the rebalance
// timeout. A consumer holds group rebalancing while it processes a poll and
// commits after every record that needed a retry, so one record is the unit
// that must fit: every handler attempt, the longest wait before each retry,
// the dead letter write, and the offset commit. A member that exceeds the
// timeout is removed from the group, and its records are processed again.
// Database outages are not part of the budget: they are retried without a
// bound, and the removal they can cause is harmless because of the markers.
func (config Config) validateConsumerRebalance() error {
if config.ConsumerRebalanceTimeout < minConsumerRebalanceTimeout || config.ConsumerRebalanceTimeout > maxConsumerRebalanceTimeout {
return fmt.Errorf("Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must be between %s and %s", minConsumerRebalanceTimeout, maxConsumerRebalanceTimeout)
}
worstRecord := config.consumerRecordBudget()
if worstRecord+consumerRebalanceMargin > config.ConsumerRebalanceTimeout {
return fmt.Errorf("Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must exceed the worst case of one record (%s) by %s; lower CONSUMER_MAX_ATTEMPTS, CONSUMER_HANDLER_TIMEOUT, CONSUMER_BACKOFF_MAX, or CONSUMER_COMMIT_TIMEOUT, or raise the timeout",
worstRecord, consumerRebalanceMargin)
}
return nil
}
// consumerRecordBudget is the longest time one record can take without a
// database outage: CONSUMER_MAX_ATTEMPTS handler attempts, the longest
// backoff before each retry, one dead letter write, and one offset commit.
// The backoff ceiling starts at CONSUMER_BACKOFF_INITIAL and doubles up to
// CONSUMER_BACKOFF_MAX, as the workers' retry.Backoff does.
func (config Config) consumerRecordBudget() time.Duration {
attempts := config.ConsumerMaxAttempts
budget := time.Duration(attempts+1) * config.ConsumerHandlerTimeout
ceiling := min(config.ConsumerBackoffInitial, config.ConsumerBackoffMax)
for retry := 1; retry < attempts; retry++ {
budget += ceiling
ceiling = min(ceiling*2, config.ConsumerBackoffMax)
}
return budget + config.ConsumerCommitTimeout
}
+126
View File
@@ -0,0 +1,126 @@
package config
import (
"strings"
"testing"
"time"
)
func TestLoadFromEnvConsumerDefaults(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(nil))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if !settings.ConsumerEnabled || settings.ConsumerGroupPrefix != "lincodex" || settings.ConsumerMaxAttempts != 5 ||
settings.ConsumerBackoffInitial != 500*time.Millisecond || settings.ConsumerBackoffMax != 10*time.Second ||
settings.ConsumerHandlerTimeout != 5*time.Second || settings.ConsumerMaxPollRecords != 100 ||
settings.ConsumerCommitTimeout != 5*time.Second || settings.ConsumerShutdownGrace != 5*time.Second ||
settings.ConsumerRebalanceTimeout != time.Minute {
t.Fatalf("unexpected consumer defaults: %+v", consumerSettings(settings))
}
// Six handler timeouts (five attempts and the dead letter write), the
// backoff ceilings 0.5s, 1s, 2s, and 4s, and one commit; the deployment
// guide quotes this value.
if budget := settings.consumerRecordBudget(); budget != 42500*time.Millisecond {
t.Fatalf("default record budget = %s, want 42.5s", budget)
}
}
func TestLoadFromEnvReadsConsumerSettings(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{
"CONSUMER_ENABLED": " False ",
"CONSUMER_GROUP_PREFIX": " stand-1.lincodex ",
"CONSUMER_MAX_ATTEMPTS": "20",
"CONSUMER_BACKOFF_INITIAL": "1s",
"CONSUMER_BACKOFF_MAX": "1s",
"CONSUMER_HANDLER_TIMEOUT": "100ms",
"CONSUMER_MAX_POLL_RECORDS": "10000",
"CONSUMER_COMMIT_TIMEOUT": "1m",
"CONSUMER_SHUTDOWN_GRACE": "20s",
"SHUTDOWN_TIMEOUT": "20s",
// 21 handler timeouts, 19 waits of 1s, and one commit fit easily.
"CONSUMER_REBALANCE_TIMEOUT": "10m",
}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.ConsumerEnabled || settings.ConsumerGroupPrefix != "stand-1.lincodex" || settings.ConsumerMaxAttempts != 20 ||
settings.ConsumerBackoffInitial != time.Second || settings.ConsumerBackoffMax != time.Second ||
settings.ConsumerRebalanceTimeout != 10*time.Minute ||
settings.ConsumerHandlerTimeout != 100*time.Millisecond || settings.ConsumerMaxPollRecords != 10000 ||
settings.ConsumerCommitTimeout != time.Minute || settings.ConsumerShutdownGrace != 20*time.Second {
t.Fatalf("consumer settings were not loaded: %+v", consumerSettings(settings))
}
}
func TestLoadFromEnvRejectsConsumerSettings(t *testing.T) {
tests := []struct {
key, value, want string
}{
{key: "CONSUMER_ENABLED", value: "on", want: "config.boolOrDefault - CONSUMER_ENABLED"},
{key: "CONSUMER_GROUP_PREFIX", value: "", want: "Config.ValidateConsumer - CONSUMER_GROUP_PREFIX"},
{key: "CONSUMER_GROUP_PREFIX", value: "group/secret", want: "Config.ValidateConsumer - CONSUMER_GROUP_PREFIX"},
{key: "CONSUMER_GROUP_PREFIX", value: strings.Repeat("g", 129), want: "Config.ValidateConsumer - CONSUMER_GROUP_PREFIX"},
{key: "CONSUMER_MAX_ATTEMPTS", value: "", want: "config.intOrDefault - CONSUMER_MAX_ATTEMPTS"},
{key: "CONSUMER_MAX_ATTEMPTS", value: "0", want: "Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS"},
{key: "CONSUMER_MAX_ATTEMPTS", value: "21", want: "Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS"},
{key: "CONSUMER_BACKOFF_INITIAL", value: "soon", want: "config.durationOrDefault - parse CONSUMER_BACKOFF_INITIAL"},
{key: "CONSUMER_BACKOFF_INITIAL", value: "0s", want: "Config.ValidateConsumer - CONSUMER_BACKOFF_INITIAL"},
{key: "CONSUMER_BACKOFF_INITIAL", value: "11s", want: "Config.ValidateConsumer - CONSUMER_BACKOFF_MAX"},
{key: "CONSUMER_BACKOFF_MAX", value: "6m", want: "Config.ValidateConsumer - CONSUMER_BACKOFF_MAX"},
{key: "CONSUMER_HANDLER_TIMEOUT", value: "99ms", want: "Config.ValidateConsumer - CONSUMER_HANDLER_TIMEOUT"},
{key: "CONSUMER_HANDLER_TIMEOUT", value: "6m", want: "Config.ValidateConsumer - CONSUMER_HANDLER_TIMEOUT"},
{key: "CONSUMER_MAX_POLL_RECORDS", value: "0", want: "Config.ValidateConsumer - CONSUMER_MAX_POLL_RECORDS"},
{key: "CONSUMER_MAX_POLL_RECORDS", value: "10001", want: "Config.ValidateConsumer - CONSUMER_MAX_POLL_RECORDS"},
{key: "CONSUMER_COMMIT_TIMEOUT", value: "99ms", want: "Config.ValidateConsumer - CONSUMER_COMMIT_TIMEOUT"},
{key: "CONSUMER_COMMIT_TIMEOUT", value: "61s", want: "Config.ValidateConsumer - CONSUMER_COMMIT_TIMEOUT"},
{key: "CONSUMER_SHUTDOWN_GRACE", value: "0s", want: "Config.ValidateConsumer - CONSUMER_SHUTDOWN_GRACE"},
// Longer than the default SHUTDOWN_TIMEOUT of 10s.
{key: "CONSUMER_SHUTDOWN_GRACE", value: "11s", want: "Config.ValidateConsumer - CONSUMER_SHUTDOWN_GRACE"},
{key: "CONSUMER_REBALANCE_TIMEOUT", value: "soon", want: "config.durationOrDefault - parse CONSUMER_REBALANCE_TIMEOUT"},
{key: "CONSUMER_REBALANCE_TIMEOUT", value: "9s", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must be between"},
{key: "CONSUMER_REBALANCE_TIMEOUT", value: "31m", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must be between"},
// The default 42.5s budget plus the 5s margin exceeds 45s.
{key: "CONSUMER_REBALANCE_TIMEOUT", value: "45s", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must exceed"},
// Twenty attempts with the default timeouts need several minutes.
{key: "CONSUMER_MAX_ATTEMPTS", value: "20", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must exceed"},
}
for _, test := range tests {
t.Run(test.key+"/"+test.value, func(t *testing.T) {
_, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value}))
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want)
}
if strings.Contains(err.Error(), "secret") {
t.Fatal("configuration error disclosed the value")
}
})
}
}
func TestValidateConsumerChecksSettingsEvenWhenDisabled(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{"CONSUMER_ENABLED": "false"}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
settings.ConsumerMaxAttempts = 0
if err := settings.Validate(); err == nil || !strings.HasPrefix(err.Error(), "Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS") {
t.Fatalf("Validate() error = %v, want the consumer attempts error", err)
}
}
// consumerSettings collects the consumer fields for failure messages.
func consumerSettings(settings Config) map[string]any {
return map[string]any{
"enabled": settings.ConsumerEnabled,
"group_prefix": settings.ConsumerGroupPrefix,
"max_attempts": settings.ConsumerMaxAttempts,
"backoff_initial": settings.ConsumerBackoffInitial,
"backoff_max": settings.ConsumerBackoffMax,
"handler_timeout": settings.ConsumerHandlerTimeout,
"max_poll": settings.ConsumerMaxPollRecords,
"commit_timeout": settings.ConsumerCommitTimeout,
"shutdown_grace": settings.ConsumerShutdownGrace,
"rebalance": settings.ConsumerRebalanceTimeout,
}
}