-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcustom_node.go
95 lines (78 loc) · 2.08 KB
/
custom_node.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
package zen
// #include "zen_engine.h"
import "C"
import (
"encoding/json"
"errors"
"github.com/tidwall/gjson"
)
type CustomNodeHandler func(request NodeRequest) (NodeResponse, error)
type CustomNode struct {
ID string `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
Config json.RawMessage `json:"config"`
}
type NodeRequest struct {
Node CustomNode `json:"node"`
Input json.RawMessage `json:"input"`
}
type NodeResponse struct {
Output any `json:"output"`
TraceData any `json:"traceData"`
}
func wrapCustomNodeHandler(customNodeHandler CustomNodeHandler) func(cRequest *C.char) C.ZenCustomNodeResult {
return func(cRequest *C.char) C.ZenCustomNodeResult {
strRequest := C.GoString(cRequest)
var request NodeRequest
if err := json.Unmarshal([]byte(strRequest), &request); err != nil {
return C.ZenCustomNodeResult{
content: nil,
error: C.CString(err.Error()),
}
}
response, err := customNodeHandler(request)
if err != nil {
return C.ZenCustomNodeResult{
content: nil,
error: C.CString(err.Error()),
}
}
cResponse, err := json.Marshal(response)
if err != nil {
return C.ZenCustomNodeResult{
content: nil,
error: C.CString(err.Error()),
}
}
return C.ZenCustomNodeResult{
content: C.CString(string(cResponse)),
error: nil,
}
}
}
func GetNodeFieldRaw[T any](request NodeRequest, path string) (T, error) {
result := gjson.GetBytes(request.Node.Config, path)
if !result.Exists() {
return *new(T), errors.New("path does not exist")
}
var r T
if err := json.Unmarshal([]byte(result.Raw), &r); err != nil {
return *new(T), err
}
return r, nil
}
func GetNodeField[T any](request NodeRequest, path string) (T, error) {
result := gjson.GetBytes(request.Node.Config, path)
if !result.Exists() {
return *new(T), errors.New("path does not exist")
}
if result.Type != gjson.String {
var r T
if err := json.Unmarshal([]byte(result.Raw), &r); err != nil {
return *new(T), err
}
return r, nil
}
return RenderTemplate[T](result.Str, request.Input)
}