Skip to content

Commit

Permalink
Merge pull request #568 from grafana/update/279-go1.19
Browse files Browse the repository at this point in the history
  • Loading branch information
inancgumus authored Oct 19, 2022
2 parents a94a165 + f24e01c commit 16c0b8c
Show file tree
Hide file tree
Showing 43 changed files with 326 additions and 355 deletions.
2 changes: 1 addition & 1 deletion api/browser_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ type BrowserContext interface {
SetOffline(offline bool)
StorageState(opts goja.Value) *goja.Promise
Unroute(url goja.Value, handler goja.Callable) *goja.Promise
WaitForEvent(event string, optsOrPredicate goja.Value) interface{}
WaitForEvent(event string, optsOrPredicate goja.Value) any
}
2 changes: 1 addition & 1 deletion api/frame.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type Frame interface {
Content() string
Dblclick(selector string, opts goja.Value)
DispatchEvent(selector string, typ string, eventInit goja.Value, opts goja.Value)
Evaluate(pageFunc goja.Value, args ...goja.Value) interface{}
Evaluate(pageFunc goja.Value, args ...goja.Value) any
EvaluateHandle(pageFunc goja.Value, args ...goja.Value) JSHandle
Fill(selector string, value string, opts goja.Value)
Focus(selector string, opts goja.Value)
Expand Down
2 changes: 1 addition & 1 deletion api/js_handle.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
type JSHandle interface {
AsElement() ElementHandle
Dispose()
Evaluate(pageFunc goja.Value, args ...goja.Value) interface{}
Evaluate(pageFunc goja.Value, args ...goja.Value) any
EvaluateHandle(pageFunc goja.Value, args ...goja.Value) JSHandle
GetProperties() map[string]JSHandle
GetProperty(propertyName string) JSHandle
Expand Down
2 changes: 1 addition & 1 deletion api/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type Page interface {
DragAndDrop(source string, target string, opts goja.Value) *goja.Promise
EmulateMedia(opts goja.Value)
EmulateVisionDeficiency(typ string)
Evaluate(pageFunc goja.Value, arg ...goja.Value) interface{}
Evaluate(pageFunc goja.Value, arg ...goja.Value) any
EvaluateHandle(pageFunc goja.Value, arg ...goja.Value) JSHandle
ExposeBinding(name string, callback goja.Callable, opts goja.Value) *goja.Promise
ExposeFunction(name string, callback goja.Callable) *goja.Promise
Expand Down
2 changes: 1 addition & 1 deletion api/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import "github.com/dop251/goja"

// Worker is the interface of a web worker.
type Worker interface {
Evaluate(pageFunc goja.Value, args ...goja.Value) interface{}
Evaluate(pageFunc goja.Value, args ...goja.Value) any
EvaluateHandle(pageFunc goja.Value, args ...goja.Value) JSHandle
URL() string
}
14 changes: 7 additions & 7 deletions chromium/browser_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ func (b *BrowserType) Name() string {
// allocate starts a new Chromium browser process and returns it.
func (b *BrowserType) allocate(
ctx context.Context, opts *common.LaunchOptions,
flags map[string]interface{}, env []string, dataDir *storage.Dir,
flags map[string]any, env []string, dataDir *storage.Dir,
logger *log.Logger,
) (_ *common.BrowserProcess, rerr error) {
bProcCtx, bProcCtxCancel := context.WithTimeout(ctx, opts.Timeout)
Expand All @@ -236,7 +236,7 @@ func (b *BrowserType) allocate(
}

// parseArgs parses command-line arguments and returns them.
func parseArgs(flags map[string]interface{}) ([]string, error) {
func parseArgs(flags map[string]any) ([]string, error) {
// Build command line args list
var args []string
for name, value := range flags {
Expand Down Expand Up @@ -268,9 +268,9 @@ func parseArgs(flags map[string]interface{}) ([]string, error) {
return args, nil
}

func prepareFlags(lopts *common.LaunchOptions, k6opts *k6lib.Options) map[string]interface{} {
func prepareFlags(lopts *common.LaunchOptions, k6opts *k6lib.Options) map[string]any {
// After Puppeteer's and Playwright's default behavior.
f := map[string]interface{}{
f := map[string]any{
"disable-background-networking": true,
"enable-features": "NetworkService,NetworkServiceInProcess",
"disable-background-timer-throttling": true,
Expand Down Expand Up @@ -322,7 +322,7 @@ func prepareFlags(lopts *common.LaunchOptions, k6opts *k6lib.Options) map[string
}

// ignoreDefaultArgsFlags ignores any flags in the provided slice.
func ignoreDefaultArgsFlags(flags map[string]interface{}, toIgnore []string) {
func ignoreDefaultArgsFlags(flags map[string]any, toIgnore []string) {
for _, name := range toIgnore {
delete(flags, strings.TrimPrefix(name, "--"))
}
Expand All @@ -331,7 +331,7 @@ func ignoreDefaultArgsFlags(flags map[string]interface{}, toIgnore []string) {
// setFlagsFromArgs fills flags by parsing the args slice.
// This is used for passing the "arg=value" arguments along with other launch options
// when launching a new Chrome browser.
func setFlagsFromArgs(flags map[string]interface{}, args []string) {
func setFlagsFromArgs(flags map[string]any, args []string) {
var argname, argval string
for _, arg := range args {
pair := strings.SplitN(arg, "=", 2)
Expand All @@ -345,7 +345,7 @@ func setFlagsFromArgs(flags map[string]interface{}, args []string) {

// setFlagsFromK6Options adds additional data to flags considering the k6 options.
// Such as: "host-resolver-rules" for blocking requests.
func setFlagsFromK6Options(flags map[string]interface{}, k6opts *k6lib.Options) {
func setFlagsFromK6Options(flags map[string]any, k6opts *k6lib.Options) {
if k6opts == nil {
return
}
Expand Down
8 changes: 4 additions & 4 deletions chromium/browser_type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ func TestBrowserTypePrepareFlags(t *testing.T) {
flag string
changeOpts *common.LaunchOptions
changeK6Opts *k6lib.Options
expInitVal, expChangedVal interface{}
expInitVal, expChangedVal any
pre func(t *testing.T)
post func(t *testing.T, flags map[string]interface{})
post func(t *testing.T, flags map[string]any)
}{
{
flag: "auto-open-devtools-for-tabs",
Expand Down Expand Up @@ -76,7 +76,7 @@ func TestBrowserTypePrepareFlags(t *testing.T) {
changeOpts: &common.LaunchOptions{Args: []string{
"browser-arg1='value1", "browser-arg2=''value2''", "browser-flag",
}},
post: func(t *testing.T, flags map[string]interface{}) {
post: func(t *testing.T, flags map[string]any) {
t.Helper()

assert.Equal(t, "'value1", flags["browser-arg1"])
Expand Down Expand Up @@ -122,7 +122,7 @@ func TestBrowserTypePrepareFlags(t *testing.T) {
expInitVal: false,
changeOpts: &common.LaunchOptions{Headless: true},
expChangedVal: true,
post: func(t *testing.T, flags map[string]interface{}) {
post: func(t *testing.T, flags map[string]any) {
t.Helper()

extraFlags := []string{"hide-scrollbars", "mute-audio", "blink-settings"}
Expand Down
4 changes: 3 additions & 1 deletion common/barrier.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ func (b *Barrier) AddFrameNavigation(frame *Frame) {
if frame.parentFrame != nil {
return // We only care about top-frame navigation
}
ch, evCancelFn := createWaitForEventHandler(frame.ctx, frame, []string{EventFrameNavigation}, func(data interface{}) bool { return true })
ch, evCancelFn := createWaitForEventHandler(frame.ctx, frame, []string{EventFrameNavigation}, func(data any) bool {
return true
})
go func() {
defer evCancelFn() // Remove event handler
atomic.AddInt64(&b.count, 1)
Expand Down
4 changes: 2 additions & 2 deletions common/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ func (b *Browser) newPageInContext(id cdp.BrowserContextID) (*Page, error) {
ctx,
browserCtx, // browser context will emit the following event:
[]string{EventBrowserContextPage},
func(e interface{}) bool {
func(e any) bool {
tid := <-targetID

b.logger.Debugf("Browser:newPageInContext:createWaitForEventHandler",
Expand Down Expand Up @@ -499,7 +499,7 @@ func (b *Browser) On(event string) *goja.Promise {
if event != EventBrowserDisconnected {
k6ext.Panic(b.ctx, "unknown browser event: %q, must be %q", event, EventBrowserDisconnected)
}
return k6ext.Promise(b.ctx, func() (interface{}, error) {
return k6ext.Promise(b.ctx, func() (any, error) {
select {
case <-b.browserProc.lostConnection:
return true, nil
Expand Down
102 changes: 56 additions & 46 deletions common/browser_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,20 +331,21 @@ func (b *BrowserContext) Unroute(url goja.Value, handler goja.Callable) *goja.Pr
return nil
}

func (b *BrowserContext) WaitForEvent(event string, optsOrPredicate goja.Value) interface{} {
// WaitForEvent waits for event.
func (b *BrowserContext) WaitForEvent(event string, optsOrPredicate goja.Value) any {
// TODO: This public API needs Promise support (as return value) to be useful in JS!
b.logger.Debugf("BrowserContext:WaitForEvent", "bctxid:%v event:%q", b.id, event)

rt := b.vu.Runtime()

var isCallable bool
var predicateFn goja.Callable = nil
timeout := time.Duration(b.browser.launchOpts.Timeout * time.Second)

if optsOrPredicate != nil && !goja.IsUndefined(optsOrPredicate) && !goja.IsNull(optsOrPredicate) {
var (
isCallable bool
predicateFn goja.Callable
// TODO: Find out whether * time.Second is necessary.
timeout = b.browser.launchOpts.Timeout * time.Second //nolint:durationcheck
)
if gojaValueExists(optsOrPredicate) {
switch optsOrPredicate.ExportType() {
case reflect.TypeOf(goja.Object{}):
opts := optsOrPredicate.ToObject(rt)
opts := optsOrPredicate.ToObject(b.vu.Runtime())
for _, k := range opts.Keys() {
switch k {
case "predicate":
Expand All @@ -364,46 +365,15 @@ func (b *BrowserContext) WaitForEvent(event string, optsOrPredicate goja.Value)
}
}

return b.waitForEvent(event, predicateFn, timeout)
}

func (b *BrowserContext) waitForEvent(event string, predicateFn goja.Callable, timeout time.Duration) any {
evCancelCtx, evCancelFn := context.WithCancel(b.ctx)
chEvHandler := make(chan Event)
ch := make(chan interface{})

go func() {
b.logger.Debugf("BrowserContext:WaitForEvent:go():starts", "bctxid:%v", b.id)
defer b.logger.Debugf("BrowserContext:WaitForEvent:go():returns", "bctxid:%v", b.id)
for {
select {
case <-evCancelCtx.Done():
b.logger.Debugf("BrowserContext:WaitForEvent:go():evCancelCtx:done", "bctxid:%v", b.id)
return
case ev := <-chEvHandler:
if ev.typ == EventBrowserContextClose {
b.logger.Debugf("BrowserContext:WaitForEvent:go():EventBrowserContextClose:return", "bctxid:%v", b.id)
ch <- nil
close(ch)
ch := make(chan any)

// We wait for one matching event only,
// then remove event handler by cancelling context and stopping goroutine.
evCancelFn()
return
}
if ev.typ == EventBrowserContextPage {
b.logger.Debugf("BrowserContext:WaitForEvent:go():EventBrowserContextPage", "bctxid:%v", b.id)
p, _ := ev.data.(*Page)
if retVal, err := predicateFn(rt.ToValue(p)); err == nil && retVal.ToBoolean() {
b.logger.Debugf("BrowserContext:WaitForEvent:go():EventBrowserContextPage:return", "bctxid:%v", b.id)
ch <- p
close(ch)

// We wait for one matching event only,
// then remove event handler by cancelling context and stopping goroutine.
evCancelFn()
return
}
}
}
}
}()
go b.runWaitForEventHandler(evCancelCtx, evCancelFn, chEvHandler, ch, predicateFn)

b.on(evCancelCtx, []string{EventBrowserContextPage}, chEvHandler)
defer evCancelFn() // Remove event handler
Expand All @@ -418,9 +388,49 @@ func (b *BrowserContext) WaitForEvent(event string, optsOrPredicate goja.Value)
return evData
}
b.logger.Debugf("BrowserContext:WaitForEvent:return nil", "bctxid:%v event:%q", b.id, event)

return nil
}

func (b *BrowserContext) runWaitForEventHandler(
ctx context.Context, evCancelFn func(), chEvHandler chan Event, out chan any, predicateFn goja.Callable,
) {
b.logger.Debugf("BrowserContext:WaitForEvent:go():starts", "bctxid:%v", b.id)
defer b.logger.Debugf("BrowserContext:WaitForEvent:go():returns", "bctxid:%v", b.id)
for {
select {
case <-ctx.Done():
b.logger.Debugf("BrowserContext:WaitForEvent:go():ctx:done", "bctxid:%v", b.id)
return
case ev := <-chEvHandler:
if ev.typ == EventBrowserContextClose {
b.logger.Debugf("BrowserContext:WaitForEvent:go():EventBrowserContextClose:return", "bctxid:%v", b.id)
out <- nil
close(out)

// We wait for one matching event only,
// then remove event handler by cancelling context and stopping goroutine.
evCancelFn()
return
}
if ev.typ == EventBrowserContextPage {
b.logger.Debugf("BrowserContext:WaitForEvent:go():EventBrowserContextPage", "bctxid:%v", b.id)
p, _ := ev.data.(*Page)
if retVal, err := predicateFn(b.vu.Runtime().ToValue(p)); err == nil && retVal.ToBoolean() {
b.logger.Debugf("BrowserContext:WaitForEvent:go():EventBrowserContextPage:return", "bctxid:%v", b.id)
out <- p
close(out)

// We wait for one matching event only,
// then remove event handler by cancelling context and stopping goroutine.
evCancelFn()
return
}
}
}
}
}

func (b *BrowserContext) getSession(id target.SessionID) *Session {
return b.browser.conn.getSession(id)
}
2 changes: 1 addition & 1 deletion common/browser_context_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (b *BrowserContextOptions) Parse(ctx context.Context, opts goja.Value) erro
case "offline":
b.Offline = opts.Get(k).ToBoolean()
case "permissions":
if ps, ok := opts.Get(k).Export().([]interface{}); ok {
if ps, ok := opts.Get(k).Export().([]any); ok {
for _, p := range ps {
b.Permissions = append(b.Permissions, fmt.Sprintf("%v", p))
}
Expand Down
4 changes: 2 additions & 2 deletions common/browser_context_options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ func TestBrowserContextOptionsPermissions(t *testing.T) {

var opts BrowserContextOptions
err := opts.Parse(vu.Context(), vu.ToGojaValue((struct {
Permissions []interface{} `js:"permissions"`
Permissions []any `js:"permissions"`
}{
Permissions: []interface{}{"camera", "microphone"},
Permissions: []any{"camera", "microphone"},
})))
assert.NoError(t, err)
assert.Len(t, opts.Permissions, 2)
Expand Down
Loading

0 comments on commit 16c0b8c

Please sign in to comment.