-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
269 lines (221 loc) · 5.41 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
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
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package orbit
import (
"fmt"
"path"
"sync"
"time"
"context"
"github.com/abcum/emitr"
"github.com/abcum/otto"
)
// Orbit is a node.go context.
type Orbit struct {
// Underlying Otto instance.
*otto.Otto
// Emitter
*emitr.Emitter
// Context
ctx context.Context
// Lock mutex
lock sync.RWMutex
// Quit channel
quit chan interface{}
// Loop channel
queue chan Task
// Timeout timer
timer *time.Timer
// Runtime tasks
tasks map[Task]Task
// Timeout sets a timeout
timeout time.Duration
// Module outputs are cached for future use.
modules map[string]otto.Value
}
type (
// simple is a javascript module
simple func(*Orbit) interface{}
// module is a javascript module
module func(*Orbit) (otto.Value, error)
)
var (
// Event groups
inits []func(*Orbit)
exits []func(*Orbit)
fails []func(*Orbit, error)
// Finder loads files
finder func(*Orbit, []string) (interface{}, string, error)
// Modules stores registered packages
modules = make(map[string]module)
)
// Add adds a module to the runtime
func Add(name string, item interface{}) {
switch what := item.(type) {
case string:
modules[name] = exec(what, name)
case []byte:
modules[name] = exec(what, name)
case func(*Orbit) (otto.Value, error):
modules[name] = what
case func(*Orbit) interface{}:
modules[name] = func(orb *Orbit) (otto.Value, error) {
return orb.ToValue(what(orb))
}
}
}
// OnInit registers a callback for when the program starts up
func OnInit(call func(*Orbit)) {
inits = append(inits, call)
}
// OnExit registers a callback for when the program shuts down
func OnExit(call func(*Orbit)) {
exits = append(exits, call)
}
// OnFail registers a callback for when the program encounters an error
func OnFail(call func(*Orbit, error)) {
fails = append(fails, call)
}
// OnFile registers a callback for finding required files
func OnFile(call func(*Orbit, []string) (interface{}, string, error)) {
finder = call
}
// New creates a new Orbit runtime
func New(timeout time.Duration) *Orbit {
orbit := &Orbit{
Otto: otto.New(),
quit: make(chan interface{}, 1),
queue: make(chan Task),
tasks: make(map[Task]Task),
modules: make(map[string]otto.Value),
timeout: timeout * time.Millisecond,
Emitter: &emitr.Emitter{},
}
orbit.Interrupt = make(chan func(), 1)
return orbit
}
func (orb *Orbit) Context() context.Context {
if orb.ctx != nil {
return orb.ctx
}
return context.Background()
}
func (orb *Orbit) WithContext(ctx context.Context) *Orbit {
nrb := new(Orbit)
*nrb = *orb
nrb.ctx = ctx
return nrb
}
// Def sets a global variable in the runtime
func (orb *Orbit) Def(name string, item interface{}) {
obj, _ := orb.Get("global")
obj.Object().Set(name, item)
orb.Set(name, item)
}
// Exec executes some code. Code may be a string or a byte slice.
func (orb *Orbit) Exec(name string, code interface{}) (err error) {
defer func() {
if r := recover(); r != nil {
switch e := r.(type) {
case error:
err = e
case string:
err = fmt.Errorf(e)
}
orb.fail(err)
}
orb.exit()
if orb.timer != nil {
orb.timer.Stop()
}
for task := range orb.tasks {
orb.Pull(task)
}
}()
orb.SetStackDepthLimit(20000)
orb.tick()
orb.init()
// Run main code
_, err = main(code, name)(orb)
if err != nil {
panic(err)
}
// Wait for timers
err = orb.loop()
if err != nil {
panic(err)
}
return
}
// File finds a file relative to the current javascript context.
func (orb *Orbit) File(name string, extn string) (code interface{}, file string, err error) {
var files []string
fold, _ := path.Split(orb.Otto.Context().Filename)
if path.IsAbs(name) == true {
if path.Ext(name) != "" {
files = append(files, name)
}
if path.Ext(name) == "" {
files = append(files, name+"."+extn)
}
}
if path.IsAbs(name) == false {
if path.Ext(name) != "" {
files = append(files, path.Join(fold, name))
}
if path.Ext(name) == "" {
files = append(files, path.Join(fold, name)+"."+extn)
}
}
if finder == nil {
panic(orb.MakeCustomError("Error", fmt.Sprintf("Cannot find file '%s'", name)))
}
if code, file, err = finder(orb, files); err != nil {
panic(orb.MakeCustomError("Error", fmt.Sprintf("Cannot find file '%s'", name)))
}
return code, name, err
}
// Quit exits the current javascript context cleanly, or with an error.
func (orb *Orbit) Quit(err error) {
panic(orb.MakeCustomError("Error", err.Error()))
}
func (orb *Orbit) init() {
orb.Emit("init")
for _, e := range inits {
e(orb)
}
}
func (orb *Orbit) exit() {
orb.Emit("exit")
for _, e := range exits {
e(orb)
}
}
func (orb *Orbit) fail(err error) {
orb.Emit("fail")
for _, e := range fails {
e(orb, err)
}
}
func (orb *Orbit) tick() {
if orb.timeout > 0 {
orb.timer = time.AfterFunc(orb.timeout, func() {
err := fmt.Errorf("Script timeout")
orb.Interrupt <- func() {
panic(err)
}
orb.quit <- err
})
}
}