-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.go
More file actions
321 lines (265 loc) · 7.31 KB
/
plugin.go
File metadata and controls
321 lines (265 loc) · 7.31 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
package jsmachine
import (
"context"
"fmt"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/robertkrimen/otto"
"go.uber.org/zap"
)
const (
PluginName = "js"
)
// MetricsPlugin interface for accessing metrics plugin's collectors
type MetricsPlugin interface {
Name() string
}
// metricsPluginInternal provides access to metrics plugin's internal collectors sync.Map
type metricsPluginInternal struct {
collectors sync.Map // name -> *collector
}
// Plugin represents the JavaScript execution plugin
type Plugin struct {
log *zap.Logger
cfg *Config
// VM pool management
vmPool chan *otto.Otto
vmPoolSize int
mu sync.RWMutex
// Go bindings for JavaScript
bindings *Bindings
// Graceful shutdown
stopCh chan struct{}
wg sync.WaitGroup
// Prometheus metrics
executionsTotal *prometheus.CounterVec
executionDuration *prometheus.HistogramVec
poolSizeGauge prometheus.Gauge
poolAvailable prometheus.Gauge
activeExecutions prometheus.Gauge
codeSize prometheus.Histogram
// Metrics plugin reference (for accessing user-defined metrics)
metricsPlugin *metricsPluginInternal
}
// Configurer interface for configuration access
type Configurer interface {
UnmarshalKey(name string, out interface{}) error
Has(name string) bool
}
// Logger interface for dependency injection
type Logger interface {
NamedLogger(name string) *zap.Logger
}
// Init initializes the plugin
func (p *Plugin) Init(cfg Configurer, log Logger) error {
const op = "js_plugin_init"
// Initialize configuration with defaults
p.cfg = &Config{}
// Try to unmarshal config if it exists
if cfg.Has(PluginName) {
if err := cfg.UnmarshalKey(PluginName, p.cfg); err != nil {
return fmt.Errorf("%s: failed to unmarshal config: %w", op, err)
}
}
// Always set defaults (fills in missing values)
p.cfg.InitDefaults()
// Validate configuration
if err := p.cfg.Validate(); err != nil {
return fmt.Errorf("%s: config validation failed: %w", op, err)
}
// Initialize logger
p.log = log.NamedLogger(PluginName)
// Initialize metrics
p.initMetrics()
// Initialize bindings
p.bindings = newBindings(p.log, p)
p.log.Info("JavaScript plugin initialized",
zap.Int("pool_size", p.cfg.PoolSize),
zap.Int("max_memory_mb", p.cfg.MaxMemoryMB),
zap.Int("default_timeout_ms", p.cfg.DefaultTimeout),
)
return nil
}
// Name returns plugin name
func (p *Plugin) Name() string {
return PluginName
}
// Serve starts the plugin (initializes VM pool)
func (p *Plugin) Serve() chan error {
errCh := make(chan error, 1)
p.vmPoolSize = p.cfg.PoolSize
p.vmPool = make(chan *otto.Otto, p.vmPoolSize)
p.stopCh = make(chan struct{})
// Initialize VM pool
for i := 0; i < p.vmPoolSize; i++ {
vm := otto.New()
// Set up interrupt channel for timeout handling
vm.Interrupt = make(chan func(), 1)
// Inject Go bindings into VM
if err := p.bindings.injectIntoVM(vm); err != nil {
p.log.Error("failed to inject bindings into VM", zap.Error(err))
errCh <- fmt.Errorf("failed to inject bindings: %w", err)
return errCh
}
p.vmPool <- vm
}
p.log.Info("JavaScript plugin started",
zap.Int("pool_size", p.vmPoolSize),
zap.Int("default_timeout_ms", p.cfg.DefaultTimeout),
)
return errCh
}
// Stop gracefully shuts down the plugin
func (p *Plugin) Stop(ctx context.Context) error {
p.log.Info("Stopping JavaScript plugin...")
// Signal shutdown
close(p.stopCh)
// Wait for active executions with timeout
done := make(chan struct{})
go func() {
p.wg.Wait()
close(done)
}()
select {
case <-done:
p.log.Info("All JavaScript executions completed")
case <-ctx.Done():
p.log.Warn("Timeout waiting for JavaScript executions, forcing shutdown")
}
// Close VM pool
close(p.vmPool)
return nil
}
// RPC returns the RPC interface
func (p *Plugin) RPC() interface{} {
return &rpc{
plugin: p,
log: p.log,
}
}
// Collects declares plugin dependencies - collects metrics plugin if available
func (p *Plugin) Collects() []interface{} {
return []interface{}{
// Collect metrics plugin (optional dependency)
// This allows JavaScript to manipulate metrics registered in the metrics plugin
func(plugin interface{}) {
// Type assert to get access to the metrics plugin
// We need access to its internal collectors sync.Map
if mp, ok := plugin.(interface{ Name() string }); ok {
if mp.Name() == "metrics" {
// Use type assertion to access the internal structure
// This is safe because we control both plugins
if internal, ok := plugin.(interface {
GetCollectors() *sync.Map
}); ok {
p.metricsPlugin = &metricsPluginInternal{
collectors: *internal.GetCollectors(),
}
p.log.Info("metrics plugin collected, JavaScript can now access user metrics")
}
}
}
},
}
}
// acquireVM gets a VM from the pool
func (p *Plugin) acquireVM(ctx context.Context) (*otto.Otto, error) {
select {
case vm := <-p.vmPool:
return vm, nil
case <-ctx.Done():
return nil, ctx.Err()
case <-p.stopCh:
return nil, fmt.Errorf("plugin is shutting down")
}
}
// releaseVM returns a VM to the pool
func (p *Plugin) releaseVM(vm *otto.Otto) {
select {
case p.vmPool <- vm:
case <-p.stopCh:
// Plugin is shutting down, don't return to pool
}
}
// execute runs JavaScript code with timeout
func (p *Plugin) execute(ctx context.Context, script string, timeout time.Duration) (interface{}, error) {
p.wg.Add(1)
defer p.wg.Done()
start := time.Now()
var status string
defer func() {
duration := time.Since(start)
p.executionDuration.WithLabelValues(status).Observe(duration.Seconds())
p.executionsTotal.WithLabelValues(status).Inc()
}()
// Track code size
p.codeSize.Observe(float64(len(script)))
// Track active executions
p.activeExecutions.Inc()
defer p.activeExecutions.Dec()
// Ensure we have a valid context
if ctx == nil {
ctx = context.Background()
}
// Acquire VM from pool
p.poolAvailable.Dec()
vm, err := p.acquireVM(ctx)
if err != nil {
status = "error"
p.poolAvailable.Inc()
return nil, fmt.Errorf("failed to acquire VM: %w", err)
}
defer func() {
p.releaseVM(vm)
p.poolAvailable.Inc()
}()
// Create execution context with timeout
execCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Result channels
resultCh := make(chan otto.Value, 1)
errCh := make(chan error, 1)
// Execute JavaScript in goroutine
go func() {
defer func() {
if caught := recover(); caught != nil {
errCh <- fmt.Errorf("execution panic: %v", caught)
}
}()
value, err := vm.Run(script)
if err != nil {
errCh <- err
return
}
resultCh <- value
}()
// Timeout watchdog - only interrupt if context times out
go func() {
<-execCtx.Done()
if execCtx.Err() == context.DeadlineExceeded {
// Only interrupt on actual timeout, not cancellation
vm.Interrupt <- func() {
panic("execution timeout")
}
}
}()
// Wait for result or timeout
select {
case value := <-resultCh:
// Convert otto.Value to Go interface{}
exported, err := value.Export()
if err != nil {
status = "error"
return nil, fmt.Errorf("failed to export result: %w", err)
}
status = "success"
return exported, nil
case err := <-errCh:
status = "error"
return nil, fmt.Errorf("execution error: %w", err)
case <-execCtx.Done():
status = "timeout"
return nil, fmt.Errorf("execution timeout after %v", timeout)
}
}