-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuilder.go
70 lines (63 loc) · 1.54 KB
/
builder.go
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
package iocast
import (
"time"
)
type taskBuilder[T any] struct {
id string
taskFn TaskFn[T]
resultChan chan Result[T]
next *Task[T]
maxRetries int
backoff []time.Duration
db DB
metadata Metadata
}
// TaskBuilder creates and returns a new TaskBuilder instance.
func TaskBuilder[T any](id string, fn TaskFn[T]) *taskBuilder[T] {
t := &taskBuilder[T]{
id: id,
taskFn: fn,
resultChan: make(chan Result[T], 1),
maxRetries: 1,
metadata: Metadata{
CreatetAt: time.Now().UTC(),
Status: TaskStatusPending,
},
}
return t
}
// MaxRetries passes a number of max retries to the task builder.
func (b *taskBuilder[T]) MaxRetries(maxRetries int) *taskBuilder[T] {
if maxRetries < 1 {
maxRetries = 1
}
b.maxRetries = maxRetries
return b
}
// BackOff passes backoff intervals between retires to the task builder.
func (b *taskBuilder[T]) BackOff(backoff []time.Duration) *taskBuilder[T] {
if len(backoff) > b.maxRetries {
b.backoff = backoff[:b.maxRetries]
} else if len(backoff) == b.maxRetries {
b.backoff = backoff
}
return b
}
// Database passes a database implementation to the task builder.
func (b *taskBuilder[T]) Database(db DB) *taskBuilder[T] {
b.db = db
return b
}
// Build initializes and returns a new task instance.
func (b *taskBuilder[T]) Build() *Task[T] {
return &Task[T]{
id: b.id,
taskFn: b.taskFn,
resultChan: b.resultChan,
maxRetries: b.maxRetries,
backoff: b.backoff,
next: b.next,
db: b.db,
metadata: b.metadata,
}
}