middleware

package
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package middleware provides messaging-specific goflux.Middleware implementations: acknowledgment handling (auto-ack, retry-policy-aware ack/nak/term), header injection and message-ID forwarding for handler chains.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoAck

func AutoAck[T any]() goflux.Middleware[T]

AutoAck returns a Middleware that acknowledges messages automatically: nil handler error triggers Ack, non-nil error triggers Nak. Messages without an acker (fire-and-forget transports) are passed through as-is.

Example

ExampleAutoAck demonstrates the AutoAck middleware. On handler success, Ack is called; on handler error, Nak is called.

package main

import (
	"context"
	"fmt"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/middleware"
)

// ExampleAutoAck demonstrates the AutoAck middleware. On handler success,
// Ack is called; on handler error, Nak is called.
func main() {
	// Spy acker records which method was called.
	acker := &spyAcker{}

	msg := goflux.NewMessage("events", "payload").WithAcker(acker)

	handler := middleware.AutoAck[string]()(func(_ context.Context, _ goflux.Message[string]) error {
		return nil // success
	})

	_ = handler(context.Background(), msg)

	fmt.Println("acked:", acker.acked)
	fmt.Println("naked:", acker.naked)
}

// spyAcker records ack/nak calls for testing.
type spyAcker struct {
	acked bool
	naked bool
}

func (s *spyAcker) Ack() error { s.acked = true; return nil }
func (s *spyAcker) Nak() error { s.naked = true; return nil }
Output:
acked: true
naked: false

func ForwardMessageID added in v0.4.0

func ForwardMessageID[T any]() goflux.Middleware[T]

ForwardMessageID returns a goflux.Middleware that puts the received goflux.Message.ID into the context via goflux.WithMessageID, so messages published from the handler carry the same ID. Use this with pipe's pipe.WithMiddleware (or pipe.WithMapMiddleware for NewMap and NewFlatMap) to forward message IDs across pipe stages.

Transports never forward the ID on their own. The ID is the Nats-Msg-Id on NATS, so forward it only into a different JetStream stream: a forwarded message that lands in the same stream as the received one is dropped as a duplicate within the stream's Duplicates window. pipe.NewFlatMap derives one ID per item from the forwarded ID.

Example
package main

import (
	"context"
	"fmt"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/middleware"
)

func main() {
	inner := func(ctx context.Context, msg goflux.Message[string]) error {
		fmt.Println(goflux.MessageID(ctx))

		return nil
	}

	handler := middleware.ForwardMessageID[string]()(inner)

	msg := goflux.NewMessage("test", "payload")
	msg.ID = "msg-123"

	_ = handler(context.Background(), msg)
}
Output:
msg-123

func InjectHeader

func InjectHeader[T any]() goflux.Middleware[T]

InjectHeader returns a goflux.Middleware that injects the message's goflux.Header into the context via goflux.WithHeader. Downstream code can read it with goflux.HeaderFromContext.

No transport does this automatically, so use this middleware when downstream code reads goflux.HeaderFromContext.

Example

ExampleInjectHeader demonstrates injecting the full message header into the context so downstream code can access it via HeaderFromContext.

package main

import (
	"context"
	"fmt"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/middleware"
)

func main() {
	header := goflux.Header{}
	header.Set("X-Tenant", "acme")
	header.Set("X-Region", "eu-west-1")

	msg := goflux.NewMessageWithHeader("events", "payload", header)

	handler := middleware.InjectHeader[string]()(
		func(ctx context.Context, msg goflux.Message[string]) error {
			h := goflux.HeaderFromContext(ctx)
			fmt.Println("tenant:", h.Get("X-Tenant"))
			fmt.Println("region:", h.Get("X-Region"))

			return nil
		},
	)

	_ = handler(context.Background(), msg)
}
Output:
tenant: acme
region: eu-west-1

func KeepAlive added in v0.11.0

func KeepAlive[T any](interval time.Duration) goflux.Middleware[T]

KeepAlive returns a Middleware that calls goflux.Message.InProgress every interval while the handler runs, so long-running handlers (e.g. imports) are not redelivered when they exceed the transport's ack timeout. Choose an interval well below the timeout (e.g. JetStream AckWait / 3).

The heartbeat stops before the handler's result is returned, so place KeepAlive inside AutoAck or RetryAck in a goflux.Chain. Messages without an acker, and non-positive intervals, are passed through.

func RetryAck

func RetryAck[T any](policy RetryPolicy, opts ...RetryAckOption) goflux.Middleware[T]

RetryAck returns a Middleware that acknowledges messages based on handler outcome and a RetryPolicy:

The policy receives the message's goflux.Message.Delivery metadata. Each outcome is recorded via goflux.Telemetry.RecordAckOutcome. Messages without an acker (fire-and-forget transports) are passed through.

