-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrun.go
More file actions
454 lines (408 loc) · 13.9 KB
/
Copy pathrun.go
File metadata and controls
454 lines (408 loc) · 13.9 KB
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package starlet
import (
"context"
"fmt"
"io"
"io/fs"
"math"
"sync"
"time"
"github.com/1set/starlet/lib/goidiomatic"
"github.com/1set/starlight/convert"
"go.starlark.net/starlark"
"go.starlark.net/syntax"
)
// REPL is defined in run_repl.go (terminal targets) / run_repl_stub.go
// (non-terminal targets): the
// interactive REPL pulls go.starlark.net/repl -> chzyer/readline, a terminal
// library that does not compile for browser js/wasm or WASI. Isolating it
// behind a build tag keeps the library core (and every consumer, e.g. a WASM
// playground) free of that terminal dependency.
// RunScript initiates a Machine, executes a script with extra variables, and returns the Machine and the execution result.
func RunScript(content []byte, extras StringAnyMap) (*Machine, StringAnyMap, error) {
m := NewDefault()
res, err := m.RunScript(content, extras)
return m, res, err
}
// RunFile initiates a Machine, executes a script from a file with extra variables, and returns the Machine and the execution result.
func RunFile(name string, fileSys fs.FS, extras StringAnyMap) (*Machine, StringAnyMap, error) {
m := NewDefault()
res, err := m.RunFile(name, fileSys, extras)
return m, res, err
}
// RunTrustedScript initiates a Machine, executes a script with all builtin modules loaded and extra variables, returns the Machine and the result.
// Use with caution as it allows script access to file system and network.
func RunTrustedScript(content []byte, globals, extras StringAnyMap) (*Machine, StringAnyMap, error) {
m := NewWithBuiltins(globals, nil, nil)
res, err := m.RunScript(content, extras)
return m, res, err
}
// RunTrustedFile initiates a Machine, executes a script from a file with all builtin modules loaded and extra variables, returns the Machine and the result.
// Use with caution as it allows script access to file system and network.
func RunTrustedFile(name string, fileSys fs.FS, globals, extras StringAnyMap) (*Machine, StringAnyMap, error) {
m := NewWithBuiltins(globals, nil, nil)
res, err := m.RunFile(name, fileSys, extras)
return m, res, err
}
// Run executes a preset script and returns the output.
func (m *Machine) Run() (StringAnyMap, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.runInternal(context.Background(), nil, true)
}
// RunScript executes a script with additional variables, which take precedence over global variables and modules, returns the result.
func (m *Machine) RunScript(content []byte, extras StringAnyMap) (StringAnyMap, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.scriptName = "direct.star"
m.scriptContent = content
m.scriptFS = nil
return m.runInternal(context.Background(), extras, false)
}
// RunFile executes a script from a file with additional variables, which take precedence over global variables and modules, returns the result.
func (m *Machine) RunFile(name string, fileSys fs.FS, extras StringAnyMap) (StringAnyMap, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.scriptName = name
m.scriptContent = nil
m.scriptFS = fileSys
return m.runInternal(context.Background(), extras, true)
}
// RunWithTimeout executes a preset script with a timeout and additional variables, which take precedence over global variables and modules, returns the result.
func (m *Machine) RunWithTimeout(timeout time.Duration, extras StringAnyMap) (StringAnyMap, error) {
m.mu.Lock()
defer m.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return m.runInternal(ctx, extras, true)
}
// RunWithContext executes a preset script within a specified context and additional variables, which take precedence over global variables and modules, returns the result.
func (m *Machine) RunWithContext(ctx context.Context, extras StringAnyMap) (StringAnyMap, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.runInternal(ctx, extras, true)
}
// watchThreadCancelCtx cancels thread when ctx fires, until the returned stop
// function is called. stop is idempotent and waits for the watcher goroutine to
// exit, so callers can both defer it (panic safety) and invoke it right after
// execution finishes.
func watchThreadCancelCtx(ctx context.Context, thread *starlark.Thread) (stop func()) {
var wg sync.WaitGroup
wg.Add(1)
done := make(chan struct{})
go func() {
defer wg.Done()
select {
case <-ctx.Done():
thread.Cancel("context cancelled")
case <-done:
// no action if execution has finished
}
}()
var once sync.Once
return func() {
once.Do(func() {
close(done)
wg.Wait()
})
}
}
// watchContextCancel cancels the machine's main thread when ctx fires, until
// the returned stop function is called.
func (m *Machine) watchContextCancel(ctx context.Context) (stop func()) {
return watchThreadCancelCtx(ctx, m.thread)
}
// watchLoadThread cancels a load thread when the run's context (carried as the
// "context" thread-local by newLoadThread) fires, until the returned stop is
// called. A module executed by load() runs on its own thread, so without this
// the run's timeout/cancellation would interrupt only the main thread and a
// long computation inside a loaded module would run past the deadline (bounded
// only by its step budget, or unbounded when none is set). Returns a no-op stop
// when the thread carries no cancellable context.
func (m *Machine) watchLoadThread(thread *starlark.Thread) (stop func()) {
ctx, ok := thread.Local("context").(context.Context)
if !ok || ctx == nil {
return func() {}
}
return watchThreadCancelCtx(ctx, thread)
}
func (m *Machine) runInternal(ctx context.Context, extras StringAnyMap, allowCache bool) (out StringAnyMap, err error) {
defer func() {
if r := recover(); r != nil {
if me, ok := r.(MaxStepsExceededError); ok {
err = errorStarlarkError("exec", me)
} else {
err = errorStarlarkPanic("exec", r)
}
}
}()
// either script content or name and FS must be set
var (
scriptName = m.scriptName
source interface{}
)
if m.scriptContent != nil {
if scriptName == "" {
// for default name, and disable cache to avoid conflict
scriptName = "eval.star"
allowCache = false
}
source = m.scriptContent
} else if m.scriptFS != nil {
if scriptName == "" {
// if no name, cannot load
return nil, errorStarletErrorf("run", "no script name")
}
// load the script content from FS, so that the program cache can
// key on the content (passing the open reader through degraded the
// cache key to the bare filename, letting different files with the
// same name hit each other's compiled program) — and the file
// handle was never closed
rd, e := m.scriptFS.Open(scriptName)
if e != nil {
return nil, errorStarletError("run", e)
}
b, e := io.ReadAll(rd)
_ = rd.Close()
if e != nil {
return nil, errorStarletError("run", e)
}
source = b
} else {
return nil, errorStarletErrorf("run", "no script to execute")
}
// prepare thread
if err = m.prepareThread(extras); err != nil {
return nil, err
}
// cancel thread when context cancelled
if ctx == nil {
// no context given: use an inert placeholder
ctx = context.TODO()
} else if e := ctx.Err(); e != nil {
// an already-cancelled context used to be silently replaced with an
// uncancellable one, running the script with no deadline at all —
// fail fast instead
return nil, errorStarletError("run", e)
}
m.thread.SetLocal("context", ctx)
// cancel the thread when the context fires, until execution finishes
stop := m.watchContextCancel(ctx)
defer stop()
// run with everything prepared
m.runTimes++
res, err := m.execStarlarkFile(scriptName, source, allowCache)
stop()
// merge result as predeclared for next run
for k, v := range res {
m.predeclared[k] = v
}
// handle result and convert
out = m.convertOutput(res)
if err != nil {
// for exit code
if err.Error() == goidiomatic.ErrSystemExit.Error() {
var exitCode uint8
if c := m.thread.Local("exit_code"); c != nil {
if co, ok := c.(uint8); ok {
exitCode = co
}
}
// exit code 0 means success
if exitCode == 0 {
err = nil
} else {
err = errorStarletErrorf("run", "exit code: %d", exitCode)
}
} else {
// wrap starlark errors
err = errorStarlarkError("exec", err)
}
return out, err
}
return out, nil
}
// prepareThread prepares the thread for execution, including preset globals, preload modules and extras.
func (m *Machine) prepareThread(extras StringAnyMap) (err error) {
mergeExtra := func() error {
// no extras
if extras == nil {
return nil
}
// convert extras if needed
esd, err := m.convertInput(extras)
if err != nil {
return errorStarlightConvert("extras", err)
}
// merge extras
for k, v := range esd {
m.predeclared[k] = v
}
return nil
}
// initialize thread or reset for each run
if m.thread == nil {
// -- for the first run
// preset globals + preload modules + extras -> predeclared
if m.predeclared, err = m.convertInput(m.globals); err != nil {
return errorStarlightConvert("globals", err)
}
if err = m.preloadMods.LoadAll(m.predeclared); err != nil {
return errorStarletError("preload", err)
}
// merge extras into predeclared
if err = mergeExtra(); err != nil {
return err
}
// cache load&read + printf -> thread
m.loadCache = &cache{
cache: make(map[string]*entry),
execOpts: m.getFileOptions(),
loadMod: m.lazyloadMods.GetLazyLoader(),
readFile: func(name string) ([]byte, error) {
return readScriptFile(name, m.scriptFS)
},
globals: m.predeclared,
newThread: m.newLoadThread,
watchCancel: m.watchLoadThread,
}
m.thread = &starlark.Thread{
Name: "starlet",
Print: m.printFunc,
Load: func(thread *starlark.Thread, module string) (starlark.StringDict, error) {
return m.loadCache.Load(module)
},
}
} else {
// -- for the second and following runs
// merge extras into predeclared
if err = mergeExtra(); err != nil {
return err
}
// set globals for cache
m.loadCache.loadMod = m.lazyloadMods.GetLazyLoader()
m.loadCache.globals = m.predeclared
// reset for each run
m.thread.Print = m.printFunc
m.thread.Uncancel()
}
// arm the per-run step budget
m.applyStepBudget()
return nil
}
// newLoadThread builds the thread that runs a module executed by load(),
// mirroring the main thread's execution context: the same print func, an
// independent copy of the step budget (so a loaded module's work is bounded
// by the DoS guard instead of escaping it), and the current run's context
// local. The step budget is per-thread, not a shared aggregate counter, so a
// loaded module gets its own MaxSteps allowance — enough to stop a runaway
// loop, which is the DoS the bare thread let through.
func (m *Machine) newLoadThread(load func(*starlark.Thread, string) (starlark.StringDict, error)) *starlark.Thread {
t := &starlark.Thread{
Name: "starlet:load",
Print: m.printFunc,
Load: load,
}
limit := m.maxSteps
if limit == 0 {
limit = math.MaxUint64
}
t.SetMaxExecutionSteps(limit)
if lim := m.maxSteps; lim > 0 {
t.OnMaxSteps = func(*starlark.Thread) {
// recovered by the run/call recover and mapped to a typed error
panic(MaxStepsExceededError{Limit: lim})
}
}
if m.thread != nil {
if ctx := m.thread.Local("context"); ctx != nil {
t.SetLocal("context", ctx)
}
}
return t
}
// applyStepBudget arms the thread with the configured step budget; it must
// run before every execution. The Starlark runtime normalizes a zero limit
// to "unlimited" only on a thread's very first use, so the translation to
// MaxUint64 happens here for reused threads; the step counter resets so
// the budget applies per execution.
func (m *Machine) applyStepBudget() {
limit := m.maxSteps
if limit == 0 {
limit = math.MaxUint64
}
m.thread.SetMaxExecutionSteps(limit)
if lim := m.maxSteps; lim > 0 {
m.thread.OnMaxSteps = func(*starlark.Thread) {
// recovered by the run/call recover and mapped to a typed error
panic(MaxStepsExceededError{Limit: lim})
}
} else {
m.thread.OnMaxSteps = nil
}
m.thread.Steps = 0
}
// Reset resets the machine to initial state before the first run.
// Attention: It does not reset the compiled program cache.
//
// It takes the write lock like the other mutators: it clears the very fields
// (thread, runTimes, predeclared) that Run and the accessors read, so an
// unlocked Reset would race with them however carefully the readers lock.
func (m *Machine) Reset() {
m.mu.Lock()
defer m.mu.Unlock()
m.runTimes = 0
m.thread = nil
m.loadCache = nil
m.predeclared = nil
}
// convertInput converts a StringAnyMap to a starlark.StringDict, usually for output variable.
func (m *Machine) convertInput(a StringAnyMap) (starlark.StringDict, error) {
if m.enableInConv {
return convert.MakeStringDictWithTag(a, m.customTag)
}
return castStringAnyMapToStringDict(a)
}
// convertOutput converts a starlark.StringDict to a StringAnyMap, usually for output variable.
func (m *Machine) convertOutput(d starlark.StringDict) StringAnyMap {
if m.enableOutConv {
return convert.FromStringDict(d)
}
return castStringDictToAnyMap(d)
}
// getFileOptions gets the exec options from the config.
func (m *Machine) getFileOptions() *syntax.FileOptions {
opt := syntax.FileOptions{
Set: true,
}
if m.allowRecursion {
opt.Recursion = true
}
if m.allowGlobalReassign {
opt.GlobalReassign = true
opt.TopLevelControl = true
opt.While = true
}
return &opt
}
// castStringDictToAnyMap converts a starlark.StringDict to a StringAnyMap without any Starlight conversion.
func castStringDictToAnyMap(m starlark.StringDict) StringAnyMap {
ret := make(StringAnyMap, len(m))
for k, v := range m {
ret[k] = v
}
return ret
}
// castStringAnyMapToStringDict converts a StringAnyMap to a starlark.StringDict without any Starlight conversion.
// It fails if any values are not starlark.Value.
func castStringAnyMapToStringDict(m StringAnyMap) (starlark.StringDict, error) {
ret := make(starlark.StringDict, len(m))
for k, v := range m {
sv, ok := v.(starlark.Value)
if !ok {
return nil, fmt.Errorf("value of key %q is not a starlark.Value", k)
}
ret[k] = sv
}
return ret, nil
}