-
Notifications
You must be signed in to change notification settings - Fork 41
/
frame_session.go
1184 lines (1026 loc) · 36.7 KB
/
frame_session.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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package common
import (
"context"
"encoding/json"
"errors"
"fmt"
"runtime"
"strings"
"sync"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/grafana/xk6-browser/k6ext"
"github.com/grafana/xk6-browser/log"
k6modules "go.k6.io/k6/js/modules"
k6metrics "go.k6.io/k6/metrics"
"github.com/chromedp/cdproto"
"github.com/chromedp/cdproto/browser"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/dom"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/inspector"
cdplog "github.com/chromedp/cdproto/log"
"github.com/chromedp/cdproto/network"
cdppage "github.com/chromedp/cdproto/page"
cdpruntime "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/cdproto/security"
"github.com/chromedp/cdproto/target"
)
const utilityWorldName = "__k6_browser_utility_world__"
// CPUProfile is used in throttleCPU.
type CPUProfile struct {
// rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).
Rate float64
}
/*
FrameSession is used for managing a frame's life-cycle, or in other words its full session.
It manages all the event listening while deferring the state storage to the Frame and FrameManager
structs.
*/
type FrameSession struct {
ctx context.Context
session session
page *Page
parent *FrameSession
manager *FrameManager
networkManager *NetworkManager
k6Metrics *k6ext.CustomMetrics
targetID target.ID
windowID browser.WindowID
// To understand the concepts of Isolated Worlds, Contexts and Frames and
// the relationship betwween them have a look at the following doc:
// https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/renderer/bindings/core/v8/V8BindingDesign.md
contextIDToContextMu sync.Mutex
contextIDToContext map[cdpruntime.ExecutionContextID]*ExecutionContext
isolatedWorlds map[string]bool
eventCh chan Event
childSessions map[cdp.FrameID]*FrameSession
vu k6modules.VU
logger *log.Logger
// logger that will properly serialize RemoteObject instances
serializer *log.Logger
// Keep a reference to the main frame span so we can end it
// when FrameSession.ctx is Done
mainFrameSpan trace.Span
}
// NewFrameSession initializes and returns a new FrameSession.
//
//nolint:funlen
func NewFrameSession(
ctx context.Context, s session, p *Page, parent *FrameSession, tid target.ID, l *log.Logger,
) (_ *FrameSession, err error) {
l.Debugf("NewFrameSession", "sid:%v tid:%v", s.ID(), tid)
k6Metrics := k6ext.GetCustomMetrics(ctx)
fs := FrameSession{
ctx: ctx, // TODO: create cancelable context that can be used to cancel and close all child sessions
session: s,
page: p,
parent: parent,
manager: p.frameManager,
targetID: tid,
contextIDToContextMu: sync.Mutex{},
contextIDToContext: make(map[cdpruntime.ExecutionContextID]*ExecutionContext),
isolatedWorlds: make(map[string]bool),
eventCh: make(chan Event),
childSessions: make(map[cdp.FrameID]*FrameSession),
vu: k6ext.GetVU(ctx),
k6Metrics: k6Metrics,
logger: l,
serializer: l.ConsoleLogFormatterSerializer(),
}
var parentNM *NetworkManager
if fs.parent != nil {
parentNM = fs.parent.networkManager
}
fs.networkManager, err = NewNetworkManager(ctx, k6Metrics, s, fs.manager, parentNM)
if err != nil {
l.Debugf("NewFrameSession:NewNetworkManager", "sid:%v tid:%v err:%v",
s.ID(), tid, err)
return nil, err
}
action := browser.GetWindowForTarget().WithTargetID(fs.targetID)
if fs.windowID, _, err = action.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
l.Debugf(
"NewFrameSession:GetWindowForTarget",
"sid:%v tid:%v err:%v",
s.ID(), tid, err)
return nil, fmt.Errorf("getting browser window ID: %w", err)
}
fs.initEvents()
if err = fs.initFrameTree(); err != nil {
l.Debugf(
"NewFrameSession:initFrameTree",
"sid:%v tid:%v err:%v",
s.ID(), tid, err)
return nil, err
}
if err = fs.initIsolatedWorld(utilityWorldName); err != nil {
l.Debugf(
"NewFrameSession:initIsolatedWorld",
"sid:%v tid:%v err:%v",
s.ID(), tid, err)
return nil, err
}
if err = fs.initOptions(); err != nil {
l.Debugf(
"NewFrameSession:initOptions",
"sid:%v tid:%v err:%v",
s.ID(), tid, err)
return nil, err
}
if err = fs.initDomains(); err != nil {
l.Debugf(
"NewFrameSession:initDomains",
"sid:%v tid:%v err:%v",
s.ID(), tid, err)
return nil, err
}
return &fs, nil
}
func (fs *FrameSession) emulateLocale() error {
action := emulation.SetLocaleOverride().WithLocale(fs.page.browserCtx.opts.Locale)
if err := action.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
if strings.Contains(err.Error(), "Another locale override is already in effect") {
return nil
}
return fmt.Errorf("emulating locale %q: %w", fs.page.browserCtx.opts.Locale, err)
}
return nil
}
func (fs *FrameSession) emulateTimezone() error {
action := emulation.SetTimezoneOverride(fs.page.browserCtx.opts.TimezoneID)
if err := action.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
if strings.Contains(err.Error(), "Timezone override is already in effect") {
return nil
}
return fmt.Errorf("emulating timezone %q: %w", fs.page.browserCtx.opts.TimezoneID, err)
}
return nil
}
func (fs *FrameSession) getNetworkManager() *NetworkManager {
return fs.networkManager
}
func (fs *FrameSession) initDomains() error {
actions := []Action{
// TODO: can we get rid of the following by doing DOM related stuff in JS instead?
dom.Enable(),
cdplog.Enable(),
cdpruntime.Enable(),
target.SetAutoAttach(true, true).WithFlatten(true),
}
for _, action := range actions {
if err := action.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
return fmt.Errorf("internal error while enabling %T: %w", action, err)
}
}
return nil
}
func (fs *FrameSession) initEvents() {
fs.logger.Debugf("NewFrameSession:initEvents",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
events := []string{
cdproto.EventInspectorTargetCrashed,
}
fs.session.on(fs.ctx, events, fs.eventCh)
if !fs.isMainFrame() {
fs.initRendererEvents()
}
go func() {
fs.logger.Debugf("NewFrameSession:initEvents:go",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
defer func() {
// If there is an active span for main frame,
// end it before exiting so it can be flushed
if fs.mainFrameSpan != nil {
fs.mainFrameSpan.End()
fs.mainFrameSpan = nil
}
fs.logger.Debugf("NewFrameSession:initEvents:go:return",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
}()
for {
select {
case <-fs.session.Done():
fs.logger.Debugf("FrameSession:initEvents:go:session.done",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
return
case <-fs.ctx.Done():
fs.logger.Debugf("FrameSession:initEvents:go:ctx.Done",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
return
case event := <-fs.eventCh:
switch ev := event.data.(type) {
case *inspector.EventTargetCrashed:
fs.onTargetCrashed(ev)
case *cdplog.EventEntryAdded:
fs.onLogEntryAdded(ev)
case *cdppage.EventFrameAttached:
fs.onFrameAttached(ev.FrameID, ev.ParentFrameID)
case *cdppage.EventFrameDetached:
fs.onFrameDetached(ev.FrameID, ev.Reason)
case *cdppage.EventFrameNavigated:
const initial = false
fs.onFrameNavigated(ev.Frame, initial)
case *cdppage.EventFrameRequestedNavigation:
fs.onFrameRequestedNavigation(ev)
case *cdppage.EventFrameStartedLoading:
fs.onFrameStartedLoading(ev.FrameID)
case *cdppage.EventFrameStoppedLoading:
fs.onFrameStoppedLoading(ev.FrameID)
case *cdppage.EventLifecycleEvent:
fs.onPageLifecycle(ev)
case *cdppage.EventNavigatedWithinDocument:
fs.onPageNavigatedWithinDocument(ev)
case *cdpruntime.EventConsoleAPICalled:
fs.onConsoleAPICalled(ev)
case *cdpruntime.EventExceptionThrown:
fs.onExceptionThrown(ev)
case *cdpruntime.EventExecutionContextCreated:
fs.onExecutionContextCreated(ev)
case *cdpruntime.EventExecutionContextDestroyed:
fs.onExecutionContextDestroyed(ev.ExecutionContextID)
case *cdpruntime.EventExecutionContextsCleared:
fs.onExecutionContextsCleared()
case *target.EventAttachedToTarget:
fs.onAttachedToTarget(ev)
case *target.EventDetachedFromTarget:
fs.onDetachedFromTarget(ev)
case *cdppage.EventJavascriptDialogOpening:
fs.onEventJavascriptDialogOpening(ev)
case *cdpruntime.EventBindingCalled:
fs.onEventBindingCalled(ev)
}
}
}
}()
}
func (fs *FrameSession) onEventBindingCalled(event *cdpruntime.EventBindingCalled) {
fs.logger.Debugf("FrameSessions:onEventBindingCalled",
"sid:%v tid:%v name:%s payload:%s",
fs.session.ID(), fs.targetID, event.Name, event.Payload)
err := fs.parseAndEmitWebVitalMetric(event.Payload)
if err != nil {
fs.logger.Errorf("FrameSession:onEventBindingCalled", "failed to emit web vital metric: %v", err)
}
}
func (fs *FrameSession) parseAndEmitWebVitalMetric(object string) error {
fs.logger.Debugf("FrameSession:parseAndEmitWebVitalMetric", "object:%s", object)
wv := struct {
ID string
Name string
Value json.Number
Rating string
Delta json.Number
NumEntries json.Number
NavigationType string
URL string
SpanID string
}{}
if err := json.Unmarshal([]byte(object), &wv); err != nil {
return fmt.Errorf("json couldn't be parsed: %w", err)
}
metric, ok := fs.k6Metrics.WebVitals[wv.Name]
if !ok {
return fmt.Errorf("metric not registered %q", wv.Name)
}
value, err := wv.Value.Float64()
if err != nil {
return fmt.Errorf("value couldn't be parsed %q", wv.Value)
}
state := fs.vu.State()
tags := state.Tags.GetCurrentValues().Tags
if state.Options.SystemTags.Has(k6metrics.TagURL) {
tags = tags.With("url", wv.URL)
}
tags = tags.With("rating", wv.Rating)
now := time.Now()
k6metrics.PushIfNotDone(fs.vu.Context(), state.Samples, k6metrics.ConnectedSamples{
Samples: []k6metrics.Sample{
{
TimeSeries: k6metrics.TimeSeries{Metric: metric, Tags: tags},
Value: value,
Time: now,
},
},
})
_, span := TraceEvent(
fs.ctx, fs.targetID.String(), "web_vital", wv.SpanID, trace.WithAttributes(
attribute.String("web_vital.name", wv.Name),
attribute.Float64("web_vital.value", value),
attribute.String("web_vital.rating", wv.Rating),
))
defer span.End()
return nil
}
func (fs *FrameSession) onEventJavascriptDialogOpening(event *cdppage.EventJavascriptDialogOpening) {
fs.logger.Debugf("FrameSession:onEventJavascriptDialogOpening",
"sid:%v tid:%v url:%v dialogType:%s",
fs.session.ID(), fs.targetID, event.URL, event.Type)
// Dialog type of beforeunload needs to accept the
// dialog, instead of dismissing it. We're unable to
// dismiss beforeunload dialog boxes at the moment as
// it seems to pause the exec of any other action on
// the page. I believe this is an issue in Chromium.
action := cdppage.HandleJavaScriptDialog(false)
if event.Type == cdppage.DialogTypeBeforeunload {
action = cdppage.HandleJavaScriptDialog(true)
}
if err := action.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
fs.logger.Errorf("FrameSession:onEventJavascriptDialogOpening", "failed to dismiss dialog box: %v", err)
}
}
func (fs *FrameSession) initFrameTree() error {
fs.logger.Debugf("NewFrameSession:initFrameTree",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
action := cdppage.Enable()
if err := action.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
return fmt.Errorf("enabling page domain: %w", err)
}
var frameTree *cdppage.FrameTree
var err error
// Recursively enumerate all existing frames in page to create initial in-memory structures
// used for access and manipulation from JS.
action2 := cdppage.GetFrameTree()
if frameTree, err = action2.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
return fmt.Errorf("getting page frame tree: %w", err)
} else if frameTree == nil {
// This can happen with very short scripts when we might not have enough
// time to initialize properly.
return fmt.Errorf("got a nil page frame tree")
}
if fs.isMainFrame() {
fs.handleFrameTree(frameTree)
fs.initRendererEvents()
}
return nil
}
func (fs *FrameSession) initIsolatedWorld(name string) error {
fs.logger.Debugf("NewFrameSession:initIsolatedWorld",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
action := cdppage.SetLifecycleEventsEnabled(true)
if err := action.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
return fmt.Errorf("enabling page lifecycle events: %w", err)
}
if _, ok := fs.isolatedWorlds[name]; ok {
fs.logger.Debugf("NewFrameSession:initIsolatedWorld",
"sid:%v tid:%v, not found: %q",
fs.session.ID(), fs.targetID, name)
return nil
}
fs.isolatedWorlds[name] = true
var frames []*Frame
if fs.isMainFrame() {
frames = fs.manager.Frames()
} else {
frames = []*Frame{fs.manager.getFrameByID(cdp.FrameID(fs.targetID))}
}
for _, frame := range frames {
// A frame could have been removed before we execute this, so don't wait around for a reply.
_ = fs.session.ExecuteWithoutExpectationOnReply(
fs.ctx,
cdppage.CommandCreateIsolatedWorld,
&cdppage.CreateIsolatedWorldParams{
FrameID: cdp.FrameID(frame.ID()),
WorldName: name,
GrantUniveralAccess: true,
},
nil)
}
fs.logger.Debugf("NewFrameSession:initIsolatedWorld:AddScriptToEvaluateOnNewDocument",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
action2 := cdppage.AddScriptToEvaluateOnNewDocument(`//# sourceURL=` + evaluationScriptURL).
WithWorldName(name)
if _, err := action2.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
return fmt.Errorf("adding script to evaluate on new document: %w", err)
}
return nil
}
func (fs *FrameSession) initOptions() error {
fs.logger.Debugf("NewFrameSession:initOptions",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
var (
opts = fs.manager.page.browserCtx.opts
optActions = []Action{}
state = fs.vu.State()
)
if fs.isMainFrame() {
optActions = append(optActions, emulation.SetFocusEmulationEnabled(true))
if err := fs.updateViewport(); err != nil {
fs.logger.Debugf("NewFrameSession:initOptions:updateViewport",
"sid:%v tid:%v, err:%v",
fs.session.ID(), fs.targetID, err)
return err
}
}
if opts.BypassCSP {
optActions = append(optActions, cdppage.SetBypassCSP(true))
}
if opts.IgnoreHTTPSErrors {
optActions = append(optActions, security.SetIgnoreCertificateErrors(true))
}
if opts.HasTouch {
optActions = append(optActions, emulation.SetTouchEmulationEnabled(true))
}
if !opts.JavaScriptEnabled {
optActions = append(optActions, emulation.SetScriptExecutionDisabled(true))
}
if opts.UserAgent != "" || opts.Locale != "" {
optActions = append(optActions, emulation.SetUserAgentOverride(opts.UserAgent).WithAcceptLanguage(opts.Locale))
}
if opts.Locale != "" {
if err := fs.emulateLocale(); err != nil {
return err
}
}
if opts.TimezoneID != "" {
if err := fs.emulateTimezone(); err != nil {
return err
}
}
if err := fs.updateGeolocation(true); err != nil {
return err
}
fs.updateExtraHTTPHeaders(true)
var reqIntercept bool
if state.Options.BlockedHostnames.Trie != nil ||
len(state.Options.BlacklistIPs) > 0 {
reqIntercept = true
}
if err := fs.updateRequestInterception(reqIntercept); err != nil {
return err
}
fs.updateOffline(true)
fs.updateHTTPCredentials(true)
if err := fs.updateEmulateMedia(true); err != nil {
return err
}
// if (screencastOptions)
// promises.push(this._startVideoRecording(screencastOptions));
/*for (const source of this._crPage._browserContext._evaluateOnNewDocumentSources)
promises.push(this._evaluateOnNewDocument(source, 'main'));
for (const source of this._crPage._page._evaluateOnNewDocumentSources)
promises.push(this._evaluateOnNewDocument(source, 'main'));*/
optActions = append(optActions, cdpruntime.RunIfWaitingForDebugger())
for _, action := range optActions {
if err := action.Do(cdp.WithExecutor(fs.ctx, fs.session)); err != nil {
return fmt.Errorf("internal error while initializing frame %T: %w", action, err)
}
}
return nil
}
func (fs *FrameSession) initRendererEvents() {
fs.logger.Debugf("NewFrameSession:initEvents:initRendererEvents",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
events := []string{
cdproto.EventLogEntryAdded,
cdproto.EventPageFileChooserOpened,
cdproto.EventPageFrameAttached,
cdproto.EventPageFrameDetached,
cdproto.EventPageFrameNavigated,
cdproto.EventPageFrameRequestedNavigation,
cdproto.EventPageFrameStartedLoading,
cdproto.EventPageFrameStoppedLoading,
cdproto.EventPageJavascriptDialogOpening,
cdproto.EventPageLifecycleEvent,
cdproto.EventPageNavigatedWithinDocument,
cdproto.EventRuntimeConsoleAPICalled,
cdproto.EventRuntimeExceptionThrown,
cdproto.EventRuntimeExecutionContextCreated,
cdproto.EventRuntimeExecutionContextDestroyed,
cdproto.EventRuntimeExecutionContextsCleared,
cdproto.EventTargetAttachedToTarget,
cdproto.EventTargetDetachedFromTarget,
cdproto.EventRuntimeBindingCalled,
}
fs.session.on(fs.ctx, events, fs.eventCh)
}
func (fs *FrameSession) isMainFrame() bool {
return fs.targetID == fs.page.targetID
}
func (fs *FrameSession) handleFrameTree(frameTree *cdppage.FrameTree) {
fs.logger.Debugf("FrameSession:handleFrameTree",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
if frameTree.Frame.ParentID != "" {
fs.onFrameAttached(frameTree.Frame.ID, frameTree.Frame.ParentID)
}
fs.onFrameNavigated(frameTree.Frame, true)
if frameTree.ChildFrames == nil {
return
}
for _, child := range frameTree.ChildFrames {
fs.handleFrameTree(child)
}
}
func (fs *FrameSession) navigateFrame(frame *Frame, url, referrer string) (string, error) {
fs.logger.Debugf("FrameSession:navigateFrame",
"sid:%v fid:%s tid:%v url:%q referrer:%q",
fs.session.ID(), frame.ID(), fs.targetID, url, referrer)
action := cdppage.Navigate(url).WithReferrer(referrer).WithFrameID(cdp.FrameID(frame.ID()))
_, documentID, errorText, err := action.Do(cdp.WithExecutor(fs.ctx, fs.session))
if err != nil {
if errorText == "" {
err = fmt.Errorf("%w", err)
} else {
err = fmt.Errorf("%q: %w", errorText, err)
}
}
return documentID.String(), err
}
func (fs *FrameSession) onConsoleAPICalled(event *cdpruntime.EventConsoleAPICalled) {
l := fs.serializer.
WithTime(event.Timestamp.Time()).
WithField("source", "browser").
WithField("browser_source", "console-api")
/* accessing the state Group while not on the eventloop is racy
if s := fs.vu.State(); s.Group.Path != "" {
l = l.WithField("group", s.Group.Path)
}
*/
parsedObjects := make([]string, 0, len(event.Args))
for _, robj := range event.Args {
s := parseConsoleRemoteObject(fs.logger, robj)
parsedObjects = append(parsedObjects, s)
}
l = l.WithField("stringObjects", parsedObjects)
switch event.Type {
case "log", "info":
l.Info()
case "warning":
l.Warn()
case "error":
l.Error()
default:
l.Debug()
}
}
func (fs *FrameSession) onExceptionThrown(event *cdpruntime.EventExceptionThrown) {
fs.page.emit(EventPageError, event.ExceptionDetails)
}
func (fs *FrameSession) onExecutionContextCreated(event *cdpruntime.EventExecutionContextCreated) {
fs.logger.Debugf("FrameSession:onExecutionContextCreated",
"sid:%v tid:%v ectxid:%d",
fs.session.ID(), fs.targetID, event.Context.ID)
auxData := event.Context.AuxData
var i struct {
FrameID cdp.FrameID `json:"frameId"`
IsDefault bool `json:"isDefault"`
Type string `json:"type"`
}
if err := json.Unmarshal(auxData, &i); err != nil {
k6ext.Panic(fs.ctx, "unmarshaling executionContextCreated event JSON: %w", err)
}
var world executionWorld
frame := fs.manager.getFrameByID(i.FrameID)
if frame != nil {
if i.IsDefault {
world = mainWorld
} else if event.Context.Name == utilityWorldName && !frame.hasContext(utilityWorld) {
// In case of multiple sessions to the same target, there's a race between
// connections so we might end up creating multiple isolated worlds.
// We can use either.
world = utilityWorld
}
}
if i.Type == "isolated" {
fs.isolatedWorlds[event.Context.Name] = true
}
context := NewExecutionContext(fs.ctx, fs.session, frame, event.Context.ID, fs.logger)
if world != "" {
fs.logger.Debugf("FrameSession:setContext",
"sid:%v fid:%v ectxid:%d",
fs.session.ID(), frame.ID(), event.Context.ID)
frame.setContext(world, context)
}
fs.contextIDToContextMu.Lock()
fs.contextIDToContext[event.Context.ID] = context
fs.contextIDToContextMu.Unlock()
}
func (fs *FrameSession) onExecutionContextDestroyed(execCtxID cdpruntime.ExecutionContextID) {
fs.logger.Debugf("FrameSession:onExecutionContextDestroyed",
"sid:%v tid:%v ectxid:%d",
fs.session.ID(), fs.targetID, execCtxID)
fs.contextIDToContextMu.Lock()
defer fs.contextIDToContextMu.Unlock()
context, ok := fs.contextIDToContext[execCtxID]
if !ok {
return
}
if context.Frame() != nil {
context.Frame().nullContext(execCtxID)
}
delete(fs.contextIDToContext, execCtxID)
}
func (fs *FrameSession) onExecutionContextsCleared() {
fs.logger.Debugf("FrameSession:onExecutionContextsCleared",
"sid:%v tid:%v", fs.session.ID(), fs.targetID)
fs.contextIDToContextMu.Lock()
defer fs.contextIDToContextMu.Unlock()
for _, context := range fs.contextIDToContext {
if context.Frame() != nil {
context.Frame().nullContext(context.id)
}
}
for k := range fs.contextIDToContext {
delete(fs.contextIDToContext, k)
}
}
func (fs *FrameSession) onFrameAttached(frameID cdp.FrameID, parentFrameID cdp.FrameID) {
fs.logger.Debugf("FrameSession:onFrameAttached",
"sid:%v tid:%v fid:%v pfid:%v",
fs.session.ID(), fs.targetID, frameID, parentFrameID)
// TODO: add handling for cross-process frame transitioning
fs.manager.frameAttached(frameID, parentFrameID)
}
func (fs *FrameSession) onFrameDetached(frameID cdp.FrameID, reason cdppage.FrameDetachedReason) {
fs.logger.Debugf("FrameSession:onFrameDetached",
"sid:%v tid:%v fid:%v reason:%s",
fs.session.ID(), fs.targetID, frameID, reason)
fs.manager.frameDetached(frameID, reason)
}
func (fs *FrameSession) onFrameNavigated(frame *cdp.Frame, initial bool) {
fs.logger.Debugf("FrameSession:onFrameNavigated",
"sid:%v tid:%v fid:%v",
fs.session.ID(), fs.targetID, frame.ID)
err := fs.manager.frameNavigated(
frame.ID, frame.ParentID, frame.LoaderID.String(),
frame.Name, frame.URL+frame.URLFragment, initial)
if err != nil {
k6ext.Panic(fs.ctx, "handling frameNavigated event to %q: %w",
frame.URL+frame.URLFragment, err)
}
// Trace navigation only for the main frame.
// TODO: How will this affect sub frames such as iframes?
if isMainFrame := frame.ParentID == ""; !isMainFrame {
return
}
_, fs.mainFrameSpan = TraceNavigation(
fs.ctx, fs.targetID.String(), frame.URL,
trace.WithAttributes(attribute.String("navigation.url", frame.URL)),
)
var (
spanID = fs.mainFrameSpan.SpanContext().SpanID().String()
newFrame = fs.manager.getFrameByID(frame.ID)
)
// Only set the k6SpanId reference if it's a new frame.
if newFrame == nil {
return
}
// Set k6SpanId property in the page so it can be retrieved when pushing
// the Web Vitals events from the page execution context and used to
// correlate them with the navigation span to which they belong to.
setSpanIDProp := func() {
js := fmt.Sprintf("window.k6SpanId = '%s';", spanID)
err := newFrame.EvaluateGlobal(fs.ctx, js)
if err != nil {
fs.logger.Errorf(
"FrameSession:onFrameNavigated", "error on evaluating window.k6SpanId: %v", err,
)
}
}
// Executing a CDP command in the event parsing goroutine might deadlock in some cases.
// For example a deadlock happens if the content loaded in the frame that has navigated
// includes a JavaScript initiated dialog which we have to explicitly accept or dismiss
// (see onEventJavascriptDialogOpening). In that case our EvaluateGlobal call can't be
// executed, as the browser is waiting for us to accept/dismiss the JS dialog, but we
// can't act on that because the event parsing goroutine is stuck in onFrameNavigated.
// Because in this case the action is to set an attribute to the global object (window)
// it should be safe to just execute this in a separate goroutine.
go setSpanIDProp()
}
func (fs *FrameSession) onFrameRequestedNavigation(event *cdppage.EventFrameRequestedNavigation) {
fs.logger.Debugf("FrameSession:onFrameRequestedNavigation",
"sid:%v tid:%v fid:%v url:%q",
fs.session.ID(), fs.targetID, event.FrameID, event.URL)
if event.Disposition == "currentTab" {
err := fs.manager.frameRequestedNavigation(event.FrameID, event.URL, "")
if err != nil {
k6ext.Panic(fs.ctx, "handling frameRequestedNavigation event to %q: %w", event.URL, err)
}
}
}
func (fs *FrameSession) onFrameStartedLoading(frameID cdp.FrameID) {
fs.logger.Debugf("FrameSession:onFrameStartedLoading",
"sid:%v tid:%v fid:%v",
fs.session.ID(), fs.targetID, frameID)
fs.manager.frameLoadingStarted(frameID)
}
func (fs *FrameSession) onFrameStoppedLoading(frameID cdp.FrameID) {
fs.logger.Debugf("FrameSession:onFrameStoppedLoading",
"sid:%v tid:%v fid:%v",
fs.session.ID(), fs.targetID, frameID)
fs.manager.frameLoadingStopped(frameID)
}
func (fs *FrameSession) onLogEntryAdded(event *cdplog.EventEntryAdded) {
l := fs.logger.
WithTime(event.Entry.Timestamp.Time()).
WithField("source", "browser").
WithField("url", event.Entry.URL).
WithField("browser_source", event.Entry.Source.String()).
WithField("line_number", event.Entry.LineNumber)
/* accessing the state Group while not on the eventloop is racy
if s := fs.vu.State(); s.Group.Path != "" {
l = l.WithField("group", s.Group.Path)
}
*/
switch event.Entry.Level {
case "info":
l.Info(event.Entry.Text)
case "warning":
l.Warn(event.Entry.Text)
case "error":
l.WithField("stacktrace", event.Entry.StackTrace).Error(event.Entry.Text)
default:
l.Debug(event.Entry.Text)
}
}
func (fs *FrameSession) onPageLifecycle(event *cdppage.EventLifecycleEvent) {
fs.logger.Debugf("FrameSession:onPageLifecycle",
"sid:%v tid:%v fid:%v event:%s eventTime:%q",
fs.session.ID(), fs.targetID, event.FrameID, event.Name, event.Timestamp.Time())
frame := fs.manager.getFrameByID(event.FrameID)
if frame == nil {
return
}
switch event.Name {
case "load":
fs.manager.frameLifecycleEvent(event.FrameID, LifecycleEventLoad)
case "DOMContentLoaded":
fs.manager.frameLifecycleEvent(event.FrameID, LifecycleEventDOMContentLoad)
case "networkIdle":
fs.manager.frameLifecycleEvent(event.FrameID, LifecycleEventNetworkIdle)
}
}
func (fs *FrameSession) onPageNavigatedWithinDocument(event *cdppage.EventNavigatedWithinDocument) {
fs.logger.Debugf("FrameSession:onPageNavigatedWithinDocument",
"sid:%v tid:%v fid:%v",
fs.session.ID(), fs.targetID, event.FrameID)
fs.manager.frameNavigatedWithinDocument(event.FrameID, event.URL)
}
func (fs *FrameSession) onAttachedToTarget(event *target.EventAttachedToTarget) {
var (
ti = event.TargetInfo
sid = event.SessionID
err error
)
fs.logger.Debugf("FrameSession:onAttachedToTarget",
"sid:%v tid:%v esid:%v etid:%v ebctxid:%v type:%q",
fs.session.ID(), fs.targetID, event.SessionID,
event.TargetInfo.TargetID, event.TargetInfo.BrowserContextID,
event.TargetInfo.Type)
session := fs.page.browserCtx.getSession(event.SessionID)
if session == nil {
fs.logger.Debugf("FrameSession:onAttachedToTarget:NewFrameSession",
"sid:%v tid:%v esid:%v etid:%v ebctxid:%v type:%q err:nil session",
fs.session.ID(), fs.targetID, event.SessionID,
event.TargetInfo.TargetID, event.TargetInfo.BrowserContextID,
event.TargetInfo.Type)
return
}
switch ti.Type {
case "iframe":
err = fs.attachIFrameToTarget(ti, sid)
case "worker":
err = fs.attachWorkerToTarget(ti, sid)
default:
// Just unblock (debugger continue) these targets and detach from them.
s := fs.page.browserCtx.getSession(sid)
_ = s.ExecuteWithoutExpectationOnReply(fs.ctx, cdpruntime.CommandRunIfWaitingForDebugger, nil, nil)
_ = s.ExecuteWithoutExpectationOnReply(fs.ctx, target.CommandDetachFromTarget,
&target.DetachFromTargetParams{SessionID: s.id}, nil)
}
if err == nil {
return
}
// Handle or ignore errors.
var reason string
defer func() {
fs.logger.Debugf("FrameSession:onAttachedToTarget:return",
"sid:%v tid:%v esid:%v etid:%v ebctxid:%v type:%q reason:%s",
fs.session.ID(), fs.targetID, sid,
ti.TargetID, ti.BrowserContextID,
ti.Type, reason)
}()
// Ignore errors if we're no longer connected to browser.
// This happens when there is no browser but we still want to
// attach a frame/worker to it.
if !fs.page.browserCtx.browser.IsConnected() {
reason = "browser disconnected"
return // ignore
}
// Final chance:
// Ignore the error if the context was canceled, otherwise,
// throw a k6 error.
select {
case <-fs.ctx.Done():
reason = "frame session context canceled"
return
case <-session.done:
reason = "session closed"
return
default:
// Ignore context canceled error to gracefully handle shutting down
// of the extension. This may happen because of generated events
// while a frame session is being created.
if errors.Is(err, context.Canceled) {
reason = "context canceled"
return // ignore
}
reason = "fatal"
k6ext.Panic(fs.ctx, "attaching %v: %w", ti.Type, err)
}
}
// attachIFrameToTarget attaches an IFrame target to a given session.
func (fs *FrameSession) attachIFrameToTarget(ti *target.Info, sid target.SessionID) error {
fr := fs.manager.getFrameByID(cdp.FrameID(ti.TargetID))
if fr == nil {
// IFrame should be attached to fs.page with EventFrameAttached
// event before.
fs.logger.Debugf("FrameSession:attachIFrameToTarget:return",
"sid:%v tid:%v esid:%v etid:%v ebctxid:%v type:%q, nil frame",
fs.session.ID(), fs.targetID,
sid, ti.TargetID, ti.BrowserContextID, ti.Type)
return nil
}
// Remove all children of the previously attached frame.
fs.manager.removeChildFramesRecursively(fr)
nfs, err := NewFrameSession(
fs.ctx,
fs.page.browserCtx.getSession(sid),
fs.page, fs, ti.TargetID,
fs.logger)
if err != nil {
return fmt.Errorf("attaching iframe target ID %v to session ID %v: %w",
ti.TargetID, sid, err)
}
fs.page.attachFrameSession(cdp.FrameID(ti.TargetID), nfs)
return nil
}
// attachWorkerToTarget attaches a Worker target to a given session.
func (fs *FrameSession) attachWorkerToTarget(ti *target.Info, sid target.SessionID) error {
w, err := NewWorker(fs.ctx, fs.page.browserCtx.getSession(sid), ti.TargetID, ti.URL)
if err != nil {
return fmt.Errorf("attaching worker target ID %v to session ID %v: %w",
ti.TargetID, sid, err)
}
fs.page.workers[sid] = w
return nil
}
func (fs *FrameSession) onDetachedFromTarget(event *target.EventDetachedFromTarget) {
fs.logger.Debugf("FrameSession:onDetachedFromTarget",
"sid:%v tid:%v esid:%v",
fs.session.ID(), fs.targetID, event.SessionID)