Types

type BackoffRetryPolicyOption added in v0.11.0

type BackoffRetryPolicyOption func(*backoffRetryPolicyConfig)

BackoffRetryPolicyOption configures NewBackoffRetryPolicy.

func BackoffRetryPolicyWithMaxDeliveries added in v0.11.0

func BackoffRetryPolicyWithMaxDeliveries(n uint64) BackoffRetryPolicyOption

BackoffRetryPolicyWithMaxDeliveries terminates the message once it has been delivered n times. Zero (the default) never terminates retryable errors. Has no effect when the transport does not report delivery counts.

func WithBackoffFactor added in v0.11.0

func WithBackoffFactor(factor float64) BackoffRetryPolicyOption

WithBackoffFactor sets the multiplier applied to the delay on each redelivery. Values below 1 are ignored. Default: 2.

type RetryAckOption added in v0.11.0

type RetryAckOption func(*retryAckConfig)

RetryAckOption configures RetryAck.

func RetryAckWithTelemetry added in v0.11.0

func RetryAckWithTelemetry(t *goflux.Telemetry) RetryAckOption

RetryAckWithTelemetry sets the Telemetry instance used to record ack outcomes. If not provided, a default instance is created from the current OTel globals. Pass the transport's instance so its goflux.WithDestinationTemplate also bounds the cardinality of the ack outcome metric.

type RetryAction

type RetryAction int

RetryAction describes how a failed message should be acknowledged.

const (
	// RetryNak triggers immediate redelivery via [goflux.Message.Nak].
	RetryNak RetryAction = iota
	// RetryNakWithDelay triggers delayed redelivery via [goflux.Message.NakWithDelay].
	// The delay is specified in [RetryDecision.Delay].
	RetryNakWithDelay
	// RetryTerm terminates the message via [goflux.Message.Term] — no further
	// redelivery will occur.
	RetryTerm
)

type RetryDecision

type RetryDecision struct {
	Action RetryAction
	Delay  time.Duration
}

RetryDecision holds the action and optional delay for a failed message.

type RetryPolicy

type RetryPolicy func(err error, delivery goflux.Delivery) RetryDecision

RetryPolicy inspects a handler error and the message's delivery metadata and decides how to acknowledge the failed message. delivery is the zero value when the transport does not report delivery metadata.

func NewBackoffRetryPolicy added in v0.11.0

func NewBackoffRetryPolicy(initial, maxDelay time.Duration, opts ...BackoffRetryPolicyOption) RetryPolicy

NewBackoffRetryPolicy returns a RetryPolicy whose nak delay grows with the message's delivery count: initial * factor^(NumDelivered-1), capped at maxDelay. Non-retryable errors (see goflux.ErrNonRetryable) are terminated. When the transport does not report a delivery count, the first delivery is assumed and initial is used.

maxDelay must be positive and at least initial: it is a hard cap, not an optional one, so zero yields NakWithDelay(0) — immediate redelivery — on every failure.

Example

ExampleNewBackoffRetryPolicy demonstrates a delay that grows with the message's delivery count and terminates after a maximum.

package main

import (
	"errors"
	"fmt"
	"time"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/middleware"
)

func main() {
	policy := middleware.NewBackoffRetryPolicy(time.Second, 30*time.Second,
		middleware.BackoffRetryPolicyWithMaxDeliveries(5),
	)

	for n := uint64(1); n <= 5; n++ {
		d := policy(errors.New("timeout"), goflux.Delivery{NumDelivered: n})
		fmt.Printf("delivery=%d action=%d delay=%v\n", n, d.Action, d.Delay)
	}

}
Output:
delivery=1 action=1 delay=1s
delivery=2 action=1 delay=2s
delivery=3 action=1 delay=4s
delivery=4 action=1 delay=8s
delivery=5 action=2 delay=0s

func NewRetryPolicy

func NewRetryPolicy(delay time.Duration) RetryPolicy

NewRetryPolicy returns a RetryPolicy that terminates non-retryable errors (see goflux.ErrNonRetryable) and naks all other errors with the given delay.

Example

ExampleNewRetryPolicy demonstrates creating and using a RetryPolicy that classifies errors into retry actions.

package main

import (
	"errors"
	"fmt"
	"time"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/middleware"
)

func main() {
	policy := middleware.NewRetryPolicy(2 * time.Second)

	// Retryable error.
	d := policy(errors.New("connection reset"), goflux.Delivery{})
	fmt.Printf("action=%d delay=%v\n", d.Action, d.Delay)

	// Non-retryable error.
	d = policy(goflux.NonRetryable(errors.New("schema mismatch")), goflux.Delivery{})
	fmt.Printf("action=%d\n", d.Action)

}
Output:
action=1 delay=2s
action=2

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL