// TrackMessageAge is middleware that tracks the exponential moving average of message age, calling a callback function with the current average periodically func TrackMessageAge(period time.Duration, f func(age float64)) MessageHandlerDecorator { ema := movingaverage.New(period) go func() { for { <-time.After(period) f(ema.Value()) } }() return func(fn sqsconsumer.MessageHandlerFunc) sqsconsumer.MessageHandlerFunc { return func(ctx context.Context, msg string) error { age, err := computeMessageAge(ctx) if err == nil { ema.Update(age) } return fn(ctx, msg) } } }
// TrackMetrics decorates a MessageHandler to collect metrics about successes, failures and runtime reports in ms*10. func TrackMetrics(successes, failures *expvar.Int, timing *expvar.Float) MessageHandlerDecorator { ema := movingaverage.New(5 * time.Second) return func(fn sqsconsumer.MessageHandlerFunc) sqsconsumer.MessageHandlerFunc { return func(ctx context.Context, msg string) error { start := time.Now() defer func() { v := ema.Update(time.Since(start).Seconds() * 1000) timing.Set(v) }() err := fn(ctx, msg) if err != nil { failures.Add(1) } else { successes.Add(1) } return err } } }