-
Notifications
You must be signed in to change notification settings - Fork 1
/
task.go
136 lines (108 loc) · 2.43 KB
/
task.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
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
package queue
import (
"fmt"
"reflect"
"sync"
"time"
"github.com/ibllex/go-encoding"
"github.com/ibllex/go-queue/internal"
"github.com/ibllex/go-queue/internal/logger"
)
var (
Tasks TaskMap
taskCodec = encoding.NewMsgPackCodec(nil)
)
type Task interface {
Handle() error
}
type innerTask struct {
Name string
Data []byte
}
//
// Task registration management
//
type TaskMap struct {
tasks sync.Map
}
func (t *TaskMap) Register(value interface{}) {
t.RegisterName(internal.NameOf(value), value)
}
func (t *TaskMap) RegisterName(name string, value interface{}) {
if name == "" {
// reserved for nil
panic("attempt to register empty name")
}
if _, ok := value.(Task); !ok {
panic(fmt.Sprintf("%v is not a valid task type", value))
}
t.tasks.LoadOrStore(name, reflect.TypeOf(value))
}
func (t *TaskMap) Get(name string) interface{} {
if v, ok := t.tasks.Load(name); ok {
if tt, ok := v.(reflect.Type); ok {
return reflect.New(tt.Elem()).Interface()
}
}
return nil
}
//
// External Interface
//
func RegisterTask(value interface{}) {
Tasks.Register(value)
}
func RegisterTaskName(name string, value interface{}) {
Tasks.RegisterName(name, value)
}
// Distribute all tasks
func TaskHandler() HandlerFunc {
return func(m Message) {
defer logger.LogIfError(m.Ack())
var wrapper innerTask
if err := m.Unmarshal(&wrapper); err != nil {
logger.Error(err)
return
}
if task := Tasks.Get(wrapper.Name); task != nil {
err := taskCodec.Unmarshal(wrapper.Data, task)
if err != nil {
logger.Error(err)
return
}
if handler, ok := task.(Task); ok {
logger.LogIfError(handler.Handle())
}
} else {
logger.Errorf("unsupport task type: %s", wrapper.Name)
}
}
}
//
// Dispatcher for task
//
func DispatchTask(task interface{}) error {
return DispatchTaskName(internal.NameOf(task), task)
}
func DispatchTaskName(name string, task interface{}) error {
if _, ok := task.(Task); !ok {
return fmt.Errorf("%v is not a valid task type", task)
}
tv := reflect.ValueOf(task)
opt := &DispatchOption{}
if m := tv.MethodByName("OnQueue"); m.IsValid() {
if f, ok := m.Interface().(func() string); ok {
opt.Queue = f()
}
}
if m := tv.MethodByName("Delay"); m.IsValid() {
if f, ok := m.Interface().(func() time.Duration); ok {
opt.Delay = f()
}
}
byts, err := taskCodec.Marshal(task)
if err != nil {
return err
}
return Dispatch(opt, &innerTask{Name: name, Data: byts})
}