Skip to content

Commit

Permalink
Move logger up to browser type
Browse files Browse the repository at this point in the history
* This way we can attach the logger to the browser process.

* This also enables the debug mode on the supplied logger
  when the debug launch options enables it. So that the
  components in the chain can detect this. For example,
  connection only finds a targetID in debug mode for
  logging purposes.
  • Loading branch information
inancgumus committed Nov 25, 2021
1 parent 5fa232e commit aebddcb
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 26 deletions.
29 changes: 19 additions & 10 deletions chromium/browser_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ import (
"context"
"errors"
"fmt"
"regexp"

"github.com/dop251/goja"
"github.com/grafana/xk6-browser/api"
"github.com/grafana/xk6-browser/common"
k6common "go.k6.io/k6/js/common"
k6lib "go.k6.io/k6/lib"
)

// Ensure BrowserType implements the api.BrowserType interface.
Expand Down Expand Up @@ -62,7 +64,7 @@ func NewBrowserType(ctx context.Context) api.BrowserType {

func (b *BrowserType) Connect(opts goja.Value) {
rt := k6common.GetRuntime(b.Ctx)
k6common.Throw(rt, errors.New("BrowserType.connect() has not been implemented yet!"))
k6common.Throw(rt, errors.New("BrowserType.connect() has not been implemented yet"))
}

func (b *BrowserType) ExecutablePath() string {
Expand All @@ -75,9 +77,20 @@ func (b *BrowserType) Launch(opts goja.Value) api.Browser {

launchOpts := common.NewLaunchOptions()
launchOpts.Parse(b.Ctx, opts)

b.Ctx = common.WithLaunchOptions(b.Ctx, launchOpts)

// create an extension wide logger
reCategoryFilter, _ := regexp.Compile(launchOpts.LogCategoryFilter)
logger := common.NewLogger(b.Ctx, k6lib.GetState(b.Ctx).Logger, launchOpts.Debug, reCategoryFilter)
if launchOpts.Debug {
logger.EnableDebugMode()
}

envs := make([]string, len(launchOpts.Env))
for k, v := range launchOpts.Env {
envs = append(envs, fmt.Sprintf("%s=%s", k, v))
}

flags := map[string]interface{}{
//chromedp.ProxyServer(""),
//chromedp.UserAgent(""),
Expand Down Expand Up @@ -117,23 +130,19 @@ func (b *BrowserType) Launch(opts goja.Value) api.Browser {
"use-mock-keychain": true,
"no-startup-window": true,
}

envs := make([]string, len(launchOpts.Env))
for k, v := range launchOpts.Env {
envs = append(envs, fmt.Sprintf("%s=%s", k, v))
}

allocator := NewAllocator(flags, envs)
browserProc, err := allocator.Allocate(b.Ctx, launchOpts)
if browserProc == nil {
k6common.Throw(rt, fmt.Errorf("unable to allocate browser: %w", err))
}

browserProc.AttachLogger(logger)

// attach the browser process ID to the context
// so that we can kill it afterward if it lingers
// see: k6Throw function
b.Ctx = common.WithProcessID(b.Ctx, browserProc.Pid())
browser, err := common.NewBrowser(b.Ctx, b.CancelFn, browserProc, launchOpts)
browser, err := common.NewBrowser(b.Ctx, b.CancelFn, browserProc, launchOpts, logger)
if err != nil {
k6common.Throw(rt, err)
}
Expand All @@ -142,7 +151,7 @@ func (b *BrowserType) Launch(opts goja.Value) api.Browser {

func (b *BrowserType) LaunchPersistentContext(userDataDir string, opts goja.Value) api.Browser {
rt := k6common.GetRuntime(b.Ctx)
k6common.Throw(rt, errors.New("BrowserType.LaunchPersistentContext(userDataDir, opts) has not been implemented yet!"))
k6common.Throw(rt, errors.New("BrowserType.LaunchPersistentContext(userDataDir, opts) has not been implemented yet"))
return nil
}

Expand Down
24 changes: 8 additions & 16 deletions common/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ package common
import (
"context"
"fmt"
"regexp"
"strings"
"sync"
"sync/atomic"
Expand All @@ -36,7 +35,6 @@ import (
"github.com/dop251/goja"
"github.com/gorilla/websocket"
"github.com/grafana/xk6-browser/api"
k6lib "go.k6.io/k6/lib"
)

// Ensure Browser implements the EventEmitter and Browser interfaces
Expand Down Expand Up @@ -85,9 +83,7 @@ type Browser struct {
}

// NewBrowser creates a new browser
func NewBrowser(ctx context.Context, cancelFn context.CancelFunc, browserProc *BrowserProcess, launchOpts *LaunchOptions) (*Browser, error) {
state := k6lib.GetState(ctx)
reCategoryFilter, _ := regexp.Compile(launchOpts.LogCategoryFilter)
func NewBrowser(ctx context.Context, cancelFn context.CancelFunc, browserProc *BrowserProcess, launchOpts *LaunchOptions, logger *Logger) (*Browser, error) {
b := Browser{
BaseEventEmitter: NewBaseEventEmitter(ctx),
ctx: ctx,
Expand All @@ -103,7 +99,7 @@ func NewBrowser(ctx context.Context, cancelFn context.CancelFunc, browserProc *B
pages: make(map[target.ID]*Page),
sessionIDtoTargetIDMu: sync.RWMutex{},
sessionIDtoTargetID: make(map[target.SessionID]target.ID),
logger: NewLogger(ctx, state.Logger, launchOpts.Debug, reCategoryFilter),
logger: logger,
}
if err := b.connect(); err != nil {
return nil, err
Expand Down Expand Up @@ -223,7 +219,8 @@ func (b *Browser) onAttachedToTarget(ev *target.EventAttachedToTarget) {
isRunning := atomic.LoadInt64(&b.state) == BrowserStateOpen && b.IsConnected() //b.conn.isConnected()
if _, ok := err.(*websocket.CloseError); !ok && !isRunning {
// If we're no longer connected to browser, then ignore WebSocket errors
b.logger.Debugf("Browser:onAttachedToTarget:background_page", "sid:%v tid:%v, returns: websocket error", ev.SessionID, ev.TargetInfo.TargetID)
b.logger.Debugf("Browser:onAttachedToTarget:background_page", "sid:%v tid:%v, returns: websocket err: %v",
ev.SessionID, ev.TargetInfo.TargetID, err)
return
}
k6Throw(b.ctx, "cannot create NewPage for background_page event: %w", err)
Expand Down Expand Up @@ -326,11 +323,11 @@ func (b *Browser) newPageInContext(id cdp.BrowserContextID) (*Page, error) {
case <-b.ctx.Done():
b.logger.Debugf("Browser:newPageInContext:<-b.ctx.Done", "tid:%v bcid:%v", localTargetID, id)
case <-time.After(b.launchOpts.Timeout):
b.logger.Debugf("Browser:newPageInContext:timeout", "tid:%v bcid:%v", localTargetID, id)
b.logger.Debugf("Browser:newPageInContext:timeout", "tid:%v bcid:%v timeout:%s", localTargetID, id, b.launchOpts.Timeout)
case c := <-ch:
b.logger.Debugf("Browser:newPageInContext:<-ch", "tid:%v bcid:%v, ch:%v", localTargetID, id, c)
b.logger.Debugf("Browser:newPageInContext:<-ch", "tid:%v bcid:%v, c:%v", localTargetID, id, c)
case err := <-errCh:
b.logger.Debugf("Browser:newPageInContext:<-errCh", "tid:%v bcid:%v, ch:%v", localTargetID, id, err)
b.logger.Debugf("Browser:newPageInContext:<-errCh", "tid:%v bcid:%v, err:%v", localTargetID, id, err)
return nil, err
}
b.pagesMu.RLock()
Expand All @@ -346,12 +343,8 @@ func (b *Browser) Close() {
b.logger.Debugf("Browser:Close", "already in a closing state")
return
}
b.logger.Debugf("Browser:Close", "graceful terminate")
b.browserProc.GracefulClose()
defer func() {
b.logger.Debugf("Browser:Close", "browserProc terminate")
b.browserProc.Terminate()
}()
defer b.browserProc.Terminate()

action := cdpbrowser.Close()
if err := action.Do(cdp.WithExecutor(b.ctx, b.conn)); err != nil {
Expand Down Expand Up @@ -405,7 +398,6 @@ func (b *Browser) NewContext(opts goja.Value) api.BrowserContext {
// NewPage creates a new tab in the browser window
func (b *Browser) NewPage(opts goja.Value) api.Page {
browserCtx := b.NewContext(opts)
b.logger.Debugf("Browser:NewContext", "NewPage")
return browserCtx.NewPage()
}

Expand Down

0 comments on commit aebddcb

Please sign in to comment.