-
Notifications
You must be signed in to change notification settings - Fork 41
/
execution_context.go
355 lines (307 loc) · 9.41 KB
/
execution_context.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
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
package common
import (
"context"
_ "embed"
"errors"
"fmt"
"regexp"
"sync"
"github.com/grafana/xk6-browser/k6ext"
"github.com/grafana/xk6-browser/log"
k6modules "go.k6.io/k6/js/modules"
"github.com/chromedp/cdproto"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/dom"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/cdproto/target"
)
const evaluationScriptURL = "__xk6_browser_evaluation_script__"
// This error code originates from chromium.
const devToolsServerErrorCode = -32000
var sourceURLRegex = regexp.MustCompile(`^(?s)[\040\t]*//[@#] sourceURL=\s*(\S*?)\s*$`)
type executionWorld string
const (
mainWorld executionWorld = "main"
utilityWorld executionWorld = "utility"
)
func (ew executionWorld) valid() bool {
return ew == mainWorld || ew == utilityWorld
}
type evalOptions struct {
forceCallable, returnByValue bool
}
func (ea evalOptions) String() string {
return fmt.Sprintf("forceCallable:%t returnByValue:%t", ea.forceCallable, ea.returnByValue)
}
// ExecutionContext represents a JS execution context.
type ExecutionContext struct {
ctx context.Context
logger *log.Logger
session session
frame *Frame
id runtime.ExecutionContextID
isMutex sync.RWMutex
injectedScript JSHandleAPI
vu k6modules.VU
// Used for logging
sid target.SessionID // Session ID
stid cdp.FrameID // Session TargetID
fid cdp.FrameID // Frame ID
furl string // Frame URL
}
// NewExecutionContext creates a new JS execution context.
func NewExecutionContext(
ctx context.Context, s session, f *Frame, id runtime.ExecutionContextID, l *log.Logger,
) *ExecutionContext {
e := &ExecutionContext{
ctx: ctx,
session: s,
frame: f,
id: id,
injectedScript: nil,
vu: k6ext.GetVU(ctx),
logger: l,
}
if s != nil {
e.sid = s.ID()
e.stid = cdp.FrameID(s.TargetID())
}
if f != nil {
e.fid = cdp.FrameID(f.ID())
e.furl = f.URL()
}
l.Debugf(
"NewExecutionContext",
"sid:%s stid:%s fid:%s ectxid:%d furl:%q",
e.sid, e.stid, e.fid, id, e.furl)
return e
}
// Adopts specified backend node into this execution context from another execution context.
func (e *ExecutionContext) adoptBackendNodeID(backendNodeID cdp.BackendNodeID) (*ElementHandle, error) {
e.logger.Debugf(
"ExecutionContext:adoptBackendNodeID",
"sid:%s stid:%s fid:%s ectxid:%d furl:%q bnid:%d",
e.sid, e.stid, e.fid, e.id, e.furl, backendNodeID)
var (
remoteObj *runtime.RemoteObject
err error
)
action := dom.ResolveNode().
WithBackendNodeID(backendNodeID).
WithExecutionContextID(e.id)
if remoteObj, err = action.Do(cdp.WithExecutor(e.ctx, e.session)); err != nil {
return nil, fmt.Errorf("resolving DOM node: %w", err)
}
return NewJSHandle(e.ctx, e.session, e, e.frame, remoteObj, e.logger).AsElement(), nil
}
// Adopts the specified element handle into this execution context from another execution context.
func (e *ExecutionContext) adoptElementHandle(eh *ElementHandle) (*ElementHandle, error) {
var (
efid cdp.FrameID
esid target.SessionID
)
if eh.frame != nil {
efid = cdp.FrameID(eh.frame.ID())
}
if eh.session != nil {
esid = eh.session.ID()
}
e.logger.Debugf(
"ExecutionContext:adoptElementHandle",
"sid:%s stid:%s fid:%s ectxid:%d furl:%q ehtid:%s ehsid:%s",
e.sid, e.stid, e.fid, e.id, e.furl,
efid, esid)
if eh.execCtx == e {
return nil, errors.New("already belongs to the same execution context")
}
if e.frame == nil {
return nil, errors.New("does not have a frame owner")
}
var node *cdp.Node
var err error
action := dom.DescribeNode().WithObjectID(eh.remoteObject.ObjectID)
if node, err = action.Do(cdp.WithExecutor(e.ctx, e.session)); err != nil {
return nil, fmt.Errorf("describing DOM node: %w", err)
}
return e.adoptBackendNodeID(node.BackendNodeID)
}
// eval evaluates the provided JavaScript within this execution context and
// returns a value or handle.
func (e *ExecutionContext) eval(
apiCtx context.Context, opts evalOptions, js string, args ...any,
) (any, error) {
if escapesGojaValues(args...) {
return nil, errors.New("goja.Value escaped")
}
e.logger.Debugf(
"ExecutionContext:eval",
"sid:%s stid:%s fid:%s ectxid:%d furl:%q %s",
e.sid, e.stid, e.fid, e.id, e.furl, opts)
suffix := `//# sourceURL=` + evaluationScriptURL
var action interface {
Do(context.Context) (*runtime.RemoteObject, *runtime.ExceptionDetails, error)
}
if !opts.forceCallable {
if !sourceURLRegex.Match([]byte(js)) {
js += "\n" + suffix
}
action = runtime.Evaluate(js).
WithContextID(e.id).
WithReturnByValue(opts.returnByValue).
WithAwaitPromise(true).
WithUserGesture(true)
} else {
var arguments []*runtime.CallArgument
for _, arg := range args {
result, err := convertArgument(apiCtx, e, arg)
if err != nil {
return nil, fmt.Errorf("converting argument %q "+
"in execution context ID %d and frame ID %v: %w",
arg, e.id, e.Frame().ID(), err)
}
arguments = append(arguments, result)
}
js += "\n" + suffix + "\n"
action = runtime.CallFunctionOn(js).
WithArguments(arguments).
WithExecutionContextID(e.id).
WithReturnByValue(opts.returnByValue).
WithAwaitPromise(true).
WithUserGesture(true)
}
var (
remoteObject *runtime.RemoteObject
exceptionDetails *runtime.ExceptionDetails
err error
)
if remoteObject, exceptionDetails, err = action.Do(cdp.WithExecutor(apiCtx, e.session)); err != nil {
var cdpe *cdproto.Error
if errors.As(err, &cdpe) && cdpe.Code == devToolsServerErrorCode {
// By creating a new error instead of reusing it, we're removing the
// chromium specific error code.
return nil, errors.New(cdpe.Message)
}
e.logger.Warnf("ExecutionContext:eval", "Unexpected DevTools server error: %v", err)
return nil, err
}
if exceptionDetails != nil {
return nil, fmt.Errorf("%s", parseExceptionDetails(exceptionDetails))
}
var res any
if remoteObject == nil {
e.logger.Debugf(
"ExecutionContext:eval",
"sid:%s stid:%s fid:%s ectxid:%d furl:%q remoteObject is nil",
e.sid, e.stid, e.fid, e.id, e.furl)
return res, nil
}
if opts.returnByValue {
res, err = valueFromRemoteObject(apiCtx, remoteObject)
if err != nil {
return nil, fmt.Errorf(
"extracting value from remote object with ID %s: %w",
remoteObject.ObjectID, err)
}
} else if remoteObject.ObjectID != "" {
// Note: we don't use the passed in apiCtx here as it could be tied to a timeout
res = NewJSHandle(e.ctx, e.session, e, e.frame, remoteObject, e.logger)
}
return res, nil
}
// Based on: https://github.com/microsoft/playwright/blob/master/src/server/injected/injectedScript.ts
//
//go:embed js/injected_script.js
var injectedScriptSource string
// getInjectedScript returns a JS handle to the injected script of helper functions.
func (e *ExecutionContext) getInjectedScript(apiCtx context.Context) (JSHandleAPI, error) {
e.logger.Debugf(
"ExecutionContext:getInjectedScript",
"sid:%s stid:%s fid:%s ectxid:%d efurl:%s",
e.sid, e.stid, e.fid, e.id, e.furl)
e.isMutex.RLock()
if e.injectedScript != nil {
injectedScript := e.injectedScript
e.isMutex.RUnlock()
return injectedScript, nil
}
e.isMutex.RUnlock()
var (
suffix = `//# sourceURL=` + evaluationScriptURL
source = fmt.Sprintf(`(() => {%s; return new InjectedScript();})()`, injectedScriptSource)
expression = source
expressionWithSourceURL = expression
)
if !sourceURLRegex.Match([]byte(expression)) {
expressionWithSourceURL = expression + "\n" + suffix
}
handle, err := e.eval(
apiCtx,
evalOptions{forceCallable: false, returnByValue: false},
expressionWithSourceURL,
)
if err != nil {
return nil, err
}
if handle == nil {
return nil, errors.New("handle is nil")
}
injectedScript, ok := handle.(JSHandleAPI)
if !ok {
return nil, ErrJSHandleInvalid
}
e.isMutex.Lock()
e.injectedScript = injectedScript
e.isMutex.Unlock()
return injectedScript, nil
}
// Eval evaluates the provided JavaScript within this execution context and
// returns a value or handle.
func (e *ExecutionContext) Eval(apiCtx context.Context, js string, args ...any) (any, error) {
if escapesGojaValues(args...) {
return nil, errors.New("goja.Value escaped")
}
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
evalArgs := make([]any, 0, len(args))
for _, a := range args {
evalArgs = append(evalArgs, a)
}
return e.eval(apiCtx, opts, js, evalArgs...)
}
// EvalHandle evaluates the provided JavaScript within this execution context
// and returns a JSHandle.
func (e *ExecutionContext) EvalHandle(apiCtx context.Context, js string, args ...any) (JSHandleAPI, error) {
if escapesGojaValues(args...) {
return nil, errors.New("goja.Value escaped")
}
opts := evalOptions{
forceCallable: true,
returnByValue: false,
}
evalArgs := make([]any, 0, len(args))
for _, a := range args {
evalArgs = append(evalArgs, a)
}
res, err := e.eval(apiCtx, opts, js, evalArgs...)
if err != nil {
return nil, err
}
if res == nil {
return nil, errors.New("nil result")
}
r, ok := res.(JSHandleAPI)
if !ok {
return nil, ErrJSHandleInvalid
}
return r, nil
}
// Frame returns the frame that this execution context belongs to.
func (e *ExecutionContext) Frame() *Frame {
return e.frame
}
// ID returns the CDP runtime ID of this execution context.
func (e *ExecutionContext) ID() runtime.ExecutionContextID {
return e.id
}