2020-01-03 10:13:16 +08:00
|
|
|
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
|
2019-12-22 23:15:45 +08:00
|
|
|
// Package base defines foundational types and constants used in asynq package.
|
|
|
|
package base
|
|
|
|
|
2019-12-23 21:33:48 +08:00
|
|
|
import (
|
2020-02-13 09:12:09 +08:00
|
|
|
"context"
|
2021-06-09 21:46:21 +08:00
|
|
|
"crypto/md5"
|
|
|
|
"encoding/hex"
|
2020-01-31 22:48:58 +08:00
|
|
|
"fmt"
|
2021-07-15 21:12:13 +08:00
|
|
|
"strings"
|
2020-02-02 14:22:48 +08:00
|
|
|
"sync"
|
2019-12-23 21:33:48 +08:00
|
|
|
"time"
|
|
|
|
|
2021-09-02 20:56:02 +08:00
|
|
|
"github.com/go-redis/redis/v8"
|
2021-03-13 08:23:08 +08:00
|
|
|
"github.com/golang/protobuf/ptypes"
|
2021-05-23 04:03:12 +08:00
|
|
|
"github.com/hibiken/asynq/internal/errors"
|
2021-03-13 08:23:08 +08:00
|
|
|
pb "github.com/hibiken/asynq/internal/proto"
|
2022-02-14 06:06:26 +08:00
|
|
|
"github.com/hibiken/asynq/internal/timeutil"
|
2021-03-13 08:23:08 +08:00
|
|
|
"google.golang.org/protobuf/proto"
|
2019-12-23 21:33:48 +08:00
|
|
|
)
|
2019-12-22 23:15:45 +08:00
|
|
|
|
2020-06-30 04:56:53 +08:00
|
|
|
// Version of asynq library and CLI.
|
2022-01-22 22:15:29 +08:00
|
|
|
const Version = "0.21.0"
|
2020-06-30 04:56:53 +08:00
|
|
|
|
2020-01-06 22:53:40 +08:00
|
|
|
// DefaultQueueName is the queue name used if none are specified by user.
|
|
|
|
const DefaultQueueName = "default"
|
|
|
|
|
2020-08-06 22:34:00 +08:00
|
|
|
// DefaultQueue is the redis key for the default queue.
|
2021-03-13 08:23:08 +08:00
|
|
|
var DefaultQueue = PendingKey(DefaultQueueName)
|
2020-08-06 22:34:00 +08:00
|
|
|
|
|
|
|
// Global Redis keys.
|
2019-12-22 23:15:45 +08:00
|
|
|
const (
|
2020-09-27 08:33:29 +08:00
|
|
|
AllServers = "asynq:servers" // ZSET
|
|
|
|
AllWorkers = "asynq:workers" // ZSET
|
|
|
|
AllSchedulers = "asynq:schedulers" // ZSET
|
|
|
|
AllQueues = "asynq:queues" // SET
|
|
|
|
CancelChannel = "asynq:cancel" // PubSub channel
|
2019-12-22 23:15:45 +08:00
|
|
|
)
|
|
|
|
|
2021-05-12 11:43:01 +08:00
|
|
|
// TaskState denotes the state of a task.
|
|
|
|
type TaskState int
|
|
|
|
|
|
|
|
const (
|
|
|
|
TaskStateActive TaskState = iota + 1
|
|
|
|
TaskStatePending
|
|
|
|
TaskStateScheduled
|
|
|
|
TaskStateRetry
|
|
|
|
TaskStateArchived
|
2021-11-06 07:52:54 +08:00
|
|
|
TaskStateCompleted
|
2021-05-12 11:43:01 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func (s TaskState) String() string {
|
|
|
|
switch s {
|
|
|
|
case TaskStateActive:
|
|
|
|
return "active"
|
|
|
|
case TaskStatePending:
|
|
|
|
return "pending"
|
|
|
|
case TaskStateScheduled:
|
|
|
|
return "scheduled"
|
|
|
|
case TaskStateRetry:
|
|
|
|
return "retry"
|
|
|
|
case TaskStateArchived:
|
|
|
|
return "archived"
|
2021-11-06 07:52:54 +08:00
|
|
|
case TaskStateCompleted:
|
|
|
|
return "completed"
|
2021-05-12 11:43:01 +08:00
|
|
|
}
|
|
|
|
panic(fmt.Sprintf("internal error: unknown task state %d", s))
|
|
|
|
}
|
|
|
|
|
2021-05-23 04:03:12 +08:00
|
|
|
func TaskStateFromString(s string) (TaskState, error) {
|
|
|
|
switch s {
|
|
|
|
case "active":
|
|
|
|
return TaskStateActive, nil
|
|
|
|
case "pending":
|
|
|
|
return TaskStatePending, nil
|
|
|
|
case "scheduled":
|
|
|
|
return TaskStateScheduled, nil
|
|
|
|
case "retry":
|
|
|
|
return TaskStateRetry, nil
|
|
|
|
case "archived":
|
|
|
|
return TaskStateArchived, nil
|
2021-11-06 07:52:54 +08:00
|
|
|
case "completed":
|
|
|
|
return TaskStateCompleted, nil
|
2021-05-23 04:03:12 +08:00
|
|
|
}
|
|
|
|
return 0, errors.E(errors.FailedPrecondition, fmt.Sprintf("%q is not supported task state", s))
|
|
|
|
}
|
|
|
|
|
2021-01-29 00:59:13 +08:00
|
|
|
// ValidateQueueName validates a given qname to be used as a queue name.
|
|
|
|
// Returns nil if valid, otherwise returns non-nil error.
|
|
|
|
func ValidateQueueName(qname string) error {
|
2021-07-15 21:12:13 +08:00
|
|
|
if len(strings.TrimSpace(qname)) == 0 {
|
2021-01-29 00:59:13 +08:00
|
|
|
return fmt.Errorf("queue name must contain one or more characters")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-04-28 22:27:35 +08:00
|
|
|
// QueueKeyPrefix returns a prefix for all keys in the given queue.
|
|
|
|
func QueueKeyPrefix(qname string) string {
|
|
|
|
return fmt.Sprintf("asynq:{%s}:", qname)
|
|
|
|
}
|
|
|
|
|
2021-03-13 08:23:08 +08:00
|
|
|
// TaskKeyPrefix returns a prefix for task key.
|
|
|
|
func TaskKeyPrefix(qname string) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%st:", QueueKeyPrefix(qname))
|
2021-03-13 08:23:08 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// TaskKey returns a redis key for the given task message.
|
|
|
|
func TaskKey(qname, id string) string {
|
|
|
|
return fmt.Sprintf("%s%s", TaskKeyPrefix(qname), id)
|
|
|
|
}
|
|
|
|
|
|
|
|
// PendingKey returns a redis key for the given queue name.
|
|
|
|
func PendingKey(qname string) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%spending", QueueKeyPrefix(qname))
|
2020-08-06 22:34:00 +08:00
|
|
|
}
|
|
|
|
|
2020-09-06 03:43:15 +08:00
|
|
|
// ActiveKey returns a redis key for the active tasks.
|
|
|
|
func ActiveKey(qname string) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%sactive", QueueKeyPrefix(qname))
|
2020-08-06 22:34:00 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// ScheduledKey returns a redis key for the scheduled tasks.
|
|
|
|
func ScheduledKey(qname string) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%sscheduled", QueueKeyPrefix(qname))
|
2020-08-06 22:34:00 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// RetryKey returns a redis key for the retry tasks.
|
|
|
|
func RetryKey(qname string) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%sretry", QueueKeyPrefix(qname))
|
2020-08-06 22:34:00 +08:00
|
|
|
}
|
|
|
|
|
2021-01-13 03:01:21 +08:00
|
|
|
// ArchivedKey returns a redis key for the archived tasks.
|
|
|
|
func ArchivedKey(qname string) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%sarchived", QueueKeyPrefix(qname))
|
2020-08-06 22:34:00 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// DeadlinesKey returns a redis key for the deadlines.
|
|
|
|
func DeadlinesKey(qname string) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%sdeadlines", QueueKeyPrefix(qname))
|
2020-08-06 22:34:00 +08:00
|
|
|
}
|
|
|
|
|
2022-02-08 21:53:42 +08:00
|
|
|
// LeaseKey returns a redis key for the lease.
|
|
|
|
func LeaseKey(qname string) string {
|
|
|
|
return fmt.Sprintf("%slease", QueueKeyPrefix(qname))
|
|
|
|
}
|
|
|
|
|
2021-11-06 07:52:54 +08:00
|
|
|
func CompletedKey(qname string) string {
|
|
|
|
return fmt.Sprintf("%scompleted", QueueKeyPrefix(qname))
|
|
|
|
}
|
|
|
|
|
2020-08-06 22:34:00 +08:00
|
|
|
// PausedKey returns a redis key to indicate that the given queue is paused.
|
|
|
|
func PausedKey(qname string) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%spaused", QueueKeyPrefix(qname))
|
2020-01-06 22:53:40 +08:00
|
|
|
}
|
|
|
|
|
2021-12-17 08:53:02 +08:00
|
|
|
// ProcessedTotalKey returns a redis key for total processed count for the given queue.
|
|
|
|
func ProcessedTotalKey(qname string) string {
|
|
|
|
return fmt.Sprintf("%sprocessed", QueueKeyPrefix(qname))
|
|
|
|
}
|
|
|
|
|
|
|
|
// FailedTotalKey returns a redis key for total failure count for the given queue.
|
|
|
|
func FailedTotalKey(qname string) string {
|
|
|
|
return fmt.Sprintf("%sfailed", QueueKeyPrefix(qname))
|
|
|
|
}
|
|
|
|
|
2020-08-06 22:34:00 +08:00
|
|
|
// ProcessedKey returns a redis key for processed count for the given day for the queue.
|
|
|
|
func ProcessedKey(qname string, t time.Time) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%sprocessed:%s", QueueKeyPrefix(qname), t.UTC().Format("2006-01-02"))
|
2019-12-23 21:33:48 +08:00
|
|
|
}
|
|
|
|
|
2020-08-06 22:34:00 +08:00
|
|
|
// FailedKey returns a redis key for failure count for the given day for the queue.
|
|
|
|
func FailedKey(qname string, t time.Time) string {
|
2021-04-28 22:27:35 +08:00
|
|
|
return fmt.Sprintf("%sfailed:%s", QueueKeyPrefix(qname), t.UTC().Format("2006-01-02"))
|
2019-12-23 21:33:48 +08:00
|
|
|
}
|
|
|
|
|
2020-04-13 07:42:11 +08:00
|
|
|
// ServerInfoKey returns a redis key for process info.
|
2020-09-27 08:33:29 +08:00
|
|
|
func ServerInfoKey(hostname string, pid int, serverID string) string {
|
|
|
|
return fmt.Sprintf("asynq:servers:{%s:%d:%s}", hostname, pid, serverID)
|
2020-01-31 22:48:58 +08:00
|
|
|
}
|
|
|
|
|
2020-04-13 07:42:11 +08:00
|
|
|
// WorkersKey returns a redis key for the workers given hostname, pid, and server ID.
|
2020-09-27 08:33:29 +08:00
|
|
|
func WorkersKey(hostname string, pid int, serverID string) string {
|
|
|
|
return fmt.Sprintf("asynq:workers:{%s:%d:%s}", hostname, pid, serverID)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SchedulerEntriesKey returns a redis key for the scheduler entries given scheduler ID.
|
|
|
|
func SchedulerEntriesKey(schedulerID string) string {
|
|
|
|
return fmt.Sprintf("asynq:schedulers:{%s}", schedulerID)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SchedulerHistoryKey returns a redis key for the scheduler's history for the given entry.
|
|
|
|
func SchedulerHistoryKey(entryID string) string {
|
|
|
|
return fmt.Sprintf("asynq:scheduler_history:%s", entryID)
|
2020-02-20 22:34:09 +08:00
|
|
|
}
|
|
|
|
|
2020-08-07 20:36:54 +08:00
|
|
|
// UniqueKey returns a redis key with the given type, payload, and queue name.
|
2021-03-21 04:42:13 +08:00
|
|
|
func UniqueKey(qname, tasktype string, payload []byte) string {
|
2021-06-09 21:46:21 +08:00
|
|
|
if payload == nil {
|
|
|
|
return fmt.Sprintf("%sunique:%s:", QueueKeyPrefix(qname), tasktype)
|
|
|
|
}
|
|
|
|
checksum := md5.Sum(payload)
|
|
|
|
return fmt.Sprintf("%sunique:%s:%s", QueueKeyPrefix(qname), tasktype, hex.EncodeToString(checksum[:]))
|
2020-08-07 20:36:54 +08:00
|
|
|
}
|
|
|
|
|
2019-12-22 23:15:45 +08:00
|
|
|
// TaskMessage is the internal representation of a task with additional metadata fields.
|
2019-12-28 12:37:15 +08:00
|
|
|
// Serialized data of this type gets written to redis.
|
2019-12-22 23:15:45 +08:00
|
|
|
type TaskMessage struct {
|
2019-12-28 12:37:15 +08:00
|
|
|
// Type indicates the kind of the task to be performed.
|
2019-12-22 23:15:45 +08:00
|
|
|
Type string
|
2019-12-28 12:37:15 +08:00
|
|
|
|
2019-12-22 23:15:45 +08:00
|
|
|
// Payload holds data needed to process the task.
|
2021-03-21 04:42:13 +08:00
|
|
|
Payload []byte
|
2019-12-22 23:15:45 +08:00
|
|
|
|
2019-12-28 12:37:15 +08:00
|
|
|
// ID is a unique identifier for each task.
|
2021-09-10 21:29:37 +08:00
|
|
|
ID string
|
2019-12-28 12:37:15 +08:00
|
|
|
|
|
|
|
// Queue is a name this message should be enqueued to.
|
2019-12-22 23:15:45 +08:00
|
|
|
Queue string
|
2019-12-28 12:37:15 +08:00
|
|
|
|
2019-12-22 23:15:45 +08:00
|
|
|
// Retry is the max number of retry for this task.
|
|
|
|
Retry int
|
2019-12-28 12:37:15 +08:00
|
|
|
|
|
|
|
// Retried is the number of times we've retried this task so far.
|
2019-12-22 23:15:45 +08:00
|
|
|
Retried int
|
2019-12-28 12:37:15 +08:00
|
|
|
|
|
|
|
// ErrorMsg holds the error message from the last failure.
|
2019-12-22 23:15:45 +08:00
|
|
|
ErrorMsg string
|
2020-02-12 13:53:59 +08:00
|
|
|
|
2021-05-19 11:50:00 +08:00
|
|
|
// Time of last failure in Unix time,
|
|
|
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
|
|
|
//
|
|
|
|
// Use zero to indicate no last failure
|
|
|
|
LastFailedAt int64
|
|
|
|
|
2020-06-17 12:11:54 +08:00
|
|
|
// Timeout specifies timeout in seconds.
|
|
|
|
// If task processing doesn't complete within the timeout, the task will be retried
|
2021-01-13 03:01:21 +08:00
|
|
|
// if retry count is remaining. Otherwise it will be moved to the archive.
|
2020-02-12 13:53:59 +08:00
|
|
|
//
|
2020-06-17 12:11:54 +08:00
|
|
|
// Use zero to indicate no timeout.
|
2020-06-22 23:33:58 +08:00
|
|
|
Timeout int64
|
2020-03-08 12:24:03 +08:00
|
|
|
|
2020-06-17 12:11:54 +08:00
|
|
|
// Deadline specifies the deadline for the task in Unix time,
|
|
|
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
|
|
|
// If task processing doesn't complete before the deadline, the task will be retried
|
2021-01-13 03:01:21 +08:00
|
|
|
// if retry count is remaining. Otherwise it will be moved to the archive.
|
2020-03-08 12:24:03 +08:00
|
|
|
//
|
2020-06-17 12:11:54 +08:00
|
|
|
// Use zero to indicate no deadline.
|
2020-06-22 23:33:58 +08:00
|
|
|
Deadline int64
|
2020-03-18 21:49:39 +08:00
|
|
|
|
|
|
|
// UniqueKey holds the redis key used for uniqueness lock for this task.
|
|
|
|
//
|
|
|
|
// Empty string indicates that no uniqueness lock was used.
|
|
|
|
UniqueKey string
|
2021-11-06 07:52:54 +08:00
|
|
|
|
|
|
|
// Retention specifies the number of seconds the task should be retained after completion.
|
|
|
|
Retention int64
|
|
|
|
|
|
|
|
// CompletedAt is the time the task was processed successfully in Unix time,
|
|
|
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
|
|
|
//
|
|
|
|
// Use zero to indicate no value.
|
|
|
|
CompletedAt int64
|
2019-12-22 23:15:45 +08:00
|
|
|
}
|
2020-01-31 22:48:58 +08:00
|
|
|
|
2021-03-13 08:23:08 +08:00
|
|
|
// EncodeMessage marshals the given task message and returns an encoded bytes.
|
|
|
|
func EncodeMessage(msg *TaskMessage) ([]byte, error) {
|
|
|
|
if msg == nil {
|
|
|
|
return nil, fmt.Errorf("cannot encode nil message")
|
|
|
|
}
|
|
|
|
return proto.Marshal(&pb.TaskMessage{
|
2021-05-19 11:50:00 +08:00
|
|
|
Type: msg.Type,
|
|
|
|
Payload: msg.Payload,
|
2021-09-10 21:29:37 +08:00
|
|
|
Id: msg.ID,
|
2021-05-19 11:50:00 +08:00
|
|
|
Queue: msg.Queue,
|
|
|
|
Retry: int32(msg.Retry),
|
|
|
|
Retried: int32(msg.Retried),
|
|
|
|
ErrorMsg: msg.ErrorMsg,
|
|
|
|
LastFailedAt: msg.LastFailedAt,
|
|
|
|
Timeout: msg.Timeout,
|
|
|
|
Deadline: msg.Deadline,
|
|
|
|
UniqueKey: msg.UniqueKey,
|
2021-11-06 07:52:54 +08:00
|
|
|
Retention: msg.Retention,
|
|
|
|
CompletedAt: msg.CompletedAt,
|
2021-03-13 08:23:08 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// DecodeMessage unmarshals the given bytes and returns a decoded task message.
|
|
|
|
func DecodeMessage(data []byte) (*TaskMessage, error) {
|
|
|
|
var pbmsg pb.TaskMessage
|
|
|
|
if err := proto.Unmarshal(data, &pbmsg); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &TaskMessage{
|
2021-05-19 11:50:00 +08:00
|
|
|
Type: pbmsg.GetType(),
|
|
|
|
Payload: pbmsg.GetPayload(),
|
2021-09-10 21:29:37 +08:00
|
|
|
ID: pbmsg.GetId(),
|
2021-05-19 11:50:00 +08:00
|
|
|
Queue: pbmsg.GetQueue(),
|
|
|
|
Retry: int(pbmsg.GetRetry()),
|
|
|
|
Retried: int(pbmsg.GetRetried()),
|
|
|
|
ErrorMsg: pbmsg.GetErrorMsg(),
|
|
|
|
LastFailedAt: pbmsg.GetLastFailedAt(),
|
|
|
|
Timeout: pbmsg.GetTimeout(),
|
|
|
|
Deadline: pbmsg.GetDeadline(),
|
|
|
|
UniqueKey: pbmsg.GetUniqueKey(),
|
2021-11-06 07:52:54 +08:00
|
|
|
Retention: pbmsg.GetRetention(),
|
|
|
|
CompletedAt: pbmsg.GetCompletedAt(),
|
2021-03-13 08:23:08 +08:00
|
|
|
}, nil
|
2020-06-12 11:58:27 +08:00
|
|
|
}
|
|
|
|
|
2021-05-23 04:03:12 +08:00
|
|
|
// TaskInfo describes a task message and its metadata.
|
|
|
|
type TaskInfo struct {
|
|
|
|
Message *TaskMessage
|
|
|
|
State TaskState
|
|
|
|
NextProcessAt time.Time
|
2021-11-06 07:52:54 +08:00
|
|
|
Result []byte
|
2021-05-23 04:03:12 +08:00
|
|
|
}
|
|
|
|
|
2020-07-13 21:29:41 +08:00
|
|
|
// Z represents sorted set member.
|
|
|
|
type Z struct {
|
|
|
|
Message *TaskMessage
|
|
|
|
Score int64
|
|
|
|
}
|
|
|
|
|
2020-04-13 07:42:11 +08:00
|
|
|
// ServerInfo holds information about a running server.
|
|
|
|
type ServerInfo struct {
|
2020-02-20 23:44:13 +08:00
|
|
|
Host string
|
|
|
|
PID int
|
2020-04-13 07:42:11 +08:00
|
|
|
ServerID string
|
2020-02-02 14:22:48 +08:00
|
|
|
Concurrency int
|
2020-02-13 14:23:25 +08:00
|
|
|
Queues map[string]int
|
2020-02-02 14:22:48 +08:00
|
|
|
StrictPriority bool
|
2020-02-18 22:57:39 +08:00
|
|
|
Status string
|
2020-02-02 14:22:48 +08:00
|
|
|
Started time.Time
|
|
|
|
ActiveWorkerCount int
|
|
|
|
}
|
|
|
|
|
2021-03-13 08:23:08 +08:00
|
|
|
// EncodeServerInfo marshals the given ServerInfo and returns the encoded bytes.
|
|
|
|
func EncodeServerInfo(info *ServerInfo) ([]byte, error) {
|
|
|
|
if info == nil {
|
|
|
|
return nil, fmt.Errorf("cannot encode nil server info")
|
|
|
|
}
|
|
|
|
queues := make(map[string]int32)
|
|
|
|
for q, p := range info.Queues {
|
|
|
|
queues[q] = int32(p)
|
|
|
|
}
|
|
|
|
started, err := ptypes.TimestampProto(info.Started)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return proto.Marshal(&pb.ServerInfo{
|
|
|
|
Host: info.Host,
|
|
|
|
Pid: int32(info.PID),
|
|
|
|
ServerId: info.ServerID,
|
|
|
|
Concurrency: int32(info.Concurrency),
|
|
|
|
Queues: queues,
|
|
|
|
StrictPriority: info.StrictPriority,
|
|
|
|
Status: info.Status,
|
|
|
|
StartTime: started,
|
|
|
|
ActiveWorkerCount: int32(info.ActiveWorkerCount),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// DecodeServerInfo decodes the given bytes into ServerInfo.
|
|
|
|
func DecodeServerInfo(b []byte) (*ServerInfo, error) {
|
|
|
|
var pbmsg pb.ServerInfo
|
|
|
|
if err := proto.Unmarshal(b, &pbmsg); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
queues := make(map[string]int)
|
|
|
|
for q, p := range pbmsg.GetQueues() {
|
|
|
|
queues[q] = int(p)
|
|
|
|
}
|
|
|
|
startTime, err := ptypes.Timestamp(pbmsg.GetStartTime())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &ServerInfo{
|
|
|
|
Host: pbmsg.GetHost(),
|
|
|
|
PID: int(pbmsg.GetPid()),
|
|
|
|
ServerID: pbmsg.GetServerId(),
|
|
|
|
Concurrency: int(pbmsg.GetConcurrency()),
|
|
|
|
Queues: queues,
|
|
|
|
StrictPriority: pbmsg.GetStrictPriority(),
|
|
|
|
Status: pbmsg.GetStatus(),
|
|
|
|
Started: startTime,
|
|
|
|
ActiveWorkerCount: int(pbmsg.GetActiveWorkerCount()),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2020-02-20 23:44:13 +08:00
|
|
|
// WorkerInfo holds information about a running worker.
|
|
|
|
type WorkerInfo struct {
|
2020-12-30 23:10:53 +08:00
|
|
|
Host string
|
|
|
|
PID int
|
|
|
|
ServerID string
|
|
|
|
ID string
|
|
|
|
Type string
|
2021-03-21 04:42:13 +08:00
|
|
|
Payload []byte
|
2021-03-13 08:23:08 +08:00
|
|
|
Queue string
|
2020-12-30 23:10:53 +08:00
|
|
|
Started time.Time
|
2021-01-28 07:55:43 +08:00
|
|
|
Deadline time.Time
|
2020-02-20 23:44:13 +08:00
|
|
|
}
|
|
|
|
|
2021-03-13 08:23:08 +08:00
|
|
|
// EncodeWorkerInfo marshals the given WorkerInfo and returns the encoded bytes.
|
|
|
|
func EncodeWorkerInfo(info *WorkerInfo) ([]byte, error) {
|
|
|
|
if info == nil {
|
|
|
|
return nil, fmt.Errorf("cannot encode nil worker info")
|
|
|
|
}
|
|
|
|
startTime, err := ptypes.TimestampProto(info.Started)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
deadline, err := ptypes.TimestampProto(info.Deadline)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return proto.Marshal(&pb.WorkerInfo{
|
|
|
|
Host: info.Host,
|
|
|
|
Pid: int32(info.PID),
|
|
|
|
ServerId: info.ServerID,
|
|
|
|
TaskId: info.ID,
|
|
|
|
TaskType: info.Type,
|
2021-03-21 04:42:13 +08:00
|
|
|
TaskPayload: info.Payload,
|
2021-03-13 08:23:08 +08:00
|
|
|
Queue: info.Queue,
|
|
|
|
StartTime: startTime,
|
|
|
|
Deadline: deadline,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// DecodeWorkerInfo decodes the given bytes into WorkerInfo.
|
|
|
|
func DecodeWorkerInfo(b []byte) (*WorkerInfo, error) {
|
|
|
|
var pbmsg pb.WorkerInfo
|
|
|
|
if err := proto.Unmarshal(b, &pbmsg); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
startTime, err := ptypes.Timestamp(pbmsg.GetStartTime())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
deadline, err := ptypes.Timestamp(pbmsg.GetDeadline())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &WorkerInfo{
|
|
|
|
Host: pbmsg.GetHost(),
|
|
|
|
PID: int(pbmsg.GetPid()),
|
|
|
|
ServerID: pbmsg.GetServerId(),
|
|
|
|
ID: pbmsg.GetTaskId(),
|
|
|
|
Type: pbmsg.GetTaskType(),
|
2021-03-21 04:42:13 +08:00
|
|
|
Payload: pbmsg.GetTaskPayload(),
|
2021-03-13 08:23:08 +08:00
|
|
|
Queue: pbmsg.GetQueue(),
|
|
|
|
Started: startTime,
|
|
|
|
Deadline: deadline,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2020-09-27 08:33:29 +08:00
|
|
|
// SchedulerEntry holds information about a periodic task registered with a scheduler.
|
|
|
|
type SchedulerEntry struct {
|
|
|
|
// Identifier of this entry.
|
|
|
|
ID string
|
|
|
|
|
|
|
|
// Spec describes the schedule of this entry.
|
|
|
|
Spec string
|
|
|
|
|
|
|
|
// Type is the task type of the periodic task.
|
|
|
|
Type string
|
|
|
|
|
|
|
|
// Payload is the payload of the periodic task.
|
2021-03-21 04:42:13 +08:00
|
|
|
Payload []byte
|
2020-09-27 08:33:29 +08:00
|
|
|
|
|
|
|
// Opts is the options for the periodic task.
|
2020-10-10 21:46:47 +08:00
|
|
|
Opts []string
|
2020-09-27 08:33:29 +08:00
|
|
|
|
|
|
|
// Next shows the next time the task will be enqueued.
|
|
|
|
Next time.Time
|
|
|
|
|
2020-12-01 23:37:09 +08:00
|
|
|
// Prev shows the last time the task was enqueued.
|
2020-09-27 08:33:29 +08:00
|
|
|
// Zero time if task was never enqueued.
|
|
|
|
Prev time.Time
|
|
|
|
}
|
|
|
|
|
2021-03-13 08:23:08 +08:00
|
|
|
// EncodeSchedulerEntry marshals the given entry and returns an encoded bytes.
|
|
|
|
func EncodeSchedulerEntry(entry *SchedulerEntry) ([]byte, error) {
|
|
|
|
if entry == nil {
|
|
|
|
return nil, fmt.Errorf("cannot encode nil scheduler entry")
|
|
|
|
}
|
|
|
|
next, err := ptypes.TimestampProto(entry.Next)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
prev, err := ptypes.TimestampProto(entry.Prev)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return proto.Marshal(&pb.SchedulerEntry{
|
|
|
|
Id: entry.ID,
|
|
|
|
Spec: entry.Spec,
|
|
|
|
TaskType: entry.Type,
|
2021-03-21 04:42:13 +08:00
|
|
|
TaskPayload: entry.Payload,
|
2021-03-13 08:23:08 +08:00
|
|
|
EnqueueOptions: entry.Opts,
|
|
|
|
NextEnqueueTime: next,
|
|
|
|
PrevEnqueueTime: prev,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// DecodeSchedulerEntry unmarshals the given bytes and returns a decoded SchedulerEntry.
|
|
|
|
func DecodeSchedulerEntry(b []byte) (*SchedulerEntry, error) {
|
|
|
|
var pbmsg pb.SchedulerEntry
|
|
|
|
if err := proto.Unmarshal(b, &pbmsg); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
next, err := ptypes.Timestamp(pbmsg.GetNextEnqueueTime())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
prev, err := ptypes.Timestamp(pbmsg.GetPrevEnqueueTime())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &SchedulerEntry{
|
|
|
|
ID: pbmsg.GetId(),
|
|
|
|
Spec: pbmsg.GetSpec(),
|
|
|
|
Type: pbmsg.GetTaskType(),
|
2021-03-21 04:42:13 +08:00
|
|
|
Payload: pbmsg.GetTaskPayload(),
|
2021-03-13 08:23:08 +08:00
|
|
|
Opts: pbmsg.GetEnqueueOptions(),
|
|
|
|
Next: next,
|
|
|
|
Prev: prev,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2020-09-27 08:33:29 +08:00
|
|
|
// SchedulerEnqueueEvent holds information about an enqueue event by a scheduler.
|
|
|
|
type SchedulerEnqueueEvent struct {
|
|
|
|
// ID of the task that was enqueued.
|
|
|
|
TaskID string
|
|
|
|
|
|
|
|
// Time the task was enqueued.
|
|
|
|
EnqueuedAt time.Time
|
|
|
|
}
|
|
|
|
|
2021-03-13 08:23:08 +08:00
|
|
|
// EncodeSchedulerEnqueueEvent marshals the given event
|
|
|
|
// and returns an encoded bytes.
|
|
|
|
func EncodeSchedulerEnqueueEvent(event *SchedulerEnqueueEvent) ([]byte, error) {
|
|
|
|
if event == nil {
|
|
|
|
return nil, fmt.Errorf("cannot encode nil enqueue event")
|
|
|
|
}
|
|
|
|
enqueuedAt, err := ptypes.TimestampProto(event.EnqueuedAt)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return proto.Marshal(&pb.SchedulerEnqueueEvent{
|
|
|
|
TaskId: event.TaskID,
|
|
|
|
EnqueueTime: enqueuedAt,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// DecodeSchedulerEnqueueEvent unmarshals the given bytes
|
|
|
|
// and returns a decoded SchedulerEnqueueEvent.
|
|
|
|
func DecodeSchedulerEnqueueEvent(b []byte) (*SchedulerEnqueueEvent, error) {
|
|
|
|
var pbmsg pb.SchedulerEnqueueEvent
|
|
|
|
if err := proto.Unmarshal(b, &pbmsg); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
enqueuedAt, err := ptypes.Timestamp(pbmsg.GetEnqueueTime())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &SchedulerEnqueueEvent{
|
|
|
|
TaskID: pbmsg.GetTaskId(),
|
|
|
|
EnqueuedAt: enqueuedAt,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2020-09-06 03:43:15 +08:00
|
|
|
// Cancelations is a collection that holds cancel functions for all active tasks.
|
2020-02-13 09:12:09 +08:00
|
|
|
//
|
2020-02-18 22:57:39 +08:00
|
|
|
// Cancelations are safe for concurrent use by multipel goroutines.
|
2020-02-13 09:12:09 +08:00
|
|
|
type Cancelations struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
cancelFuncs map[string]context.CancelFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewCancelations returns a Cancelations instance.
|
|
|
|
func NewCancelations() *Cancelations {
|
|
|
|
return &Cancelations{
|
|
|
|
cancelFuncs: make(map[string]context.CancelFunc),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-13 09:33:41 +08:00
|
|
|
// Add adds a new cancel func to the collection.
|
2020-02-13 09:12:09 +08:00
|
|
|
func (c *Cancelations) Add(id string, fn context.CancelFunc) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
c.cancelFuncs[id] = fn
|
|
|
|
}
|
|
|
|
|
2020-02-13 09:33:41 +08:00
|
|
|
// Delete deletes a cancel func from the collection given an id.
|
2020-02-13 09:12:09 +08:00
|
|
|
func (c *Cancelations) Delete(id string) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
delete(c.cancelFuncs, id)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns a cancel func given an id.
|
2020-02-20 23:44:13 +08:00
|
|
|
func (c *Cancelations) Get(id string) (fn context.CancelFunc, ok bool) {
|
2020-02-13 09:12:09 +08:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
2020-02-20 23:44:13 +08:00
|
|
|
fn, ok = c.cancelFuncs[id]
|
|
|
|
return fn, ok
|
2020-02-13 09:12:09 +08:00
|
|
|
}
|
|
|
|
|
2022-02-14 06:06:26 +08:00
|
|
|
// Lease is a time bound lease for worker to process task.
|
|
|
|
// It provides a communication channel between lessor and lessee about lease expiration.
|
|
|
|
type Lease struct {
|
|
|
|
once sync.Once
|
|
|
|
ch chan struct{}
|
|
|
|
|
|
|
|
clock timeutil.Clock
|
|
|
|
|
|
|
|
mu sync.Mutex
|
|
|
|
expireAt time.Time // guarded by mu
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewLease(expirationTime time.Time) *Lease {
|
|
|
|
return &Lease{
|
|
|
|
ch: make(chan struct{}),
|
|
|
|
expireAt: expirationTime,
|
|
|
|
clock: timeutil.NewRealClock(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reset chanegs the lease to expire at the given time.
|
|
|
|
// It returns true if the lease is still valid and reset operation was successful, false if the lease had been expired.
|
|
|
|
func (l *Lease) Reset(expirationTime time.Time) bool {
|
|
|
|
if !l.IsValid() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
l.mu.Lock()
|
|
|
|
defer l.mu.Unlock()
|
|
|
|
l.expireAt = expirationTime
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sends a notification to lessee about expired lease
|
|
|
|
// Returns true if notification was sent, returns false if the lease is still valid and notification was not sent.
|
|
|
|
func (l *Lease) NotifyExpiration() bool {
|
|
|
|
if l.IsValid() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
l.once.Do(l.closeCh)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *Lease) closeCh() {
|
|
|
|
close(l.ch)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Done returns a communication channel from which the lessee can read to get notified when lessor notifies about lease expiration.
|
|
|
|
func (l *Lease) Done() <-chan struct{} {
|
|
|
|
return l.ch
|
|
|
|
}
|
|
|
|
|
|
|
|
// Deadline returns the expiration time of the lease.
|
|
|
|
func (l *Lease) Deadline() time.Time {
|
|
|
|
l.mu.Lock()
|
|
|
|
defer l.mu.Unlock()
|
|
|
|
return l.expireAt
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsValid returns true if the lease's expieration time is in the future or equals to the current time,
|
|
|
|
// returns false otherwise.
|
|
|
|
func (l *Lease) IsValid() bool {
|
|
|
|
now := l.clock.Now()
|
|
|
|
l.mu.Lock()
|
|
|
|
defer l.mu.Unlock()
|
|
|
|
return l.expireAt.After(now) || l.expireAt.Equal(now)
|
|
|
|
}
|
|
|
|
|
2020-04-18 22:55:10 +08:00
|
|
|
// Broker is a message broker that supports operations to manage task queues.
|
|
|
|
//
|
|
|
|
// See rdb.RDB as a reference implementation.
|
|
|
|
type Broker interface {
|
2020-07-26 09:49:27 +08:00
|
|
|
Ping() error
|
2021-11-16 08:34:26 +08:00
|
|
|
Enqueue(ctx context.Context, msg *TaskMessage) error
|
|
|
|
EnqueueUnique(ctx context.Context, msg *TaskMessage, ttl time.Duration) error
|
2022-02-14 06:06:26 +08:00
|
|
|
Dequeue(qnames ...string) (*TaskMessage, time.Time, error)
|
2022-02-14 06:34:38 +08:00
|
|
|
Done(ctx context.Context, msg *TaskMessage) error
|
|
|
|
MarkAsComplete(ctx context.Context, msg *TaskMessage) error
|
|
|
|
Requeue(ctx context.Context, msg *TaskMessage) error
|
2021-11-16 08:34:26 +08:00
|
|
|
Schedule(ctx context.Context, msg *TaskMessage, processAt time.Time) error
|
|
|
|
ScheduleUnique(ctx context.Context, msg *TaskMessage, processAt time.Time, ttl time.Duration) error
|
2022-02-14 06:34:38 +08:00
|
|
|
Retry(ctx context.Context, msg *TaskMessage, processAt time.Time, errMsg string, isFailure bool) error
|
|
|
|
Archive(ctx context.Context, msg *TaskMessage, errMsg string) error
|
2021-03-13 08:23:08 +08:00
|
|
|
ForwardIfReady(qnames ...string) error
|
2021-11-06 07:52:54 +08:00
|
|
|
DeleteExpiredCompletedTasks(qname string) error
|
2022-02-11 22:18:27 +08:00
|
|
|
ListLeaseExpired(cutoff time.Time, qnames ...string) ([]*TaskMessage, error)
|
2022-02-14 06:06:26 +08:00
|
|
|
ExtendLease(qname string, ids ...string) (time.Time, error)
|
2020-05-19 11:47:35 +08:00
|
|
|
WriteServerState(info *ServerInfo, workers []*WorkerInfo, ttl time.Duration) error
|
|
|
|
ClearServerState(host string, pid int, serverID string) error
|
2020-04-18 22:55:10 +08:00
|
|
|
CancelationPubSub() (*redis.PubSub, error) // TODO: Need to decouple from redis to support other brokers
|
|
|
|
PublishCancelation(id string) error
|
2021-11-06 07:52:54 +08:00
|
|
|
WriteResult(qname, id string, data []byte) (n int, err error)
|
2020-04-18 22:55:10 +08:00
|
|
|
Close() error
|
|
|
|
}
|