-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjob.go
More file actions
200 lines (165 loc) · 6.1 KB
/
job.go
File metadata and controls
200 lines (165 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package queue
import (
"crypto/md5" //nolint:gosec
"errors"
"fmt"
"time"
"github.com/go-json-experiment/json"
"github.com/hibiken/asynq"
)
// Job represents a task that will be executed by a worker.
type Job struct {
ID string `json:"id"` // Unique identifier for the job.
Fingerprint string `json:"fingerprint"` // Unique hash for the job based on its type and payload.
Type string `json:"type"` // Type of job, used for handler mapping.
Payload any `json:"payload"` // Job data.
resultWriter *asynq.ResultWriter `json:"-"` // Result writer for the job.
Options JobOptions `json:"options"` // Execution options for the job.
}
// JobOptions encapsulates settings that control job execution.
type JobOptions struct {
MaxRetries int `json:"max_retries"` // Maximum number of retries.
Queue string `json:"queue"` // Queue name to which the job is dispatched.
Delay time.Duration `json:"delay"` // Initial delay before processing the job.
ScheduleAt *time.Time `json:"schedule_at"` // Specific time at which the job should be processed.
Deadline *time.Time `json:"deadline"` // Time by which the job must complete.
Retention time.Duration `json:"retention"` // Duration to retain the job data after completion.
}
// NewJob initializes a new Job with the provided type, payload, and configuration options.
func NewJob(jobType string, payload any, opts ...JobOption) *Job {
job := &Job{
Type: jobType,
Payload: payload,
Options: JobOptions{Queue: DefaultQueue}, // Use a default queue unless overridden.
}
// Apply provided configuration options to the job.
for _, opt := range opts {
opt(job)
}
job.fingerprint() // Generate a unique fingerprint for the job.
return job
}
// WithOptions dynamically updates the job's options.
func (j *Job) WithOptions(opts ...JobOption) {
for _, opt := range opts {
opt(j)
}
}
// JobOption defines a function signature for job configuration options.
type JobOption func(*Job)
// WithDelay sets the initial delay before the job is processed.
func WithDelay(delay time.Duration) JobOption {
return func(j *Job) { j.Options.Delay = delay }
}
// WithMaxRetries sets the maximum number of retry attempts for the job.
func WithMaxRetries(maxRetries int) JobOption {
return func(j *Job) { j.Options.MaxRetries = maxRetries }
}
// WithQueue sets the queue name to which the job is dispatched.
func WithQueue(queue string) JobOption {
return func(j *Job) { j.Options.Queue = queue }
}
// WithScheduleAt sets a specific time at which the job should be processed.
func WithScheduleAt(scheduleAt *time.Time) JobOption {
return func(j *Job) { j.Options.ScheduleAt = scheduleAt }
}
// WithRetention sets the duration to retain the job data after completion.
func WithRetention(retention time.Duration) JobOption {
return func(j *Job) { j.Options.Retention = retention }
}
// WithDeadline sets the time by which the job must complete.
func WithDeadline(deadline *time.Time) JobOption {
return func(j *Job) { j.Options.Deadline = deadline }
}
// ConvertToAsynqTask converts the Job into an asynq.Task, ready for enqueueing.
func (j *Job) ConvertToAsynqTask() (*asynq.Task, []asynq.Option, error) {
if j.Type == "" {
return nil, nil, ErrNoJobTypeSpecified
}
if j.Options.Queue == "" {
return nil, nil, ErrNoJobQueueSpecified
}
payloadBytes, err := json.Marshal(j.Payload)
if err != nil {
return nil, nil, fmt.Errorf("failed to serialize payload: %w", errors.Join(ErrSerializationFailure, err))
}
opts := j.ConvertToAsynqOptions()
return asynq.NewTask(j.Type, payloadBytes), opts, nil
}
// ConvertToAsynqOptions converts the Job's options into asynq.Option slice.
func (j *Job) ConvertToAsynqOptions() []asynq.Option {
opts := make([]asynq.Option, 0, 6)
if j.Options.Queue != "" {
opts = append(opts, asynq.Queue(j.Options.Queue))
}
if j.Options.Delay > 0 {
opts = append(opts, asynq.ProcessIn(j.Options.Delay))
}
if j.Options.ScheduleAt != nil && !j.Options.ScheduleAt.IsZero() {
opts = append(opts, asynq.ProcessAt(*j.Options.ScheduleAt))
}
if j.Options.MaxRetries > 0 {
opts = append(opts, asynq.MaxRetry(j.Options.MaxRetries))
}
if j.Options.Deadline != nil && !j.Options.Deadline.IsZero() {
opts = append(opts, asynq.Deadline(*j.Options.Deadline))
}
if j.Options.Retention > 0 {
opts = append(opts, asynq.Retention(j.Options.Retention))
}
return opts
}
// fingerprint generates a unique hash for the job based on its type and payload.
func (j *Job) fingerprint() {
if j.Fingerprint != "" {
return
}
hash := md5.New() //nolint:gosec
hash.Write([]byte(j.Type))
payloadBytes, _ := json.Marshal(j.Payload)
hash.Write(payloadBytes)
optionsBytes, _ := json.Marshal(j.Options)
hash.Write(optionsBytes)
j.Fingerprint = fmt.Sprintf("%x", hash.Sum(nil))
}
// DecodePayload decodes the job payload into a given struct.
func (j *Job) DecodePayload(v any) error {
payloadBytes, err := json.Marshal(j.Payload)
if err != nil {
return fmt.Errorf("failed to serialize payload: %w", errors.Join(ErrSerializationFailure, err))
}
return json.Unmarshal(payloadBytes, v)
}
// SetID sets the job's unique identifier.
func (j *Job) SetID(id string) *Job {
j.ID = id
return j
}
// SetResultWriter sets the result writer for the job.
func (j *Job) SetResultWriter(rw *asynq.ResultWriter) *Job {
j.resultWriter = rw
return j
}
// WriteResult writes the result of the job to the result writer.
func (j *Job) WriteResult(result any) error {
if j.resultWriter == nil {
return ErrResultWriterNotSet
}
resultBytes, err := json.Marshal(result)
if err != nil {
return fmt.Errorf("failed to serialize result: %w", err)
}
if _, err = j.resultWriter.Write(resultBytes); err != nil {
return fmt.Errorf("failed to write result: %w", err)
}
return nil
}
// NewJobFromAsynqTask creates a Job from an existing asynq.Task.
// The returned Job contains the task's type and raw payload bytes.
func NewJobFromAsynqTask(task *asynq.Task) (*Job, error) {
job := &Job{
Type: task.Type(),
Payload: task.Payload(),
}
return job, nil
}