streamfleet

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2025 License: MIT Imports: 12 Imported by: 2 modules, 2 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.

README

streamfleet

Customizable Go work queue implementation backed by Redis Streams (or Valkey Streams). No Lua or fancy tricks required.

Tasks placed on the queue are processed once by the worker that can pick up the task quickest. Completion can be optionally tracked.

Features

  • Optional task completion notifications
  • Support for Redis Sentinel and Cluster
  • Automatic retry and worker crash recovery
  • Tolerance for Redis downtime without data loss

Architecture

The application is broken up into two components, coordinated by Redis:

  • The client, which submits (enqueues) tasks to the queue.

    Clients can optionally track completion or failure of tasks by listening for notifications about them. Whether to send completion notifications is sent along with the task.

  • The server (worker), which accepts work from the queue and processes it.

    In addition to receiving new tasks, workers can claim tasks that have sat idle too long in other workers' pending lists. Long-running tasks are kept fresh and not in an idle state as long as the task is pending in the functional server. Only servers that have crashed or are unresponsive would have their tasks reclaimed.

    If a task fails while the worker is running, the server will put the task back on the queue and increment its failure count.

Note that servers and clients may exist on the same process; they do not need to be in separate microservices.

Task notifications are sent over a client-specific stream for reliable delivery, even if there is temporary disconnection from Redis. Clients clean up these streams when their Close method is called to avoid resource leaks. In the event that they are not closed cleanly, other clients and servers use a simple garbage collector based on client heartbeats to find orphaned client streams and delete them.

If the underlying Redis server is unavailable, the clients will wait until it comes back online. Tasks submitted to the client stay queued in-memory until Redis is available.

The overall design philosophy is to support queues with high error tolerance without losing anything, and to have as few moving parts as possible. Many systems already have Redis, why not use its stream feature for reliable message delivery? No need to introduce a complex system like Kafka. As well as being fault-tolerance, the implementation aims to be as autonomous as possible. There are no features that rely on centralized coordination, other than Redis itself (which can be clustered for high-availability).

Use It

To add the library to your project, run:

go get github.com/termermc/streamfleet

To see some examples, visit the examples directory.

Simple Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/termermc/streamfleet"
)

func main() {
	redisOpt := streamfleet.RedisClientOpt{
		Addr: "127.0.0.1:6379",
	}
	
	const MessagesQueueKey = "messages"

	ctx := context.Background()

	// Create server.
	// ServerUniqueId is used to differentiate servers from each other.
	// Some other options we could specify:
	//  - Logger (an implementation of slog.Logger from the standard library to override the default logger)
	//  - HandlerConcurrency (how many concurrent tasks the server can handle, defaults to 1)
	// Take a look at the ServerOpt struct for a complete list of options.
	server, err := streamfleet.NewServer(ctx, streamfleet.ServerOpt{
		ServerUniqueId: "node1.example.com",
		RedisOpt:       redisOpt,
	})
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = server.Close()
	}()

	// Register handlers for queues.
	// This must be done before running the server.
	server.Handle(MessagesQueueKey, func(ctx context.Context, task *streamfleet.Task) error {
		fmt.Printf("Got message: %s\n", task.Data)
		return nil
	})

	// Launch server.
	// The Run() method blocks until the server is closed or runs into a fatal error, so it is launched in its own goroutine.
	// Note that servers do not need to be created before clients; queued messages will be picked up as soon as a server is available.
	go func() {
		err := server.Run()
		if err != nil {
			panic(err)
		}
	}()

	// Create a client using the same Redis connection options as the server.
	// Unlike servers, we do not need to manually provide a unique ID.
	// Instead, the client generates its own internally.
	// Take a look at the ClientOpt struct for a complete list of options.
	client, err := streamfleet.NewClient(ctx, streamfleet.ClientOpt{
		RedisOpt: redisOpt,
	}, MessagesQueueKey)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = client.Close()
	}()

	// Send some messages for the server to print.
	ticker := time.NewTicker(1 * time.Second)
	for range ticker.C {
		// Here, we're using EnqueueAndForget which, as the name suggests, uses a fire-and-forget strategy.
		// If we wanted to know when a server successfully processed the task or ran into an error, we could have used EnqueueAndForget.
		// Some other options we could specify:
		//  - MaxRetries (the maximum number of times to retry the task on failure, defaults to 0 for infinite tries)
		//  - ExpiresTs (an expiration timestamp, at which time the task will be expired if not already processed)
		// Take a look at the TaskOpt struct for a complete list of options.
		err = client.EnqueueAndForget(MessagesQueueKey, "The current time is: "+time.Now().String(), streamfleet.TaskOpt{})
		if err != nil {
			panic(err)
		}
	}
}

