-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
221 lines (185 loc) · 4.95 KB
/
main.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
package main
import (
"context"
"errors"
"flag"
_ "github.com/KimMachineGun/automemlimit"
"github.com/mbict/befe/buildin"
"github.com/mbict/befe/dsl"
"github.com/mbict/befe/expr"
"github.com/radovskyb/watcher"
"github.com/traefik/yaegi/interp"
"github.com/traefik/yaegi/stdlib"
_ "go.uber.org/automaxprocs"
"log"
"net/http"
"os"
"path"
"strings"
"sync"
"time"
)
type Program struct {
cancelFunc context.CancelFunc
handleRequest expr.Handler
}
func (p *Program) HandleRequest(rw http.ResponseWriter, r *http.Request) {
p.handleRequest(rw, r)
}
func (p *Program) DeInit() {
p.cancelFunc()
}
var (
scriptPath string
addr string
program *Program
ready bool
compileError error
)
func init() {
http.DefaultTransport.(*http.Transport).MaxIdleConns = 1000
http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 1000
flag.StringVar(&scriptPath, "path", "./", "path where the script can be found (./your/program)")
flag.StringVar(&addr, "addr", ":8080", "address and port to listen (:8080)")
flag.Parse()
}
func main() {
var err error
//init program
log.Printf("loading program from :%s", scriptPath)
program, err = loadProgram(scriptPath)
if err != nil {
log.Fatalf("cannot compile program: %s", err)
}
//handleRequest the connections
var e chan error
go func() {
log.Printf("starting engine and listen on :%s", addr)
e <- http.ListenAndServe(addr, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
//handle internal errors
defer func() {
r := recover()
if r != nil {
var err error
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("unknown error")
}
log.Printf("panic in request handling: %s", err)
http.Error(rw, "internal error", http.StatusInternalServerError)
}
}()
//handleRequest connection
program.handleRequest(rw, r)
}))
}()
//watch for changes and recompile program if needed
log.Printf("watching for file changes in dir: %s", scriptPath)
watchScriptDir(scriptPath)
log.Println(<-e)
//de initialize the running program.
program.DeInit()
}
func watchScriptDir(dir string) {
w := watcher.New()
w.SetMaxEvents(1)
// Only notify rename and move events.
w.FilterOps(watcher.Rename, watcher.Move, watcher.Write, watcher.Create, watcher.Remove)
go func() {
var lock sync.Mutex
for {
select {
case <-w.Event:
lock.Lock()
log.Printf("detected changes in script, reloading program")
p, err := loadProgram(scriptPath)
if err == nil {
//we replace the program with the newly loaded one, and keep a copy of the old one
log.Printf("new program running")
oldProgram := program
program = p
//deinit the old program and clean up, shared resources, go routines etc
log.Printf("deInit previous program")
oldProgram.DeInit()
} else {
log.Printf("cannot compile new program: %s", err)
}
compileError = err
lock.Unlock()
case err := <-w.Error:
log.Printf("error in watch script directory: %s", err)
return
case <-w.Closed:
return
}
}
}()
// Watch test_folder recursively for changes.
if err := w.AddRecursive(dir); err != nil {
log.Fatalln(err)
}
go func() {
if err := w.Start(time.Second); err != nil {
log.Fatalln(err)
}
}()
}
func loadProgram(path string) (*Program, error) {
interpreter, err := loadScript(path)
if err != nil {
return nil, err
}
//in case we have an init function we initialize
vInit, err := interpreter.Eval("main.Init")
if err == nil {
initFunc := vInit.Interface().(func() error)
if err := initFunc(); err != nil {
return nil, err
}
}
var handleFunc expr.Handler
//check if there is a dsl defined in the program endpoint
vDsl, err := interpreter.Eval("main.Program")
var program dsl.Expr
if err != nil {
return nil, err
}
programFunc := vDsl.Interface().(func() dsl.Expr)
program = programFunc()
ctx, cancelFunc := context.WithCancel(context.Background())
handleFunc = program.BuildHandler(ctx, nil)
return &Program{
cancelFunc: cancelFunc,
handleRequest: handleFunc,
}, nil
}
func loadScript(sourcePath string) (*interp.Interpreter, error) {
i := interp.New(interp.Options{})
i.Use(stdlib.Symbols)
i.Use(buildin.Symbols)
dir, err := os.ReadDir(sourcePath)
if err != nil {
return nil, err
}
for _, fs := range dir {
//if fs.IsDir() || (fs.Mode()&os.ModeSymlink) == os.ModeSymlink || strings.HasSuffix(fs.Name(), "_test.go") {
if fs.IsDir() || (strings.HasPrefix(fs.Name(), ".") || strings.HasSuffix(fs.Name(), "_test.go") || !strings.HasSuffix(fs.Name(), ".go")) {
log.Printf("ignoring file : %s", path.Join(sourcePath, fs.Name()))
continue
}
log.Printf("loading file : %s", path.Join(sourcePath, fs.Name()))
source, err := os.ReadFile(path.Join(sourcePath, fs.Name()))
if err != nil {
return nil, err
}
_, err = i.Eval(string(source))
if err != nil {
return nil, err
}
}
return i, nil
}