package render import ( "bufio" "bytes" "context" "encoding/json" "errors" "io" "os" "strings" "sync" "testing" "testing/iotest" "time" ) // Frames are NUL-ended, may arrive in any pieces, and one over the cap // is refused however it arrives. func TestReadFrame(t *testing.T) { const max = 32 for _, c := range []struct { name string input string want []string err error }{ {"one", "{\"id\":1}\x00", []string{`{"id":1}`}, io.EOF}, {"two in one read", "a\x00b\x00", []string{"a", "b"}, io.EOF}, {"empty frame", "\x00x\x00", []string{"", "x"}, io.EOF}, {"exactly the cap", strings.Repeat("x", max) + "\x00", []string{strings.Repeat("x", max)}, io.EOF}, {"one over the cap", strings.Repeat("x", max+1) + "\x00", nil, errFrameTooLarge}, {"over the cap, no NUL", strings.Repeat("x", 10*max), nil, errFrameTooLarge}, {"ends mid-frame", "a\x00bc", []string{"a"}, io.ErrUnexpectedEOF}, } { t.Run(c.name, func(t *testing.T) { // A small buffer and one byte a read: every frame arrives // in pieces and crosses the buffer's end. r := bufio.NewReaderSize(iotest.OneByteReader(strings.NewReader(c.input)), 16) var got []string for { msg, err := readFrame(r, max) if err != nil { if !errors.Is(err, c.err) { t.Fatalf("err %v, want %v", err, c.err) } break } got = append(got, string(msg)) } if strings.Join(got, "|") != strings.Join(c.want, "|") { t.Fatalf("frames %q, want %q", got, c.want) } }) } } // peer is a fake browser on the far side of two pipes: it reads this // side's calls and answers with whatever handle writes. type peer struct { t *testing.T toBrowser *os.File // this side writes fromPeer *os.File // this side reads in *os.File // the peer reads out *os.File // the peer writes mu sync.Mutex calls []peerCall handle func(p *peer, c peerCall) done chan struct{} } type peerCall struct { ID int64 `json:"id"` Method string `json:"method"` SessionID string `json:"sessionId"` Params json.RawMessage `json:"params"` } func newPeer(t *testing.T, handle func(p *peer, c peerCall)) *peer { t.Helper() in, toBrowser, err := os.Pipe() if err != nil { t.Fatal(err) } fromPeer, out, err := os.Pipe() if err != nil { t.Fatal(err) } p := &peer{t: t, toBrowser: toBrowser, fromPeer: fromPeer, in: in, out: out, handle: handle, done: make(chan struct{})} go func() { defer close(p.done) r := bufio.NewReader(in) for { raw, err := readFrame(r, maxFrame) if err != nil { return } var c peerCall if json.Unmarshal(raw, &c) != nil { return } p.mu.Lock() p.calls = append(p.calls, c) p.mu.Unlock() p.handle(p, c) } }() t.Cleanup(func() { toBrowser.Close() fromPeer.Close() in.Close() out.Close() <-p.done }) return p } // send writes one raw frame, NUL added. func (p *peer) send(raw string) { p.out.Write(append([]byte(raw), 0)) } func (p *peer) reply(c peerCall, result any) { raw, _ := json.Marshal(map[string]any{"id": c.ID, "result": result}) p.send(string(raw)) } func (p *peer) event(session, method string, params any) { m := map[string]any{"method": method, "params": params} if session != "" { m["sessionId"] = session } raw, _ := json.Marshal(m) p.send(string(raw)) } func (p *peer) methods() []string { p.mu.Lock() defer p.mu.Unlock() var m []string for _, c := range p.calls { m = append(m, c.Method) } return m } // Replies are matched to the call that asked, in any order; an error // reply is the call's error; events between them reach the handler. func TestConnMatchesReplies(t *testing.T) { var pending []peerCall var mu sync.Mutex p := newPeer(t, func(p *peer, c peerCall) { mu.Lock() defer mu.Unlock() pending = append(pending, c) if len(pending) < 2 { return } // Both calls are in: a reply to no call, an event, then the // replies the other way round. p.send(`{"id":999,"result":{}}`) p.event("S", "Page.loadEventFired", map[string]any{"timestamp": 1}) p.send(`{"id":` + itoa(pending[1].ID) + `,"error":{"code":-32000,"message":"no\u0007 such thing"}}`) p.reply(pending[0], map[string]any{"value": "first"}) }) var events []string var emu sync.Mutex c := newConn(p.fromPeer, p.toBrowser, maxFrame, func(session, method string, _ json.RawMessage) { emu.Lock() events = append(events, session+" "+method) emu.Unlock() }) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() var wg sync.WaitGroup var first struct { Value string `json:"value"` } var errFirst, errSecond error wg.Add(2) go func() { defer wg.Done(); errFirst = c.call(ctx, "", "A.first", nil, &first) }() time.Sleep(50 * time.Millisecond) go func() { defer wg.Done(); errSecond = c.call(ctx, "S", "B.second", map[string]any{"x": 1}, nil) }() wg.Wait() if errFirst != nil || first.Value != "first" { t.Fatalf("first: %v %+v", errFirst, first) } var ce *cdpError if !errors.As(errSecond, &ce) || ce.Method != "B.second" || ce.Code != -32000 || ce.Message != "no such thing" { t.Fatalf("second: %v", errSecond) } emu.Lock() defer emu.Unlock() if len(events) != 1 || events[0] != "S Page.loadEventFired" { t.Fatalf("events %q", events) } if c.Err() != nil { t.Fatalf("the connection ended: %v", c.Err()) } } // A browser that never answers, or never reads, does not hold a call // past its deadline. func TestConnCallHasADeadline(t *testing.T) { t.Run("no reply", func(t *testing.T) { p := newPeer(t, func(*peer, peerCall) {}) c := newConn(p.fromPeer, p.toBrowser, maxFrame, nil) ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() began := time.Now() if err := c.call(ctx, "", "Never.answered", nil, nil); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("err %v", err) } if time.Since(began) > 2*time.Second { t.Fatal("the call outlived its deadline") } c.mu.Lock() defer c.mu.Unlock() if len(c.calls) != 0 { t.Fatalf("%d calls still waiting", len(c.calls)) } }) t.Run("never reads", func(t *testing.T) { in, toBrowser, err := os.Pipe() if err != nil { t.Fatal(err) } defer in.Close() defer toBrowser.Close() from, out, err := os.Pipe() if err != nil { t.Fatal(err) } defer from.Close() defer out.Close() c := newConn(from, toBrowser, maxFrame, nil) ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) defer cancel() // More than a pipe holds, to a browser that reads nothing. big := strings.Repeat("x", 4<<20) began := time.Now() if err := c.call(ctx, "", "Big.call", map[string]any{"x": big}, nil); err == nil { t.Fatal("the write finished") } if time.Since(began) > 2*time.Second { t.Fatal("the write outlived its deadline") } if c.Err() == nil { t.Fatal("a half-written message left the connection open") } }) } // What the browser sends cannot grow without bound or confuse the // client: an oversize frame or a frame that is not JSON ends the // connection, and every waiting call fails with it. func TestConnEndsOnABadFrame(t *testing.T) { for _, c := range []struct { name string send func(p *peer) want error }{ {"oversize", func(p *peer) { p.send(`{"id":1,"result":{"data":"` + strings.Repeat("A", 2048) + `"}}`) }, errFrameTooLarge}, {"not JSON", func(p *peer) { p.send(`{"id":1,`) }, nil}, {"pipe closed", func(p *peer) { p.out.Close() }, errConnClosed}, } { t.Run(c.name, func(t *testing.T) { p := newPeer(t, func(p *peer, _ peerCall) { c.send(p) }) conn := newConn(p.fromPeer, p.toBrowser, 1024, nil) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() err := conn.call(ctx, "", "Any.thing", nil, nil) if err == nil || errors.Is(err, context.DeadlineExceeded) { t.Fatalf("err %v", err) } if c.want != nil && !errors.Is(err, c.want) { t.Fatalf("err %v, want %v", err, c.want) } if conn.Err() == nil { t.Fatal("the connection is still open") } if err := conn.call(ctx, "", "After.end", nil, nil); err == nil { t.Fatal("a call after the end was sent") } }) } } // A message this side sends is one JSON object and one NUL, with the // session when there is one. func TestConnWritesOneFramePerCall(t *testing.T) { p := newPeer(t, func(p *peer, c peerCall) { p.reply(c, map[string]any{}) }) c := newConn(p.fromPeer, p.toBrowser, maxFrame, nil) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := c.call(ctx, "S1", "Page.navigate", map[string]any{"url": "http://127.0.0.1:1/"}, nil); err != nil { t.Fatal(err) } if err := c.call(ctx, "", "Browser.getVersion", nil, nil); err != nil { t.Fatal(err) } p.mu.Lock() defer p.mu.Unlock() if len(p.calls) != 2 || p.calls[0].SessionID != "S1" || p.calls[1].SessionID != "" || !bytes.Contains(p.calls[0].Params, []byte(`"url"`)) || p.calls[0].ID == p.calls[1].ID { t.Fatalf("calls %+v", p.calls) } } func itoa(n int64) string { raw, _ := json.Marshal(n) return string(raw) }