Documentation

Index

Constants

View Source
const DefaultReceiverStreamGcInterval = 1 * time.Minute

DefaultReceiverStreamGcInterval is the default interval at which receiver stream garbage collections are run. This applies to clients and servers if no specific interval is set.

View Source
const KeyPrefix = "streamfleet:"

KeyPrefix is the prefix used by Streamfleet for all Redis keys, including work queue streams. The underlying stream key for a queue will be KeyPrefix + the queue's key.

View Source
const TaskMaxPendingTime = 1 * time.Minute

TaskMaxPendingTime is the maximum time a task can sit in a worker's pending list before it is reclaimable by other workers. Tasks pending time is updated by healthy clients at the interval specified by TaskUpdatePendingInterval. This duration will always be higher than TaskUpdatePendingInterval to ensure healthy tasks aren't being reclaimed.

View Source
const TaskUpdatePendingInterval = 10 * time.Second

TaskUpdatePendingInterval is the interval at which the pending time of a task is updated.

Variables

View Source
var ErrClientQueueFull = fmt.Errorf(`streamfleet: client queue is full, tasks are being enqueued too quickly to send to Redis, or Redis is unreachable`)

ErrClientQueueFull is returned when the client's queue is full. This can be returned when enqueuing tasks, or be the logged error when a task is trying to be re-queued after an error.

View Source
var ErrMissingOrMalformedEncodingVersion = errors.New("streamfleet: missing or malformed enc_version in encoded message")

ErrMissingOrMalformedEncodingVersion is returned when the version field of an encoded message from a Redis stream is missing or malformed.

View Source
var ErrMissingRedisOpt = fmt.Errorf("streamfleet: Redis client options are missing")

ErrMissingRedisOpt is returned when a server is instantiated without the necessary options to construct a Redis client.

View Source
var ErrMissingServerUniqueId = fmt.Errorf("streamfleet: server unique ID is missing")

ErrMissingServerUniqueId is returned when a server is instantiated without a unique ID.

View Source
var ErrNoQueues = fmt.Errorf("streamfleet: tried to run a server or instantiate a client that had no configured queue keys")

ErrNoQueues is returned when running a server or instantiating a client without specifying any queue keys.

View Source
var ErrTaskCanceled = fmt.Errorf("streamfleet: task canceled")

ErrTaskCanceled is returned when a task has been canceled.

View Source
var ErrTaskExpired = fmt.Errorf("streamfleet: task expired")

ErrTaskExpired is returned when a task could not be handled before its expiration time.

View Source
var ErrUnsupportedEncodingVersion = errors.New("streamfleet: unsupported enc_version in encoded message, this node may be running an outdated version of Streamfleet")

ErrUnsupportedEncodingVersion is returned when the version field of an encoded message from a Redis stream is unsupported.

View Source
var ErrUnsupportedQueueKey = fmt.Errorf(`streamfleet: unsupported queue key, client was not instantiated with support for this queue key`)

ErrUnsupportedQueueKey is returned when trying to enqueue a task for a queue key that the client was not instantiated with.

Functions

func MustUuidV7

func MustUuidV7() string

MustUuidV7 returns a new UUIDv7 string. If there are errors in creating it (which could only ever happen because of an OS error related to PRNG), the function panics.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a work queue client. It submits tasks to the queue and can receive notifications of their completion.

func NewClient

func NewClient(ctx context.Context, opt ClientOpt, queueKeys ...string) (*Client, error)

NewClient creates a new client instance. The list of queue keys to support for this client must be exhaustive and cannot change without creating a new client. Returns ErrNoQueues if no queue keys were specified.

