Repository navigation
Expand file tree
/
Copy pathconnection.go
More file actions
573 lines (533 loc) · 15.8 KB
/
Copy pathconnection.go
File metadata and controls
573 lines (533 loc) · 15.8 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
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
package playwright
import (
"errors"
"fmt"
"math/rand/v2"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/go-stack/stack"
"github.com/mxschmitt/playwright-go/internal/safe"
)
var (
pkgSourcePathPattern = regexp.MustCompile(`.+[\\/]playwright-go[\\/][^\\/]+\.go`)
apiNameTransform = regexp.MustCompile(`(?U)\(\*(.+)(Impl)?\)`)
)
type connection struct {
transport transport
// apiZone is keyed by goroutine id so concurrent API calls cannot consume
// each other's stack/internal metadata. A zone is removed as soon as its
// first protocol message is built, matching upstream's exit from the API zone
// before waiting for the server or dispatching re-entrant events.
apiZone sync.Map // map[uint64]parsedStackTrace
objects *safe.SyncMap[string, *channelOwner]
// callIDPrefix makes call ids unique across connections, since they
// double as call ids in traces.
callIDPrefix string
lastID atomic.Uint32
rootObject *rootChannelOwner
callbacks *safe.SyncMap[string, *protocolCallback]
afterClose func()
onClose func() error
isRemote bool
localUtils *localUtilsImpl
tracingCount atomic.Int32
abort chan struct{}
abortOnce sync.Once
err *safeValue[error] // for event listener error
closedError *safeValue[error]
// dispatchGID is the id of the goroutine that runs the receive loop (and
// therefore synchronously runs event handlers). When a handler makes a
// blocking server call, the reply can only be delivered by this same
// goroutine; blocking on it would deadlock. waitResult detects that case by
// comparing against this id and instead pumps the receive loop re-entrantly
// until the reply arrives. Keeping all message processing on one goroutine
// preserves the original event ordering and avoids data races on the object
// graph.
dispatchGID atomic.Uint64
}
func (c *connection) Start() (*Playwright, error) {
go func() {
c.dispatchGID.Store(currentGoroutineID())
for {
if !c.pollOnce() {
return
}
}
}()
c.onClose = func() error {
if err := c.transport.Close(); err != nil {
return err
}
return nil
}
return c.rootObject.initialize()
}
// pollOnce reads and dispatches a single message. It returns false when the
// transport is closed or errors, signalling the receive loop to stop. It is
// also called re-entrantly from waitResult to drain replies for a blocking
// call made on the dispatch goroutine itself (see waitResult).
func (c *connection) pollOnce() bool {
msg, err := c.transport.Poll()
if err != nil {
_ = c.transport.Close()
c.cleanup(err)
return false
}
c.Dispatch(msg)
return true
}
func (c *connection) Stop() error {
if err := c.onClose(); err != nil {
return err
}
c.cleanup()
return nil
}
func (c *connection) cleanup(cause ...error) {
if len(cause) > 0 {
c.closedError.Set(fmt.Errorf("%w: %w", ErrTargetClosed, cause[0]))
} else {
c.closedError.Set(ErrTargetClosed)
}
if c.afterClose != nil {
c.afterClose()
}
c.abortOnce.Do(func() {
select {
case <-c.abort:
default:
close(c.abort)
}
})
}
func (c *connection) Dispatch(msg *message) {
if c.closedError.Get() != nil {
return
}
method := msg.Method
if msg.ID != "" {
cb, ok := c.callbacks.LoadAndDelete(msg.ID)
if !ok {
// No pending callback for this id (duplicate or unknown reply).
// Upstream throws "Cannot find command to respond"; dereferencing
// the nil callback below would instead panic the dispatch
// goroutine, so guard and ignore the stray reply.
return
}
if cb.noReply {
return
}
if msg.Error != nil && msg.Result == nil {
err := parseError(msg.Error.Error)
if log := formatCallLog(msg.Log); log != "" {
err = fmt.Errorf("%w%s", err, log)
}
// Preserve structured errorDetails (e.g. assertion `expect` failures
// in v1.61+) so callers can reconstruct the result via errors.As.
if msg.ErrorDetails != nil {
details, derr := c.replaceGuidsWithChannels(msg.ErrorDetails)
if derr == nil {
if detailsMap, ok := details.(map[string]any); ok {
err = &errorWithDetails{err: err, details: detailsMap, log: msg.Log}
}
}
}
cb.SetError(err)
} else {
// Always resolve GUIDs in responses, regardless of connection type
// The protocol guarantees that __create__ events arrive before responses that reference those objects
result, err := c.replaceGuidsWithChannels(msg.Result)
if err != nil {
cb.SetError(fmt.Errorf("failed to resolve response objects: %w", err))
} else {
cb.SetResult(result.(map[string]any))
}
}
return
}
object, _ := c.objects.Load(msg.GUID)
if method == "__create__" {
_, err := c.createRemoteObject(
object, msg.Params["type"].(string), msg.Params["guid"].(string), msg.Params["initializer"],
)
if err != nil {
// Critical: object creation failure indicates corrupted protocol state
// Close connection to prevent cascade failures
c.cleanup(err)
}
return
}
if object == nil {
return
}
if method == "__adopt__" {
child, ok := c.objects.Load(msg.Params["guid"].(string))
if !ok {
return
}
object.adopt(child)
return
}
if method == "__dispose__" {
reason, ok := msg.Params["reason"]
if ok {
object.dispose(reason.(string))
} else {
object.dispose()
}
return
}
if object.objectType == "JsonPipe" {
object.channel.Emit(method, msg.Params)
} else {
// Always resolve GUIDs in events, regardless of connection type
// The protocol guarantees that __create__ events arrive before events that reference those objects
params, err := c.replaceGuidsWithChannels(msg.Params)
if err != nil {
// Event parameters contain invalid references - connection is corrupted
c.cleanup(fmt.Errorf("failed to resolve event parameters for %s: %w", method, err))
return
}
object.channel.Emit(method, params)
}
}
func (c *connection) LocalUtils() *localUtilsImpl {
return c.localUtils
}
func (c *connection) createRemoteObject(parent *channelOwner, objectType string, guid string, initializer any) (any, error) {
resolved, err := c.replaceGuidsWithChannels(initializer)
if err != nil {
return nil, fmt.Errorf("failed to resolve initializer for %s (guid=%s): %w", objectType, guid, err)
}
result := createObjectFactory(parent, objectType, guid, resolved.(map[string]any))
return result, nil
}
func (c *connection) WrapAPICall(cb func() (any, error), isInternal bool) (any, error) {
zoneKey := currentGoroutineID()
if _, ok := c.apiZone.Load(zoneKey); ok {
return cb()
}
c.apiZone.Store(zoneKey, serializeCallStack(isInternal))
// innerSend can return before sendMessageToServer (for example, when a route
// handler left a pending error). Do not let that stale zone classify the next
// call made by the same goroutine.
defer c.apiZone.Delete(zoneKey)
return cb()
}
func (c *connection) replaceGuidsWithChannels(payload any) (any, error) {
if payload == nil {
return nil, nil
}
v := reflect.ValueOf(payload)
if v.Kind() == reflect.Slice {
listV := payload.([]any)
for i := range listV {
resolved, err := c.replaceGuidsWithChannels(listV[i])
if err != nil {
return nil, fmt.Errorf("failed to resolve slice element at index %d: %w", i, err)
}
listV[i] = resolved
}
return listV, nil
}
if v.Kind() == reflect.Map {
mapV := payload.(map[string]any)
// A map whose "guid" names a bound object is a reference to that object.
// Any other "guid" key is plain data and the map is walked like every
// other map: raw CDP payloads relayed through CDPSession "event" carry
// Chrome's own guid fields (Page.downloadWillBegin, Page.downloadProgress),
// and the reference client passes such maps through untouched. Treating
// them as broken references tore down the whole connection on the first
// download seen by any CDP session.
if guid, hasGUID := mapV["guid"]; hasGUID {
if guidStr, ok := guid.(string); ok {
if channelOwner, ok := c.objects.Load(guidStr); ok {
return channelOwner.channel, nil
}
}
}
// Recursively process all values in the map
for key := range mapV {
resolved, err := c.replaceGuidsWithChannels(mapV[key])
if err != nil {
return nil, fmt.Errorf("failed to resolve map key '%s': %w", key, err)
}
mapV[key] = resolved
}
return mapV, nil
}
return payload, nil
}
func (c *connection) sendMessageToServer(object *channelOwner, method string, params any, noReply bool, timeout *float64) (cb *protocolCallback) {
cb = newProtocolCallback(c, noReply, c.abort)
if err := c.closedError.Get(); err != nil {
cb.SetError(err)
return
}
if object.wasCollected {
cb.SetError(errors.New("The object has been collected to prevent unbounded heap growth."))
return
}
id := fmt.Sprintf("%s@%d", c.callIDPrefix, c.lastID.Add(1))
// The server never replies to noReply messages, so storing their callbacks
// would leak an entry per call for the connection's lifetime.
if !noReply {
c.callbacks.Store(id, cb)
}
var (
metadata = make(map[string]any, 0)
stack = make([]map[string]any, 0)
)
apiZone, ok := c.apiZone.LoadAndDelete(currentGoroutineID())
if ok {
for k, v := range apiZone.(parsedStackTrace).metadata {
metadata[k] = v
}
stack = append(stack, apiZone.(parsedStackTrace).frames...)
}
metadata["wallTime"] = time.Now().UnixMilli()
// Playwright 1.62+: call timeout is protocol metadata, not a method param.
// Preserve explicit zero; omit the field entirely when timeout is nil.
if timeout != nil {
metadata["timeout"] = *timeout
}
message := map[string]any{
"id": id,
"guid": object.guid,
"method": method,
"params": params, // channel.MarshalJSON will replace channel with guid
"metadata": metadata,
}
if c.tracingCount.Load() > 0 && len(stack) > 0 && object.guid != "localUtils" {
c.LocalUtils().AddStackToTracingNoReply(id, stack)
}
if err := c.transport.Send(message); err != nil {
// Keep the callback registered until Send returns so an immediately
// dispatched response cannot be lost. If the send itself fails, however,
// no caller can consume a future response for this id, so remove it to
// avoid retaining one callback per failed send.
if !noReply {
c.callbacks.Delete(id)
}
cb.SetError(fmt.Errorf("could not send message: %w", err))
return
}
return
}
func (c *connection) setInTracing(isTracing bool) {
if isTracing {
c.tracingCount.Add(1)
} else {
c.tracingCount.Add(-1)
}
}
type parsedStackTrace struct {
frames []map[string]any
metadata map[string]any
}
func serializeCallStack(isInternal bool) parsedStackTrace {
st := stack.Trace().TrimRuntime()
if len(st) == 0 { // https://github.com/go-stack/stack/issues/27
st = stack.Trace()
}
lastInternalIndex := 0
for i, s := range st {
if pkgSourcePathPattern.MatchString(s.Frame().File) {
lastInternalIndex = i
}
}
apiName := ""
if !isInternal {
apiName = fmt.Sprintf("%n", st[lastInternalIndex])
}
st = st.TrimBelow(st[lastInternalIndex])
callStack := make([]map[string]any, 0)
for i, s := range st {
if i == 0 {
continue
}
callStack = append(callStack, map[string]any{
"file": s.Frame().File,
"line": s.Frame().Line,
"column": 0,
"function": s.Frame().Function,
})
}
metadata := make(map[string]any)
if len(st) > 1 {
metadata["location"] = serializeCallLocation(st[1])
}
apiName = apiNameTransform.ReplaceAllString(apiName, "$1")
if len(apiName) > 1 {
apiName = strings.ToUpper(apiName[:1]) + apiName[1:]
}
metadata["apiName"] = apiName
// The protocol carries the internal-call marker as metadata.internal.
metadata["internal"] = isInternal
return parsedStackTrace{
metadata: metadata,
frames: callStack,
}
}
func serializeCallLocation(caller stack.Call) map[string]any {
line, _ := strconv.Atoi(fmt.Sprintf("%d", caller))
return map[string]any{
"file": fmt.Sprintf("%s", caller),
"line": line,
}
}
// newCallIDPrefix returns four random lowercase letters, matching the call id
// prefix of the upstream clients.
func newCallIDPrefix() string {
const alphabet = "abcdefghijklmnopqrstuvwxyz"
prefix := make([]byte, 4)
for i := range prefix {
prefix[i] = alphabet[rand.IntN(len(alphabet))]
}
return string(prefix)
}
func newConnection(transport transport, localUtils ...*localUtilsImpl) *connection {
connection := &connection{
abort: make(chan struct{}, 1),
callbacks: safe.NewSyncMap[string, *protocolCallback](),
callIDPrefix: newCallIDPrefix(),
objects: safe.NewSyncMap[string, *channelOwner](),
transport: transport,
isRemote: false,
err: &safeValue[error]{},
closedError: &safeValue[error]{},
}
if len(localUtils) > 0 {
connection.localUtils = localUtils[0]
connection.isRemote = true
}
connection.rootObject = newRootChannelOwner(connection)
return connection
}
func fromChannel(v any) any {
if ch, ok := v.(*channel); ok {
return ch.object
}
panic(fmt.Sprintf("fromChannel: expected *channel, got %T: %+v", v, v))
}
func fromNullableChannel(v any) any {
if v == nil {
return nil
}
return fromChannel(v)
}
type protocolCallback struct {
connection *connection
done chan struct{}
noReply bool
abort <-chan struct{}
once sync.Once
value map[string]any
err error
}
func (pc *protocolCallback) setResultOnce(result map[string]any, err error) {
pc.once.Do(func() {
pc.value = result
pc.err = err
if pc.done != nil {
close(pc.done)
}
})
}
func (pc *protocolCallback) waitResult() {
if pc.noReply {
return
}
// A blocking call made from within an event handler runs on the dispatch
// goroutine, which is the only goroutine that can deliver this reply.
// Blocking on pc.done would deadlock, so instead drive the receive loop
// re-entrantly until the reply (or connection close) arrives. If a reply
// dispatched here triggers another event whose handler makes a blocking
// call, waitResult re-enters; the recursion is bounded by the nesting depth
// of blocking-handler chains, which mirrors the synchronous client model.
//
// dispatchGID is 0 until the receive loop records its id; currentGoroutineID
// also returns 0 if the stack header can't be parsed. Guarding against 0
// ensures neither case is mistaken for the dispatch goroutine.
if gid := pc.connection.dispatchGID.Load(); gid != 0 && gid == currentGoroutineID() {
for {
select {
case <-pc.done:
return
case <-pc.abort:
// Prefer a delivered result over the close error: setResultOnce
// sets value/err before closing done, so a closed done means a
// real result is already available.
select {
case <-pc.done:
default:
pc.err = errors.New("Connection closed")
}
return
default:
}
if !pc.connection.pollOnce() {
select {
case <-pc.done:
default:
pc.err = errors.New("Connection closed")
}
return
}
}
}
select {
case <-pc.done: // wait for result
return
case <-pc.abort:
select {
case <-pc.done:
return
default:
pc.err = errors.New("Connection closed")
return
}
}
}
func (pc *protocolCallback) SetError(err error) {
pc.setResultOnce(nil, err)
}
func (pc *protocolCallback) SetResult(result map[string]any) {
pc.setResultOnce(result, nil)
}
func (pc *protocolCallback) GetResult() (map[string]any, error) {
pc.waitResult()
return pc.value, pc.err
}
// GetResultValue returns value if the map has only one element
func (pc *protocolCallback) GetResultValue() (any, error) {
pc.waitResult()
if len(pc.value) == 0 { // empty map treated as nil
return nil, pc.err
}
if len(pc.value) == 1 {
for key := range pc.value {
return pc.value[key], pc.err
}
}
return pc.value, pc.err
}
func newProtocolCallback(connection *connection, noReply bool, abort <-chan struct{}) *protocolCallback {
if noReply {
return &protocolCallback{
connection: connection,
noReply: true,
abort: abort,
}
}
return &protocolCallback{
connection: connection,
done: make(chan struct{}, 1),
abort: abort,
}
}