forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
242 lines (206 loc) · 5.08 KB
/
server.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package blobl
import (
"context"
"encoding/json"
"errors"
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"runtime"
"sync"
"syscall"
"time"
"github.com/urfave/cli/v2"
"github.com/dafanshu/benthos/v4/internal/bloblang"
"github.com/dafanshu/benthos/v4/internal/bloblang/parser"
"github.com/dafanshu/benthos/v4/internal/filepath/ifs"
_ "embed"
)
//go:embed resources/bloglang_editor_page.html
var bloblangEditorPage string
func openBrowserAt(url string) {
switch runtime.GOOS {
case "linux":
_ = exec.Command("xdg-open", url).Start()
case "windows":
_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
_ = exec.Command("open", url).Start()
}
}
type fileSync struct {
mut sync.Mutex
dirty bool
mappingString string
inputString string
writeBack bool
mappingFile string
inputFile string
}
func newFileSync(inputFile, mappingFile string, writeBack bool) *fileSync {
f := &fileSync{
inputString: `{"message":"hello world"}`,
mappingString: "root = this",
writeBack: writeBack,
inputFile: inputFile,
mappingFile: mappingFile,
}
if inputFile != "" {
inputBytes, err := ifs.ReadFile(ifs.OS(), inputFile)
if err != nil {
if !writeBack || !errors.Is(err, fs.ErrNotExist) {
log.Fatal(err)
}
} else {
f.inputString = string(inputBytes)
}
}
if mappingFile != "" {
mappingBytes, err := ifs.ReadFile(ifs.OS(), mappingFile)
if err != nil {
if !writeBack || !errors.Is(err, fs.ErrNotExist) {
log.Fatal(err)
}
} else {
f.mappingString = string(mappingBytes)
}
}
if writeBack {
go func() {
t := time.NewTicker(time.Second * 5)
for {
<-t.C
f.write()
}
}()
}
return f
}
func (f *fileSync) update(input, mapping string) {
f.mut.Lock()
if mapping != f.mappingString || input != f.inputString {
f.dirty = true
}
f.mappingString = mapping
f.inputString = input
f.mut.Unlock()
}
func (f *fileSync) write() {
f.mut.Lock()
defer f.mut.Unlock()
if !f.writeBack || !f.dirty {
return
}
if f.inputFile != "" {
if err := ifs.WriteFile(ifs.OS(), f.inputFile, []byte(f.inputString), 0o644); err != nil {
log.Printf("Failed to write input file: %v\n", err)
}
}
if f.mappingFile != "" {
if err := ifs.WriteFile(ifs.OS(), f.mappingFile, []byte(f.mappingString), 0o644); err != nil {
log.Printf("Failed to write mapping file: %v\n", err)
}
}
f.dirty = false
}
func (f *fileSync) input() string {
f.mut.Lock()
defer f.mut.Unlock()
return f.inputString
}
func (f *fileSync) mapping() string {
f.mut.Lock()
defer f.mut.Unlock()
return f.mappingString
}
func runServer(c *cli.Context) error {
fSync := newFileSync(c.String("input-file"), c.String("mapping-file"), c.Bool("write"))
defer fSync.write()
mux := http.NewServeMux()
mux.HandleFunc("/execute", func(w http.ResponseWriter, r *http.Request) {
req := struct {
Mapping string `json:"mapping"`
Input string `json:"input"`
}{}
dec := json.NewDecoder(r.Body)
if err := dec.Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fSync.update(req.Input, req.Mapping)
res := struct {
ParseError string `json:"parse_error"`
MappingError string `json:"mapping_error"`
Result string `json:"result"`
}{}
defer func() {
resBytes, err := json.Marshal(res)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
_, _ = w.Write(resBytes)
}()
exec, err := bloblang.GlobalEnvironment().NewMapping(req.Mapping)
if err != nil {
if perr, ok := err.(*parser.Error); ok {
res.ParseError = fmt.Sprintf("failed to parse mapping: %v\n", perr.ErrorAtPositionStructured("", []rune(req.Mapping)))
} else {
res.ParseError = err.Error()
}
return
}
execCache := newExecCache()
output, err := execCache.executeMapping(exec, false, true, []byte(req.Input))
if err != nil {
res.MappingError = err.Error()
} else {
res.Result = output
}
})
indexTemplate := template.Must(template.New("index").Parse(bloblangEditorPage))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
err := indexTemplate.Execute(w, struct {
InitialInput string
InitialMapping string
}{
fSync.input(),
fSync.mapping(),
})
if err != nil {
http.Error(w, "Template error", http.StatusBadGateway)
return
}
})
host, port := c.String("host"), c.String("port")
bindAddress := host + ":" + port
if !c.Bool("no-open") {
u, err := url.Parse("http://localhost:" + port)
if err != nil {
return fmt.Errorf("failed to parse URL: %w", err)
}
openBrowserAt(u.String())
}
log.Printf("Serving at: http://%v\n", bindAddress)
server := http.Server{
Addr: bindAddress,
Handler: mux,
}
go func() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
// Wait for termination signal
<-sigChan
_ = server.Shutdown(context.Background())
}()
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return fmt.Errorf("failed to listen and serve: %w", err)
}
return nil
}