func (*Client) Close

func (c *Client) Close() error

Close closes resources associated with the client. Will cancel pending tasks. Locally queued tasks will be lost. The client must not be used after calling Close. Subsequent Close calls are no-op.

func (*Client) EnqueueAndForget

func (c *Client) EnqueueAndForget(queueKey string, data string, opt TaskOpt) error

EnqueueAndForget adds a task to the queue and immediately returns. Errors in queuing or the status of the task once it is picked up by a server are not tracked. If you need to know when the task has been completed, use EnqueueAndTrack.

If the number of locally queued tasks would exceed ClientOpt.MaxLocalQueueSize, returns ErrClientQueueFull. This will normally only happen if the client cannot connect to Redis and tasks pile up.

func (*Client) EnqueueAndTrack

func (c *Client) EnqueueAndTrack(queueKey string, data string, opt TaskOpt) (*TaskHandle, error)

EnqueueAndTrack adds a task to the queue and returns a handle to it. Errors in queuing or the status of the task once it is picked up by the server can be tracked using the returned handle. If you do not need to know when the task has been completed, use EnqueueAndForget. You should only use this method if you need to know the status of the task, as it is less efficient than EnqueueAndForget.

If the number of locally queued tasks would exceed ClientOpt.MaxLocalQueueSize, returns ErrClientQueueFull. This will normally only happen if the client cannot connect to Redis and tasks pile up.

type ClientOpt

type ClientOpt struct {
	// The Redis client options to use.
	// See the RedisClientOpt, RedisClusterClientOpt or RedisClusterClientOpt struct for more details.
	//
	// Required.
	RedisOpt ToRedisClient

	// The maximum number of tasks to queue locally in-memory while waiting for Redis to come back online.
	// After the local queue has filled up, new tasks being queued will result in an error.
	// Defaults to 25.
	MaxLocalQueueSize int

	// The interval at which to run the receiver stream garbage collector.
	// If omitted, defaults to DefaultReceiverStreamGcInterval.
	// If you do not know what this is, you do not need to change it.
	ReceiverStreamGcInterval time.Duration
	// contains filtered or unexported fields
}

ClientOpt are options for Streamfleet clients.

type RedisClientOpt

type RedisClientOpt struct {
	// Network type to use, either tcp or unix.
	// Default is tcp.
	Network string

	// Redis server address in "host:port" format.
	Addr string

	// Username to authenticate the current connection when Redis ACLs are used.
	// See: https://redis.io/commands/auth.
	Username string

	// Password to authenticate the current connection.
	// See: https://redis.io/commands/auth.
	Password string

	// Redis DB to select after connecting to a server.
	// See: https://redis.io/commands/select.
	DB int

	// Dial timeout for establishing new connections.
	// Default is 5 seconds.
	DialTimeout time.Duration

	// Timeout for socket reads.
	// If timeout is reached, read commands will fail with a timeout error
	// instead of blocking.
	//
	// Use value -1 for no timeout and 0 for default.
	// Default is 3 seconds.
	ReadTimeout time.Duration

	// Timeout for socket writes.
	// If timeout is reached, write commands will fail with a timeout error
	// instead of blocking.
	//
	// Use value -1 for no timeout and 0 for default.
	// Default is ReadTimout.
	WriteTimeout time.Duration

	// Maximum number of socket connections.
	// Default is 10 connections per every CPU as reported by runtime.NumCPU.
	PoolSize int

	// TLS Config used to connect to a server.
	// TLS will be negotiated only if this field is set.
	TLSConfig *tls.Config
}

RedisClientOpt is used to create a redis client that connects to a redis server directly.

func (RedisClientOpt) ToClient

func (opt RedisClientOpt) ToClient() redis.UniversalClient

type RedisClusterClientOpt

