-
Notifications
You must be signed in to change notification settings - Fork 1
/
activity.go
192 lines (163 loc) · 6.87 KB
/
activity.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
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
package tempts
import (
"context"
"fmt"
"reflect"
"go.temporal.io/sdk/activity"
"go.temporal.io/sdk/worker"
"go.temporal.io/sdk/workflow"
)
// ActivityWithImpl is a temporary struct that implements Registerable. It's meant to be passed into `tempts.NewWorker`.
type ActivityWithImpl struct {
activityName string
queue *Queue
fn any
}
func (a ActivityWithImpl) register(ar worker.Registry) {
ar.RegisterActivityWithOptions(a.fn, activity.RegisterOptions{Name: a.activityName})
}
func (a ActivityWithImpl) validate(q *Queue, v *validationState) error {
if a.queue.name != q.name {
return fmt.Errorf("activity for queue %s can't be registered on worker with queue %s", a.queue.name, q.name)
}
_, ok := v.activitiesValidated[a.activityName]
if ok {
return fmt.Errorf("duplicate activtity name %s for queue %s", a.activityName, q.name)
}
v.activitiesValidated[a.activityName] = struct{}{}
return nil
}
// Activity is used for interacting with activities in a safe way that takes into account the input and output types, queue name and other properties.
type Activity[Param, Return any] struct {
Name string
queue *Queue
// If true, the Param struct fields will be passed as positional arguments
positional bool
}
// NewActivity declares the existence of an activity on a given queue with a given name.
func NewActivity[Param, Return any](q *Queue, name string) Activity[Param, Return] {
panicIfNotStruct[Param]("NewActivity")
q.registerActivity(name, func(ctx context.Context, param Param) (Return, error) {
panic(fmt.Sprintf("Activity %s execution not mocked", name))
})
return Activity[Param, Return]{Name: name, queue: q}
}
// NewActivityPositional declares the existence of an activity on a given queue with a given name.
// Instead of passing the Param struct directly to the activity, it passes each field of the struct
// as a separate positional argument in the order they are defined.
func NewActivityPositional[Param, Return any](q *Queue, name string) Activity[Param, Return] {
panicIfNotStruct[Param]("NewActivityPositional")
// Get the type information for the Param struct
paramType := reflect.TypeOf((*Param)(nil)).Elem()
if paramType.Kind() == reflect.Ptr {
paramType = paramType.Elem()
}
// Create a slice of function parameter types: (context.Context, field1Type, field2Type, ...)
paramTypes := make([]reflect.Type, paramType.NumField()+1)
paramTypes[0] = reflect.TypeOf((*context.Context)(nil)).Elem()
for i := 0; i < paramType.NumField(); i++ {
paramTypes[i+1] = paramType.Field(i).Type
}
// Create the function type: func(context.Context, field1Type, field2Type, ...) (Return, error)
returnType := reflect.TypeOf((*Return)(nil)).Elem()
errorType := reflect.TypeOf((*error)(nil)).Elem()
fnType := reflect.FuncOf(paramTypes, []reflect.Type{returnType, errorType}, false)
// Create a function that panics with the message "Function execution not mocked"
mockFn := reflect.MakeFunc(fnType, func(args []reflect.Value) []reflect.Value {
panic(fmt.Sprintf("Activity %s execution not mocked", name))
})
// Register the mock function
q.registerActivity(name, mockFn.Interface())
return Activity[Param, Return]{Name: name, queue: q, positional: true}
}
func panicIfNotStruct[Param any](funcName string) {
paramType := reflect.TypeOf((*Param)(nil)).Elem()
if paramType.Kind() == reflect.Ptr {
paramType = paramType.Elem()
}
if paramType.Kind() != reflect.Struct {
panic(fmt.Sprintf("%s requires a struct or pointer to struct type parameter, got %v", funcName, paramType.Kind()))
}
}
func extractFieldTypes(structType reflect.Type) []reflect.Type {
if structType.Kind() == reflect.Ptr {
structType = structType.Elem()
}
if structType.Kind() != reflect.Struct {
panic("extractFieldTypes called with non-struct type")
}
fieldTypes := make([]reflect.Type, structType.NumField())
for i := 0; i < structType.NumField(); i++ {
fieldTypes[i] = structType.Field(i).Type
}
return fieldTypes
}
// WithImplementation should be called to create the parameters for NewWorker(). It declares which function implements the activity.
func (a Activity[Param, Return]) WithImplementation(fn func(context.Context, Param) (Return, error)) *ActivityWithImpl {
if !a.positional {
return &ActivityWithImpl{activityName: a.Name, queue: a.queue, fn: fn}
}
// For positional activities, create a wrapper function that converts positional arguments to a struct
paramType := reflect.TypeOf((*Param)(nil)).Elem()
var fieldTypes []reflect.Type
if paramType.Kind() == reflect.Ptr {
fieldTypes = extractFieldTypes(paramType.Elem())
} else {
fieldTypes = extractFieldTypes(paramType)
}
wrapper := reflect.MakeFunc(
reflect.FuncOf(
append([]reflect.Type{reflect.TypeOf((*context.Context)(nil)).Elem()}, fieldTypes...),
[]reflect.Type{reflect.TypeOf((*Return)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()},
false,
),
func(args []reflect.Value) []reflect.Value {
ctx := args[0]
// Create a new instance of the Param struct
var paramVal reflect.Value
if paramType.Kind() == reflect.Ptr {
paramVal = reflect.New(paramType.Elem())
// Fill the struct fields with the positional arguments
for i := 0; i < paramType.Elem().NumField(); i++ {
paramVal.Elem().Field(i).Set(args[i+1])
}
} else {
paramVal = reflect.New(paramType).Elem()
// Fill the struct fields with the positional arguments
for i := 0; i < paramType.NumField(); i++ {
paramVal.Field(i).Set(args[i+1])
}
}
// Call the implementation function with the context and constructed struct
results := reflect.ValueOf(fn).Call([]reflect.Value{ctx, paramVal})
return results
},
)
return &ActivityWithImpl{activityName: a.Name, queue: a.queue, fn: wrapper.Interface()}
}
// Execute asynchronously executes the activity and returns a promise.
func (a Activity[Param, Return]) Execute(ctx workflow.Context, param Param) workflow.Future {
if !a.positional {
return workflow.ExecuteActivity(workflow.WithTaskQueue(ctx, a.queue.name), a.Name, param)
}
// For positional activities, extract struct fields into separate arguments
paramVal := reflect.ValueOf(param)
if paramVal.Kind() == reflect.Ptr {
paramVal = paramVal.Elem()
}
args := make([]interface{}, paramVal.NumField())
for i := 0; i < paramVal.NumField(); i++ {
args[i] = paramVal.Field(i).Interface()
}
return workflow.ExecuteActivity(workflow.WithTaskQueue(ctx, a.queue.name), a.Name, args...)
}
// AppendFuture executes the activity and appends the resulting future to the provided slice of futures.
func (a Activity[Param, Return]) AppendFuture(ctx workflow.Context, futures *[]workflow.Future, param Param) {
*futures = append(*futures, a.Execute(ctx, param))
}
// Run synchronously executes the activity and returns the result.
func (a Activity[Param, Return]) Run(ctx workflow.Context, param Param) (Return, error) {
var result Return
err := a.Execute(ctx, param).Get(ctx, &result)
return result, err
}