-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassembler.go
74 lines (64 loc) · 1.92 KB
/
assembler.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
package gta
import (
"context"
"encoding/json"
"fmt"
"reflect"
)
type taskAssembler interface {
AssembleTask(ctxIn context.Context, taskDef *TaskDefinition, arg interface{}) (*Task, error)
DisassembleTask(taskDef *TaskDefinition, task *Task) (context.Context, interface{}, error)
}
type taskAssemblerImp struct {
*options
}
func (s *taskAssemblerImp) AssembleTask(ctxIn context.Context, taskDef *TaskDefinition, arg interface{}) (*Task, error) {
// check if arg is valid
if argTExpected := taskDef.ArgType; argTExpected != nil {
argVActual := reflect.ValueOf(arg)
if argVActual.IsValid() && argVActual.Type() != argTExpected {
return nil, fmt.Errorf("arg type mismatch: %s expected, %T passed in", argTExpected, arg)
}
}
task := &Task{
ID: taskDef.taskID,
TaskKey: taskDef.key,
TaskStatus: TaskStatusUnKnown,
}
if arg != nil {
argBytes, err := json.Marshal(arg)
if err != nil {
return nil, fmt.Errorf("get argBytes failed, err: %w", err)
}
task.Argument = argBytes
}
if ctxIn != nil {
ctxBytes, err := taskDef.ctxMarshaler(s.ctxMarshaler).MarshalCtx(ctxIn)
if err != nil {
return nil, fmt.Errorf("get ctxBytes failed, err: %w", err)
}
task.Context = ctxBytes
}
return task, nil
}
func (s *taskAssemblerImp) DisassembleTask(taskDef *TaskDefinition, task *Task) (context.Context, interface{}, error) {
ctxIn, err := taskDef.ctxMarshaler(s.ctxMarshaler).UnmarshalCtx(task.Context)
if err != nil {
return nil, nil, fmt.Errorf("unmarshal task context error: %w", err)
}
var argument interface{}
if task.Argument != nil {
var argP interface{}
if t := taskDef.ArgType; t != nil {
argP = reflect.New(t).Interface()
} else {
var argI interface{}
argP = &argI
}
if err := json.Unmarshal(task.Argument, argP); err != nil {
return nil, nil, fmt.Errorf("unmarshal arg error: %w", err)
}
argument = reflect.ValueOf(argP).Elem().Interface()
}
return ctxIn, argument, nil
}