type RedisClusterClientOpt struct {
	// A seed list of host:port addresses of cluster nodes.
	Addrs []string

	// The maximum number of retries before giving up.
	// Command is retried on network errors and MOVED/ASK redirects.
	// Default is 8 retries.
	MaxRedirects int

	// Username to authenticate the current connection when Redis ACLs are used.
	// See: https://redis.io/commands/auth.
	Username string

	// Password to authenticate the current connection.
	// See: https://redis.io/commands/auth.
	Password string

	// Dial timeout for establishing new connections.
	// Default is 5 seconds.
	DialTimeout time.Duration

	// Timeout for socket reads.
	// If timeout is reached, read commands will fail with a timeout error
	// instead of blocking.
	//
	// Use value -1 for no timeout and 0 for default.
	// Default is 3 seconds.
	ReadTimeout time.Duration

	// Timeout for socket writes.
	// If timeout is reached, write commands will fail with a timeout error
	// instead of blocking.
	//
	// Use value -1 for no timeout and 0 for default.
	// Default is ReadTimeout.
	WriteTimeout time.Duration

	// TLS Config used to connect to a server.
	// TLS will be negotiated only if this field is set.
	TLSConfig *tls.Config
}

RedisClusterClientOpt is used to creates a redis client that connects to redis cluster.

func (RedisClusterClientOpt) ToClient

type RedisFailoverClientOpt

type RedisFailoverClientOpt struct {
	// Redis master name that monitored by sentinels.
	MasterName string

	// Addresses of sentinels in "host:port" format.
	// Use at least three sentinels to avoid problems described in
	// https://redis.io/topics/sentinel.
	SentinelAddrs []string

	// Redis sentinel username.
	SentinelUsername string

	// Redis sentinel password.
	SentinelPassword string

	// Username to authenticate the current connection when Redis ACLs are used.
	// See: https://redis.io/commands/auth.
	Username string

	// Password to authenticate the current connection.
	// See: https://redis.io/commands/auth.
	Password string

	// Redis DB to select after connecting to a server.
	// See: https://redis.io/commands/select.
	DB int

	// Dial timeout for establishing new connections.
	// Default is 5 seconds.
	DialTimeout time.Duration

	// Timeout for socket reads.
	// If timeout is reached, read commands will fail with a timeout error
	// instead of blocking.
	//
	// Use value -1 for no timeout and 0 for default.
	// Default is 3 seconds.
	ReadTimeout time.Duration

	// Timeout for socket writes.
	// If timeout is reached, write commands will fail with a timeout error
	// instead of blocking.
	//
	// Use value -1 for no timeout and 0 for default.
	// Default is ReadTimeout
	WriteTimeout time.Duration

	// Maximum number of socket connections.
	// Default is 10 connections per every CPU as reported by runtime.NumCPU.
	PoolSize int

	// TLS Config used to connect to a server.
	// TLS will be negotiated only if this field is set.
	TLSConfig *tls.Config
}

RedisFailoverClientOpt is used to creates a redis client that talks to redis sentinels for service discovery and has an automatic failover capability.

func (RedisFailoverClientOpt) ToClient

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a work queue server (a worker). It accepts tasks from the queue and handles them.

func NewServer

func NewServer(ctx context.Context, opt ServerOpt) (*Server, error)

NewServer creates a new server instance. It does not connect to Redis until Server.Run is called.

func (*Server) Close

func (s *Server) Close() error

Close stops the server. Will cancel pending tasks and wait for processing loops to finish. The server must not be used after calling Close. Subsequent Close calls are no-op.

func (*Server) Handle

func (s *Server) Handle(queueKey string, handler TaskHandler)

Handle sets the handler for the queue with the specified key. Once the handler returns, the task will be acknowledged as complete if error is nil, otherwise it will be re-queued according to its retry policy. If the server is already running, this function panics.

func (*Server) Run

func (s *Server) Run() error

Run runs the server. It will only return if the server's initial connection fails, or retrying the connection times out. Note that handlers are not guaranteed to run on the same goroutine as this call.

Since this method will run for the duration of the server's life, it blocks and should usually be run in its own goroutine.

type ServerOpt

