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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
|
package main
import (
"errors"
"io"
"log"
"net/http"
"os"
"strings"
"sync"
)
type HTTPRequest struct {
request *http.Request
route string
debug bool
result chan *HTTPResponse
}
type HTTPResponse struct {
Code int
Headers map[string]string
Body string
}
func HandleHTTPRequest(
queue chan *HTTPRequest,
route string,
req *http.Request,
) chan *HTTPResponse {
res := make(chan *HTTPResponse)
queue <- &HTTPRequest{
request: req,
route: route,
result: res,
}
return res
}
type Worker struct {
lua *Lua
routes map[string]LuaRef
started bool
mu sync.Mutex
evalFn *LuaRef
}
// NewWorker creates a new instance of Worker type.
func NewWorker() *Worker {
return &Worker {
routes: make(map[string]LuaRef),
lua: &Lua{},
}
}
// Start starts the worker:
// 1) creates a Lua context
// 2) executes the argv in it
// 3) initiates the the "luna" module so it's possible to call Go functions
// from Lua
func (w *Worker) Start(argv []string, module map[string]any) error {
if len(argv) == 0 {
return errors.New("argv must at least contain lua file name")
}
w.mu.Lock()
defer w.mu.Unlock()
if w.started {
return errors.New("already started")
}
w.lua.Start()
defer w.lua.RestoreStackFunc()()
// emulate passing arguments to the loaded chunk
args := []any{}
if len(argv) > 1 {
for _, arg := range argv[1:] {
args = append(args, arg)
}
}
err := w.lua.PushArray(args)
if err != nil {
return err
}
w.lua.SetGlobal("arg")
// register the module in the Lua context
err = w.lua.PushObject(module)
if err != nil {
return err
}
w.lua.SetGlobal("luna")
waitCh := make(chan bool)
w.lua.yield = func () {
<- waitCh
}
w.lua.resume = func () bool {
waitCh <- true
return true
}
err = w.lua.Require(argv[0])
if err != nil {
return err
}
w.started = true
return nil
}
// Listen starts handling HTTP requests from the queue.
func (w *Worker) Listen(queue chan *HTTPRequest) {
stringListToAny := func(slice []string) []any {
res := []any{}
for _, v := range slice {
res = append(res, v)
}
return res
}
handle := func(r *HTTPRequest, yield func(), resume func() bool) {
l := w.lua.NewThread(yield, resume)
// Save a thread to a reference so it's not garbage collected
// before we are done with it.
ref := w.lua.PopToRef()
defer w.lua.Unref(ref)
if _, ok := w.routes[r.route]; !ok {
r.result <- &HTTPResponse{
Code: 404,
Headers: make(map[string]string),
Body: "not found",
}
return
}
l.PushTracebackHandler()
l.PushFromRef(w.routes[r.route])
req := r.request
res := make(map[string]any)
res["method"] = req.Method
res["path"] = req.URL.Path
fh := make(map[string]any)
for k := range req.Header {
fh[k] = req.Header.Get(k)
}
res["headers"] = fh
flatQr := make(map[string]any)
qr := req.URL.Query()
for k := range qr {
flatQr[k] = stringListToAny(qr[k])
}
res["query"] = flatQr
// if request body is a multipart form: automatically parse it,
// save the files and form values and put them in to the
// request object in the "form" field
// in all other cases just put the body as a string in the
// "body" field
if strings.HasPrefix(
req.Header.Get("Content-Type"),
"multipart/form-data",
) {
err := req.ParseMultipartForm(0)
if err != nil {
r.result <- &HTTPResponse{
Code: 400,
Headers: make(map[string]string),
Body: "bad multipart request",
}
return
}
form := make(map[string]any)
for k, v := range req.MultipartForm.File {
// for now only take the first value
fh := v[0]
if fh == nil {
continue
}
fd, err := fh.Open()
defer fd.Close()
if err != nil {
r.result <- &HTTPResponse{
Code: 500,
Headers: make(map[string]string),
Body: "server error",
}
log.Println("could not open multipart file:", err)
return
}
// assume fd is a file stored on the filesystem.
// if it's not the case: write the file from
// memory to the filesystem.
f, ok := fd.(*os.File)
if !ok {
f, _ = os.CreateTemp(os.TempDir(), "multipart-")
buf := make([]byte, 8192)
for {
nread, _ := fd.Read(buf)
_, _ = f.Write(buf)
if nread < 8192 {
break
}
}
f.Close()
defer os.Remove(f.Name())
}
record := make(map[string]any)
record["path"] = f.Name()
record["size"] = fh.Size
record["name"] = fh.Filename
form[k] = record
}
for k, v := range req.MultipartForm.Value {
// for now only take the first value
form[k] = v[0]
}
res["form"] = form
} else {
body, err := io.ReadAll(req.Body)
if err != nil {
r.result <- &HTTPResponse{
Code: 500,
Headers: make(map[string]string),
Body: "server error",
}
log.Println("could not read request body:", err)
return
}
res["body"] = string(body)
}
err := l.PushObject(res)
if err != nil {
r.result <- &HTTPResponse{
Code: 500,
Headers: make(map[string]string),
Body: "server error",
}
log.Println("could not form request to lua:", err)
return
}
err = l.PCall(1, 3, -3)
if err != nil {
var body string
if debug {
body = err.Error()
} else {
body = "server error"
}
r.result <- &HTTPResponse{
Code: 500,
Headers: make(map[string]string),
Body: body,
}
log.Println("could not process request:\n" + err.Error())
return
}
// TODO: probably it would be better to just use l.Scan()
// here but i'm not really sure if we want to have that
// overhead here.
code := l.ToInt(-3)
rbody := l.ToString(-1)
// Parse headers.
headers := make(map[string]string)
l.Pop(1)
l.PushNil()
for l.Next() {
if !l.IsString(-2) || !l.IsString(-1) {
l.Pop(1)
continue
}
v := l.ToString(-1)
l.Pop(1)
// We must not pop the item key from the stack
// because otherwise C.lua_next won't work
// properly.
k := l.ToString(-1)
headers[k] = v
}
r.result <- &HTTPResponse{
Code: int(code),
Headers: headers,
Body: rbody,
}
}
resCh := make(chan func() bool, 4096)
outer:
for {
select {
case r, ok := <- queue:
// accept new requests
if !ok {
break outer
}
resCh <- NewCoroutine(
func(yield func(), resume func() bool) {
handle(r, yield, func () bool {
resCh <- resume
return true
})
},
)
case resume, ok := <-resCh:
// coroutine executor
if !ok {
break outer
}
resume()
}
}
}
// Eval evaluates the code in the Lua context. Not safe for execution when
// there are requests in the processing queue, only meant for development
// purposes.
func (w *Worker) Eval(code string) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.evalFn != nil {
w.lua.PushFromRef(*w.evalFn)
w.lua.PushString(code)
return w.lua.PCall(1, 0, 0)
}
return w.lua.LoadString(code)
}
// SetRoute sets a handler for the route.
func (w *Worker) SetRoute(route string, handler LuaRef) {
w.routes[route] = handler
}
// Stop stops the worker closing the Lua context. TODO: stop Listen goroutine
// as well.
func (w *Worker) Stop() {
w.mu.Lock()
defer w.mu.Unlock()
w.lua.Close()
}
// HasSameLua checks if the Lua context belongs to the worker.
func (w *Worker) HasSameLua(l *Lua) bool {
return w.lua == l
}
func NewCoroutine(f func (yield func(), resume func() bool)) (resume func() bool) {
cin := make(chan bool)
cout := make(chan bool)
running := true
resume = func() bool {
if !running {
return false
}
cin <- true
<-cout
return true
}
yield := func() {
cout <- true
<-cin
}
go func() {
<-cin
f(yield, resume)
running = false
cout <- true
}()
return resume
}
|