/
input.go
82 lines (67 loc) · 1.77 KB
/
input.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
package workflow
import (
"context"
"encoding/json"
"fmt"
"reflect"
"github.com/authgear/authgear-server/pkg/util/validation"
)
type InputReactor interface {
CanReactTo(ctx context.Context, deps *Dependencies, workflows Workflows) ([]Input, error)
ReactTo(ctx context.Context, deps *Dependencies, workflows Workflows, input Input) (*Node, error)
}
type Input interface {
Kind() string
JSONSchema() *validation.SimpleSchema
}
type InputJSON struct {
Kind string `json:"kind"`
Data json.RawMessage `json:"data"`
}
// There is no private input factory because
// input cannot be deserialized from the database (at the moment).
type InputFactory func() Input
var publicInputRegistry = map[string]InputFactory{}
func RegisterPublicInput(input Input) {
inputType := reflect.TypeOf(input).Elem()
inputKind := input.Kind()
factory := InputFactory(func() Input {
return reflect.New(inputType).Interface().(Input)
})
if _, hasKind := publicInputRegistry[inputKind]; hasKind {
panic(fmt.Errorf("workflow: duplicated input kind: %v", inputKind))
}
publicInputRegistry[inputKind] = factory
}
func InstantiateInputFromPublicRegistry(j InputJSON) (Input, error) {
factory, ok := publicInputRegistry[j.Kind]
if !ok {
return nil, ErrUnknownInput
}
input := factory()
err := input.JSONSchema().Validator().ParseJSONRawMessage(j.Data, input)
if err != nil {
return nil, err
}
return input, nil
}
func AsInput(i Input, iface interface{}) bool {
if i == nil {
return false
}
val := reflect.ValueOf(iface)
typ := val.Type()
targetType := typ.Elem()
for {
if reflect.TypeOf(i).AssignableTo(targetType) {
val.Elem().Set(reflect.ValueOf(i))
return true
}
if x, ok := i.(interface{ Input() Input }); ok {
i = x.Input()
} else {
break
}
}
return false
}