-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctions.go
176 lines (157 loc) · 4.38 KB
/
functions.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 cfft
import (
"bytes"
"context"
"crypto/md5"
"fmt"
"log/slog"
"os"
"os/exec"
"regexp"
"strings"
"syscall"
"text/template"
"time"
"github.com/mattn/go-shellwords"
)
const MaxCodeSize = 10 * 1024
var FuncMap = template.FuncMap{
"join": strings.Join,
}
type FuncTemplateArgs struct {
Name string
Code string
}
var FuncTemplate = template.Must(template.New("func").Parse(`
const {{.Name}} = async function(event) {
{{.Code}}
return handler(event);
}
`))
type MainTemplateArgs struct {
Imports []string
FuncNames []string
FuncCodes []string
}
var MainTemplateRequest = template.Must(template.New("main").Funcs(FuncMap).Parse(`
{{- range .Imports }}
{{.}}
{{- end -}}
{{- range .FuncCodes }}
{{.}}
{{- end -}}
async function handler(event) {
const funcs = [{{ join .FuncNames ","}}];
for (let i = 0; i < funcs.length; i++) {
const res = await funcs[i](event);
if (res && res.statusCode) {
// when viewer-request returns response object, return it immediately
return res;
}
event.request = res;
}
return event.request;
}
`))
var MainTemplateResponse = template.Must(template.New("main").Funcs(FuncMap).Parse(`
{{- range .Imports -}}
{{.}}
{{- end -}}
{{- range .FuncCodes -}}
{{.}}
{{- end -}}
async function handler(event) {
const funcs = [{{ join .FuncNames "," }}];
for (let i = 0; i < funcs.length; i++) {
event.response = await funcs[i](event);
}
return event.response;
}
`))
type ConfigFunction struct {
EventType string `json:"event_type" yaml:"event_type"`
Functions []string `json:"functions" yaml:"functions"`
FilterCommand string `json:"filter_command" yaml:"filter_command"`
}
func (c *ConfigFunction) FunctionCode(ctx context.Context, readFile func(string) ([]byte, error)) ([]byte, error) {
if len(c.Functions) == 1 {
// single function
if b, err := readFile(c.Functions[0]); err != nil {
return nil, fmt.Errorf("failed to read function file %s, %w", c.Functions[0], err)
} else {
return c.runFilter(ctx, b)
}
}
// chain function
slog.Debug("generating chain function code")
funcNames := make([]string, 0, len(c.Functions))
funcCodes := make([]string, 0, len(c.Functions))
imports := make([]string, 0)
for _, cf := range c.Functions {
slog.Debug(f("reading chain function file %s", cf))
b, err := readFile(cf)
if err != nil {
return nil, fmt.Errorf("failed to read chain function file %s, %w", cf, err)
}
name := fmt.Sprintf("__chain_%x", md5.Sum(b))
imps, code := splitCode(string(b))
buf := strings.Builder{}
if err := FuncTemplate.Execute(&buf, FuncTemplateArgs{Name: name, Code: code}); err != nil {
return nil, fmt.Errorf("failed to execute function template, %w", err)
}
funcCodes = append(funcCodes, buf.String())
imports = append(imports, imps...)
funcNames = append(funcNames, name)
}
var tmpl *template.Template
switch c.EventType {
case "viewer-request":
tmpl = MainTemplateRequest
case "viewer-response":
tmpl = MainTemplateResponse
default:
return nil, fmt.Errorf("invalid chain event_type %s", c.EventType)
}
buf := bytes.Buffer{}
if err := tmpl.Execute(&buf, MainTemplateArgs{Imports: imports, FuncNames: funcNames, FuncCodes: funcCodes}); err != nil {
return nil, fmt.Errorf("failed to execute main template, %w", err)
}
return c.runFilter(ctx, buf.Bytes())
}
func splitCode(s string) ([]string, string) {
importRegexp := regexp.MustCompile(`(?m)^import\s+.*?;$`)
imports := importRegexp.FindAllString(s, -1)
nonImports := importRegexp.ReplaceAllString(s, "")
return imports, nonImports
}
func (c *ConfigFunction) runFilter(ctx context.Context, b []byte) ([]byte, error) {
if c.FilterCommand == "" {
return b, nil
}
slog.Info(f("running filter command %s", c.FilterCommand))
cmds, err := shellwords.Parse(c.FilterCommand)
if err != nil {
return nil, fmt.Errorf("failed to parse filter command, %w", err)
}
var cmd *exec.Cmd
switch len(cmds) {
case 0:
return nil, fmt.Errorf("empty filter command")
case 1:
cmd = exec.CommandContext(ctx, cmds[0])
default:
cmd = exec.CommandContext(ctx, cmds[0], cmds[1:]...)
}
cmd.Cancel = func() error {
return cmd.Process.Signal(syscall.SIGTERM)
}
cmd.WaitDelay = 60 * time.Second
cmd.Stdin = bytes.NewReader(b)
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("failed to run filter command, %w", err)
}
return out.Bytes(), nil
}