-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathchrome.go
More file actions
227 lines (204 loc) · 7 KB
/
chrome.go
File metadata and controls
227 lines (204 loc) · 7 KB
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
// package chrome provides helper functions to execute JS in a Chrome browser
//
// This would ordinarily be done via a Chrome struct but Go does not allow
// generic methods, only generic static functions, producing "method must have no type parameters".
package chrome
import (
"context"
"embed"
"fmt"
"io/fs"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"sync"
"syscall"
"time"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
"github.com/matrix-org/complement/ct"
)
//go:embed dist
var jsSDKDistDirectory embed.FS
// Void is a type which can be used when you want to run an async function without returning anything.
// It can stop large responses causing errors "Object reference chain is too long (-32000)"
// when we don't care about the response.
type Void *runtime.RemoteObject
// Run an anonymous async iffe in the browser. Set the type parameter to a basic data type
// which can be returned as JSON e.g string, map[string]any, []string. If you do not want
// to return anything, use chrome.Void. For example:
//
// result, err := RunAsyncFn[string](t, ctx, "return await getSomeString()")
// void, err := RunAsyncFn[chrome.Void](t, ctx, "doSomething(); await doSomethingElse();")
func RunAsyncFn[T any](t ct.TestLike, ctx context.Context, js string) (*T, error) {
t.Helper()
out := new(T)
err := chromedp.Run(ctx,
chromedp.Evaluate(`(async () => {`+js+`})()`, &out, func(p *runtime.EvaluateParams) *runtime.EvaluateParams {
return p.WithAwaitPromise(true)
}),
)
if err != nil {
return nil, err
}
return out, nil
}
// MustRunAsyncFn is RunAsyncFn but fails the test if an error is returned when executing.
//
// Run an anonymous async iffe in the browser. Set the type parameter to a basic data type
// which can be returned as JSON e.g string, map[string]any, []string. If you do not want
// to return anything, use chrome.Void
func MustRunAsyncFn[T any](t ct.TestLike, ctx context.Context, js string) *T {
t.Helper()
result, err := RunAsyncFn[T](t, ctx, js)
if err != nil {
ct.Fatalf(t, "MustRunAsyncFn: %s", err)
}
return result
}
type Browser struct {
BaseURL string
Ctx context.Context
Cancel func()
}
// colouredLogWriter is an implementation of `io.Writer` which wraps an `os.File`, adding the date and logPrefix to each line,
// and decorating the text in a specific colour.
type coloredLogWriter struct {
colour string
logPrefix string
output *os.File
}
func (w coloredLogWriter) Write(p []byte) (n int, err error) {
_, err = w.output.WriteString(w.colour)
if err != nil {
return
}
last := byte('\n')
for _, c := range p {
// If this is the first byte after a newline, add the date and prefix
if last == '\n' {
_, err = w.output.WriteString(time.Now().Format(time.RFC3339) + " " + w.logPrefix + " ")
if err != nil {
return
}
}
_, err = w.output.Write([]byte{c})
if err != nil {
return
}
n += 1
last = c
}
ansiResetForeground := "\x1b[39m"
_, err = w.output.WriteString(ansiResetForeground)
return
}
func RunHeadless(logPrefix string, onConsoleLog func(s string), requiresPersistence bool, listenPort int) (*Browser, error) {
ansiRedForeground := "\x1b[31m"
ansiYellowForeground := "\x1b[33m"
ansiBlueForeground := "\x1b[34m"
// colorifyError returns a log format function which prints its input with a given prefix and colour.
colorifyError := func(colour string, prefix string) func(format string, args ...any) {
writer := coloredLogWriter{colour: colour, logPrefix: logPrefix + "[chromedp " + prefix + "]", output: os.Stdout}
return func(format string, args ...any) {
fmt.Fprintf(writer, format, args...)
}
}
opts := chromedp.DefaultExecAllocatorOptions[:]
if requiresPersistence {
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))
// Capture stdout/stderr from Chrome, and log it.
opts = append(opts, chromedp.CombinedOutput(coloredLogWriter{colour: ansiBlueForeground, logPrefix: logPrefix + " chrome:", output: os.Stdout}))
// Hook into chromedp to log the command that is about to be executed. The easiest way to do that seems to be to
// set a ModifyCmdFunc.
opts = append(opts, chromedp.ModifyCmdFunc(func(cmd *exec.Cmd) {
writer := coloredLogWriter{colour: ansiBlueForeground, logPrefix: logPrefix, output: os.Stdout}
fmt.Fprintf(writer, "Executing: %v\n", cmd.Args)
// Replicate the behaviour of the default ModifyCmdFunc: tell the kernel to send the child a SIGKILL when the
// parent thread dies.
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = new(syscall.SysProcAttr)
}
cmd.SysProcAttr.Pdeathsig = syscall.SIGKILL
}))
allocCtx, allocCancel := chromedp.NewExecAllocator(context.Background(), opts...)
ctx, cancel := chromedp.NewContext(allocCtx, chromedp.WithBrowserOption(
chromedp.WithBrowserLogf(colorifyError(ansiYellowForeground, "LOG")),
chromedp.WithBrowserErrorf(colorifyError(ansiRedForeground, "ERROR")),
// chromedp.WithBrowserDebugf(log.Printf),
))
// Make sure we can talk to Chrome before we start messing about with js-sdk
fmt.Println("Starting chrome via chromedp")
err := chromedp.Run(ctx, chromedp.Evaluate(`(() => 1)()`, nil))
if err != nil {
return nil, fmt.Errorf("failed to run test evaluation via chromedp: %w", err)
}
// Listen for console logs for debugging AND to communicate live updates
chromedp.ListenTarget(ctx, 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)
}
}
})
// strip /dist so /index.html loads correctly as does /assets/xxx.js
c, err := fs.Sub(jsSDKDistDirectory, "dist")
if err != nil {
return nil, fmt.Errorf("failed to strip /dist off JS SDK files: %s", err)
}
baseJSURL := ""
// run js-sdk (need to run this as a web server to avoid CORS errors you'd otherwise get with file: URLs)
var wg sync.WaitGroup
wg.Add(1)
mux := &http.ServeMux{}
mux.Handle("/", http.FileServer(http.FS(c)))
srv := &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", listenPort),
Handler: mux,
}
startServer := func() {
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
panic(err)
}
baseJSURL = "http://" + ln.Addr().String()
fmt.Println(logPrefix, "JS SDK wrapper listening on", baseJSURL)
wg.Done()
err = srv.Serve(ln)
fmt.Printf("%s Closing webserver for JS SDK wrapper at %s: %v\n", logPrefix, baseJSURL, err)
}
go startServer()
wg.Wait()
// navigate to the page
err = chromedp.Run(ctx,
chromedp.Navigate(baseJSURL),
)
if err != nil {
return nil, fmt.Errorf("failed to navigate to %s: %s", baseJSURL, err)
}
return &Browser{
Ctx: ctx,
Cancel: func() {
cancel()
allocCancel()
srv.Close()
},
BaseURL: baseJSURL,
}, nil
}