type ServerOpt struct {
	// The unique identifier of the server.
	// This ID should be unique among all servers accepting work from any particular queue.
	// Usually, this should correspond to the name of the logical machine, e.g. its hostname (if unique).
	// Collisions in server unique IDs can result in unexpected behavior, such as work not being distributed evenly among servers.
	//
	// Required.
	ServerUniqueId string

	// The Redis client options to use.
	// See the RedisClientOpt, RedisClusterClientOpt or RedisClusterClientOpt struct for more details.
	//
	// Required.
	RedisOpt ToRedisClient

	// The number of concurrent handlers to run at once.
	// If unspecified or <1, defaults to 1.
	HandlerConcurrency int

	// The interval at which to run the receiver stream garbage collector.
	// If omitted, defaults to DefaultReceiverStreamGcInterval.
	// If you do not know what this is, you do not need to change it.
	ReceiverStreamGcInterval time.Duration
	// contains filtered or unexported fields
}

ServerOpt are options for Streamfleet servers.

type Task

type Task struct {
	// The message's unique ID.
	Id string

	// The ID of the client where the task originated.
	ClientId string

	// The task's underlying data.
	// Required, but technically can be nil/empty.
	Data string

	// The task's maximum retry count.
	// If a task is retried more than this many times, it will be removed from the queue, and optionally send a canceled signal.
	// If 0, the task will be retried until success.
	MaxRetries int

	// The timestamp when the task expires.
	// If a worker receives the task past this timestamp, it will discard it, and optionally send a canceled signal.
	// If omitted, never expires.
	// Precision below 1 second is not guaranteed to be enforced immediately by clients; it may take up to 1 second for expirations to be notified.
	ExpiresTs time.Time

	// The duration to delay retrying the task.
	RetryDelay time.Duration
	// contains filtered or unexported fields
}

Task is a task to be processed by a worker. It is sent to the queue, and then processed by a worker. The only required field is Data. Do not construct directly, use client enqueue methods.

type TaskHandle

type TaskHandle struct {
	// The task's unique ID.
	Id string
	// contains filtered or unexported fields
}

TaskHandle is a handle to a task that was enqueued by a client. The task may or may not have been completed.

func (*TaskHandle) Wait

func (t *TaskHandle) Wait() error

Wait waits for the task to complete and returns the result. Subsequent calls will return the same result. If the task was canceled, the error will be ErrTaskCanceled. If the task expired before being processed, the error will be ErrTaskExpired.

Important: Do not call this method concurrently, otherwise it may panic.

type TaskHandler

type TaskHandler func(ctx context.Context, task *Task) error

TaskHandler is a function that handles a task. Once it returns, the task will be acknowledged as complete if error is nil, otherwise it will be re-queued according to its retry policy. If the task is canceled, ctx will be canceled.

type TaskNotification

type TaskNotification struct {
	// The task ID.
	TaskId string

	// The task type.
	Type TaskNotificationType

	// The error message, if Type is TaskNotificationTypeError.
	// Otherwise, empty.
	ErrMsg string
}

TaskNotification is a notification sent about a task's status.

type TaskNotificationType

type TaskNotificationType string
const (
	// TaskNotificationTypeCompleted is sent when a task is completed successfully.
	TaskNotificationTypeCompleted TaskNotificationType = "completed"

	// TaskNotificationTypeCanceled is sent when a task is canceled.
	TaskNotificationTypeCanceled TaskNotificationType = "canceled"

	// TaskNotificationTypeExpired is sent when a task expires.
	TaskNotificationTypeExpired TaskNotificationType = "expired"

	// TaskNotificationTypeError is sent when a task fails due to an error.
	// The notification should include the underlying error message.
	TaskNotificationTypeError TaskNotificationType = "error"
)

type TaskOpt

type TaskOpt struct {
	// The maximum number of retries for this task.
	// If omitted or 0, the task will be retried until success or expiration.
	MaxRetries int

	// The timestamp when the task expires.
	// If a worker receives the task past this timestamp, it will discard it.
	// If omitted, the task will never expire.
	ExpiresTs time.Time

	// The duration to delay retrying the task.
	// If omitted, there is no delay.
	RetryDelay time.Duration
}

TaskOpt are options for creating a task. All fields are optional.

type ToRedisClient

type ToRedisClient interface {
	ToClient() redis.UniversalClient
}

ToRedisClient is a type that can be used to create a Redis client.

Directories

Path Synopsis
examples
email command
simple command

Jump to

Keyboard shortcuts

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