generated from matrix-org/.github
-
Notifications
You must be signed in to change notification settings - Fork 5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Run JS SDK in separate tabs rather than browsers #108
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
92b76a2
Move Browser to own file, add singleton
kegsay a72753e
Add Tab type and use it when we want to refer to single client instances
kegsay a41e33a
Use .localhost prefixes for different origins
kegsay 6a414f1
Update internal/api/js/chrome/browser.go
kegsay 3a988be
Update internal/api/js/chrome/chrome.go
kegsay e14c65d
Add debug logging
kegsay File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
package chrome | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"os" | ||
"path/filepath" | ||
"strconv" | ||
"sync" | ||
"time" | ||
|
||
"github.com/chromedp/cdproto/runtime" | ||
"github.com/chromedp/chromedp" | ||
) | ||
|
||
// We only spin up a single chrome browser for all tests. | ||
// Each test hosts the JS SDK HTML/JS on a random high-numbered port and opens it in a new tab | ||
// for test isolation. | ||
var ( | ||
browserInstance *Browser | ||
browserInstanceMu = &sync.Mutex{} | ||
origins *Origins | ||
) | ||
|
||
// GlobalBrowser returns the browser singleton, making it if needed. | ||
func GlobalBrowser() (*Browser, error) { | ||
browserInstanceMu.Lock() | ||
defer browserInstanceMu.Unlock() | ||
if browserInstance == nil { | ||
var err error | ||
browserInstance, err = NewBrowser() | ||
origins = NewOrigins() | ||
return browserInstance, err | ||
} | ||
return browserInstance, nil | ||
} | ||
|
||
type Browser struct { | ||
Ctx context.Context // topmost chromedp context | ||
ctxCancel func() | ||
execAllocCancel func() | ||
} | ||
|
||
// Create and run a new Chrome browser. | ||
func NewBrowser() (*Browser, error) { | ||
ansiRedForeground := "\x1b[31m" | ||
ansiResetForeground := "\x1b[39m" | ||
|
||
colorifyError := func(format string, args ...any) { | ||
format = ansiRedForeground + time.Now().Format(time.RFC3339) + " " + format + ansiResetForeground | ||
fmt.Printf(format, args...) | ||
} | ||
opts := chromedp.DefaultExecAllocatorOptions[:] | ||
os.Mkdir("chromedp", os.ModePerm) // ignore errors to allow repeated runs | ||
wd, _ := os.Getwd() | ||
userDir := filepath.Join(wd, "chromedp") | ||
opts = append(opts, | ||
chromedp.UserDataDir(userDir), | ||
) | ||
// increase the WS timeout from 20s (default) to 30s as we see timeouts with 20s in CI | ||
opts = append(opts, chromedp.WSURLReadTimeout(30*time.Second)) | ||
|
||
allocCtx, allocCancel := chromedp.NewExecAllocator(context.Background(), opts...) | ||
ctx, cancel := chromedp.NewContext(allocCtx, chromedp.WithBrowserOption( | ||
chromedp.WithBrowserLogf(colorifyError), chromedp.WithBrowserErrorf(colorifyError), //chromedp.WithBrowserDebugf(log.Printf), | ||
)) | ||
|
||
browser := &Browser{ | ||
Ctx: ctx, | ||
ctxCancel: cancel, | ||
execAllocCancel: allocCancel, | ||
} | ||
return browser, chromedp.Run(ctx) | ||
} | ||
|
||
func (b *Browser) Close() { | ||
b.ctxCancel() | ||
b.execAllocCancel() | ||
} | ||
func (b *Browser) Info() { | ||
targets, err := chromedp.Targets(b.Ctx) | ||
if err != nil { | ||
fmt.Println("DEBUG: failed to get targets: ", err) | ||
return | ||
} | ||
fmt.Printf("DEBUG: got %d targets\n", len(targets)) | ||
var urls []string | ||
for _, t := range targets { | ||
urls = append(urls, t.URL) | ||
} | ||
fmt.Println(urls) | ||
} | ||
|
||
func (b *Browser) NewTab(baseJSURL string, onConsoleLog func(s string)) (*Tab, error) { | ||
tabCtx, closeTab := chromedp.NewContext(b.Ctx) | ||
err := chromedp.Run(tabCtx, | ||
chromedp.Navigate(baseJSURL), | ||
) | ||
if err != nil { | ||
return nil, fmt.Errorf("NewTab: failed to navigate to %s: %s", baseJSURL, err) | ||
} | ||
|
||
// Listen for console logs for debugging, and to communicate live updates | ||
chromedp.ListenTarget(tabCtx, func(ev interface{}) { | ||
switch ev := ev.(type) { | ||
case *runtime.EventConsoleAPICalled: | ||
for _, arg := range ev.Args { | ||
s, err := strconv.Unquote(string(arg.Value)) | ||
if err != nil { | ||
s = string(arg.Value) | ||
} | ||
onConsoleLog(s) | ||
} | ||
} | ||
}) | ||
|
||
return &Tab{ | ||
BaseURL: baseJSURL, | ||
Ctx: tabCtx, | ||
Browser: b, | ||
cancel: closeTab, | ||
}, nil | ||
} | ||
|
||
// For clients which want persistent storage, we need to ensure when the browser | ||
// starts up a 2nd+ time we serve the same URL so the browser uses the same origin | ||
type Origins struct { | ||
clientToBaseURL map[string]string | ||
mu *sync.RWMutex | ||
} | ||
|
||
func NewOrigins() *Origins { | ||
return &Origins{ | ||
clientToBaseURL: make(map[string]string), | ||
mu: &sync.RWMutex{}, | ||
} | ||
} | ||
|
||
func (o *Origins) StoreBaseURL(userID, deviceID, baseURL string) { | ||
o.mu.Lock() | ||
defer o.mu.Unlock() | ||
o.clientToBaseURL[userID+deviceID] = baseURL | ||
} | ||
|
||
func (o *Origins) GetBaseURL(userID, deviceID string) (baseURL string) { | ||
o.mu.RLock() | ||
defer o.mu.RUnlock() | ||
return o.clientToBaseURL[userID+deviceID] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
document?