-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinvocations.go
176 lines (150 loc) · 4.73 KB
/
invocations.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
package flow
import (
"encoding/json"
"fmt"
"io"
"reflect"
dbg "runtime/debug"
"github.com/fnproject/flow-lib-go/blobstore"
"github.com/fnproject/flow-lib-go/models"
)
const (
// protocol headers. beware, since we're using go http.Header, casing is sensitive
HeaderPrefix = "Fnproject-"
FlowIDHeader = HeaderPrefix + "Flowid"
StageIDHeader = HeaderPrefix + "Stageid"
ContentTypeHeader = "Content-Type"
JSONMediaHeader = "application/json"
GobMediaHeader = "application/x-gob"
OctetStreamMediaHeader = "application/octet-stream"
MaxContinuationArgCount = 2
)
// models incoming request API (not auto-generated from swagger!)
type InvokeStageRequest struct {
FlowID string `json:"flow_id,omitempty"`
StageID string `json:"stage_id,omitempty"`
Closure *models.ModelBlobDatum `json:"closure,omitempty"`
Args []*models.ModelCompletionResult `json:"args,omitempty"`
}
type InvokeStageResponse struct {
Result *models.ModelCompletionResult `json:"result,omitempty"`
}
func (in *InvokeStageRequest) invoke(codec codec) {
// catch panics and publish them as errors
defer func() {
if r := recover(); r != nil {
stack := fmt.Sprintf("%s: %s", r, dbg.Stack())
debug(fmt.Sprintf("Recovered from invoke error:\n %s", stack))
}
}()
debug(fmt.Sprintf("Invoking continuation with %d args", len(in.Args)))
actionFunc := in.action()
argTypes := actionArgs(actionFunc)
var args []interface{}
for i, _ := range argTypes {
debug(fmt.Sprintf("Decoding arg of type %v", argTypes[i]))
args = append(args, decodeResult(in.Args[i], in.FlowID, argTypes[i], blobstore.GetBlobStore()))
}
result, err := invokeFunc(actionFunc, args)
writeResult(in.FlowID, codec, result, err)
}
func (in *InvokeStageRequest) action() (actionFunction interface{}) {
blobstore.GetBlobStore().ReadBlob(in.FlowID, in.Closure.BlobID, JSONMediaHeader,
func(body io.ReadCloser) {
var ref actionRef
if err := json.NewDecoder(body).Decode(&ref); err != nil {
panic("Failed to decode continuation")
}
var valid bool
actionFunction, valid = actions[ref.ID]
if !valid {
panic("Continuation not registered")
}
})
return
}
func handleInvocation(codec codec) {
debug("Handling continuation")
var in InvokeStageRequest
if err := json.NewDecoder(codec.in()).Decode(&in); err != nil {
panic(fmt.Sprintf("Failed to decode stage invocation request: %v", err))
}
in.invoke(codec)
}
func invokeFunc(continuation interface{}, args []interface{}) (result interface{}, err error) {
fn := reflect.ValueOf(continuation)
var rargs []reflect.Value
argTypes := actionArgs(continuation)
if reflect.TypeOf(continuation).NumIn() == 0 {
debug("Ignoring arguments for empty continuation function")
rargs = make([]reflect.Value, 0)
} else {
rargs = make([]reflect.Value, len(args))
for i, a := range args {
if a == nil { // converts empty datum parameters to zero type
rargs[i] = reflect.Zero(argTypes[i])
} else {
rargs[i] = reflect.ValueOf(a)
}
}
}
results := fn.Call(rargs)
switch len(results) {
case 0:
return nil, nil
case 1:
return valToInterface(results[0]), nil
case 2:
return valToInterface(results[0]), valToError(results[1])
default:
return nil, fmt.Errorf("Continuation returned invalid number of results")
}
}
func writeResult(flowID string, codec codec, result interface{}, err error) {
var val interface{}
if err == nil {
debug(fmt.Sprintf("Writing successful result %v", result))
val = result
} else {
debug(fmt.Sprintf("Writing error result %v", err))
val = err
}
resp := &InvokeStageResponse{Result: valueToModel(val, flowID, blobstore.GetBlobStore())}
if err := json.NewEncoder(codec.out()).Encode(resp); err != nil {
panic("Failed to encode completion result")
}
}
// internal encoding of a function pointer since go doesn't allow pointers to be serialized
type actionRef struct {
ID string `json:"action-key"`
}
func (cr *actionRef) getKey() string {
return cr.ID
}
func newActionRef(actionFunc interface{}) *actionRef {
return &actionRef{ID: getActionKey(actionFunc)}
}
func actionArgs(actionFunc interface{}) (argTypes []reflect.Type) {
if reflect.TypeOf(actionFunc).Kind() != reflect.Func {
panic("Continuation must be a function!")
}
fn := reflect.TypeOf(actionFunc)
argC := fn.NumIn() // inbound params
if argC > MaxContinuationArgCount {
panic(fmt.Sprintf("Continuations may take a maximum of %d parameters", MaxContinuationArgCount))
}
argTypes = make([]reflect.Type, argC)
for i := 0; i < argC; i++ {
argTypes[i] = fn.In(i)
}
return
}
func valToInterface(v reflect.Value) interface{} {
return v.Interface()
}
func valToError(v reflect.Value) error {
if v.IsNil() {
return nil
}
return valToInterface(v).(error)
}