Documentation
¶
Index ¶
Constants ¶
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.
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.
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.
const TaskUpdatePendingInterval = 10 * time.Second
TaskUpdatePendingInterval is the interval at which the pending time of a task is updated.
Variables ¶
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.
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.
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.
var ErrMissingServerUniqueId = fmt.Errorf("streamfleet: server unique ID is missing")
ErrMissingServerUniqueId is returned when a server is instantiated without a unique ID.
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.
var ErrTaskCanceled = fmt.Errorf("streamfleet: task canceled")
ErrTaskCanceled is returned when a task has been canceled.
var ErrTaskExpired = fmt.Errorf("streamfleet: task expired")
ErrTaskExpired is returned when a task could not be handled before its expiration time.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func (opt RedisClusterClientOpt) ToClient() redis.UniversalClient
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 ¶
func (opt RedisFailoverClientOpt) ToClient() redis.UniversalClient
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 ¶
NewServer creates a new server instance. It does not connect to Redis until Server.Run is called.
func (*Server) Close ¶
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 ¶
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 ¶
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.