| 1 | // Copyright 2020 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package jsonrpc2_test |
| 6 | |
| 7 | import ( |
| 8 | "context" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "runtime" |
| 12 | "runtime/debug" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | jsonrpc2 "golang.org/x/tools/internal/jsonrpc2_v2" |
| 17 | ) |
| 18 | |
| 19 | // needsLocalhostNet skips t if networking does not work for ports opened |
| 20 | // with "localhost". |
| 21 | // forked from golang.org/x/tools/internal/testenv. |
| 22 | func needsLocalhostNet(t testing.TB) { |
| 23 | switch runtime.GOOS { |
| 24 | case "js", "wasip1": |
| 25 | t.Skipf(`Listening on "localhost" fails on %s; see https://go.dev/issue/59718`, runtime.GOOS) |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | func TestIdleTimeout(t *testing.T) { |
| 30 | needsLocalhostNet(t) |
| 31 | |
| 32 | // Use a panicking time.AfterFunc instead of context.WithTimeout so that we |
| 33 | // get a goroutine dump on failure. We expect the test to take on the order of |
| 34 | // a few tens of milliseconds at most, so 10s should be several orders of |
| 35 | // magnitude of headroom. |
| 36 | timer := time.AfterFunc(10*time.Second, func() { |
| 37 | debug.SetTraceback("all") |
| 38 | panic("TestIdleTimeout deadlocked") |
| 39 | }) |
| 40 | defer timer.Stop() |
| 41 | |
| 42 | ctx := context.Background() |
| 43 | |
| 44 | try := func(d time.Duration) (longEnough bool) { |
| 45 | listener, err := jsonrpc2.NetListener(ctx, "tcp", "localhost:0", jsonrpc2.NetListenOptions{}) |
| 46 | if err != nil { |
| 47 | t.Fatal(err) |
| 48 | } |
| 49 | |
| 50 | idleStart := time.Now() |
| 51 | listener = jsonrpc2.NewIdleListener(d, listener) |
| 52 | defer listener.Close() |
| 53 | |
| 54 | server := jsonrpc2.NewServer(ctx, listener, jsonrpc2.ConnectionOptions{}) |
| 55 | |
| 56 | // Exercise some connection/disconnection patterns, and then assert that when |
| 57 | // our timer fires, the server exits. |
| 58 | conn1, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{}, nil) |
| 59 | if err != nil { |
| 60 | if since := time.Since(idleStart); since < d { |
| 61 | t.Fatalf("conn1 failed to connect after %v: %v", since, err) |
| 62 | } |
| 63 | t.Log("jsonrpc2.Dial:", err) |
| 64 | return false // Took to long to dial, so the failure could have been due to the idle timeout. |
| 65 | } |
| 66 | // On the server side, Accept can race with the connection timing out. |
| 67 | // Send a call and wait for the response to ensure that the connection was |
| 68 | // actually fully accepted. |
| 69 | ac := conn1.Call(ctx, "ping", nil) |
| 70 | if err := ac.Await(ctx, nil); !errors.Is(err, jsonrpc2.ErrMethodNotFound) { |
| 71 | if since := time.Since(idleStart); since < d { |
| 72 | t.Fatalf("conn1 broken after %v: %v", since, err) |
| 73 | } |
| 74 | t.Log(`conn1.Call(ctx, "ping", nil):`, err) |
| 75 | conn1.Close() |
| 76 | return false |
| 77 | } |
| 78 | |
| 79 | // Since conn1 was successfully accepted and remains open, the server is |
| 80 | // definitely non-idle. Dialing another simultaneous connection should |
| 81 | // succeed. |
| 82 | conn2, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{}, nil) |
| 83 | if err != nil { |
| 84 | conn1.Close() |
| 85 | t.Fatalf("conn2 failed to connect while non-idle after %v: %v", time.Since(idleStart), err) |
| 86 | return false |
| 87 | } |
| 88 | // Ensure that conn2 is also accepted on the server side before we close |
| 89 | // conn1. Otherwise, the connection can appear idle if the server processes |
| 90 | // the closure of conn1 and the idle timeout before it finally notices conn2 |
| 91 | // in the accept queue. |
| 92 | // (That failure mode may explain the failure noted in |
| 93 | // https://go.dev/issue/49387#issuecomment-1303979877.) |
| 94 | ac = conn2.Call(ctx, "ping", nil) |
| 95 | if err := ac.Await(ctx, nil); !errors.Is(err, jsonrpc2.ErrMethodNotFound) { |
| 96 | t.Fatalf("conn2 broken while non-idle after %v: %v", time.Since(idleStart), err) |
| 97 | } |
| 98 | |
| 99 | if err := conn1.Close(); err != nil { |
| 100 | t.Fatalf("conn1.Close failed with error: %v", err) |
| 101 | } |
| 102 | idleStart = time.Now() |
| 103 | if err := conn2.Close(); err != nil { |
| 104 | t.Fatalf("conn2.Close failed with error: %v", err) |
| 105 | } |
| 106 | |
| 107 | conn3, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{}, nil) |
| 108 | if err != nil { |
| 109 | if since := time.Since(idleStart); since < d { |
| 110 | t.Fatalf("conn3 failed to connect after %v: %v", since, err) |
| 111 | } |
| 112 | t.Log("jsonrpc2.Dial:", err) |
| 113 | return false // Took to long to dial, so the failure could have been due to the idle timeout. |
| 114 | } |
| 115 | |
| 116 | ac = conn3.Call(ctx, "ping", nil) |
| 117 | if err := ac.Await(ctx, nil); !errors.Is(err, jsonrpc2.ErrMethodNotFound) { |
| 118 | if since := time.Since(idleStart); since < d { |
| 119 | t.Fatalf("conn3 broken after %v: %v", since, err) |
| 120 | } |
| 121 | t.Log(`conn3.Call(ctx, "ping", nil):`, err) |
| 122 | conn3.Close() |
| 123 | return false |
| 124 | } |
| 125 | |
| 126 | idleStart = time.Now() |
| 127 | if err := conn3.Close(); err != nil { |
| 128 | t.Fatalf("conn3.Close failed with error: %v", err) |
| 129 | } |
| 130 | |
| 131 | serverError := server.Wait() |
| 132 | |
| 133 | if !errors.Is(serverError, jsonrpc2.ErrIdleTimeout) { |
| 134 | t.Errorf("run() returned error %v, want %v", serverError, jsonrpc2.ErrIdleTimeout) |
| 135 | } |
| 136 | if since := time.Since(idleStart); since < d { |
| 137 | t.Errorf("server shut down after %v idle; want at least %v", since, d) |
| 138 | } |
| 139 | return true |
| 140 | } |
| 141 | |
| 142 | d := 1 * time.Millisecond |
| 143 | for { |
| 144 | t.Logf("testing with idle timeout %v", d) |
| 145 | if !try(d) { |
| 146 | d *= 2 |
| 147 | continue |
| 148 | } |
| 149 | break |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | type msg struct { |
| 154 | Msg string |
| 155 | } |
| 156 | |
| 157 | type fakeHandler struct{} |
| 158 | |
| 159 | func (fakeHandler) Handle(ctx context.Context, req *jsonrpc2.Request) (any, error) { |
| 160 | switch req.Method { |
| 161 | case "ping": |
| 162 | return &msg{"pong"}, nil |
| 163 | default: |
| 164 | return nil, jsonrpc2.ErrNotHandled |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | func TestServe(t *testing.T) { |
| 169 | ctx := context.Background() |
| 170 | |
| 171 | tests := []struct { |
| 172 | name string |
| 173 | factory func(context.Context, testing.TB) (jsonrpc2.Listener, error) |
| 174 | }{ |
| 175 | {"tcp", func(ctx context.Context, t testing.TB) (jsonrpc2.Listener, error) { |
| 176 | needsLocalhostNet(t) |
| 177 | return jsonrpc2.NetListener(ctx, "tcp", "localhost:0", jsonrpc2.NetListenOptions{}) |
| 178 | }}, |
| 179 | {"pipe", func(ctx context.Context, t testing.TB) (jsonrpc2.Listener, error) { |
| 180 | return jsonrpc2.NetPipeListener(ctx) |
| 181 | }}, |
| 182 | } |
| 183 | |
| 184 | for _, test := range tests { |
| 185 | t.Run(test.name, func(t *testing.T) { |
| 186 | fake, err := test.factory(ctx, t) |
| 187 | if err != nil { |
| 188 | t.Fatal(err) |
| 189 | } |
| 190 | conn, shutdown, err := newFake(t, ctx, fake) |
| 191 | if err != nil { |
| 192 | t.Fatal(err) |
| 193 | } |
| 194 | defer shutdown() |
| 195 | var got msg |
| 196 | if err := conn.Call(ctx, "ping", &msg{"ting"}).Await(ctx, &got); err != nil { |
| 197 | t.Fatal(err) |
| 198 | } |
| 199 | if want := "pong"; got.Msg != want { |
| 200 | t.Errorf("conn.Call(...): returned %q, want %q", got, want) |
| 201 | } |
| 202 | }) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | func newFake(t *testing.T, ctx context.Context, l jsonrpc2.Listener) (*jsonrpc2.Connection, func(), error) { |
| 207 | server := jsonrpc2.NewServer(ctx, l, jsonrpc2.ConnectionOptions{ |
| 208 | Handler: fakeHandler{}, |
| 209 | }) |
| 210 | |
| 211 | client, err := jsonrpc2.Dial(ctx, |
| 212 | l.Dialer(), |
| 213 | jsonrpc2.ConnectionOptions{ |
| 214 | Handler: fakeHandler{}, |
| 215 | }, nil) |
| 216 | if err != nil { |
| 217 | return nil, nil, err |
| 218 | } |
| 219 | return client, func() { |
| 220 | if err := l.Close(); err != nil { |
| 221 | t.Fatal(err) |
| 222 | } |
| 223 | if err := client.Close(); err != nil { |
| 224 | t.Fatal(err) |
| 225 | } |
| 226 | server.Wait() |
| 227 | }, nil |
| 228 | } |
| 229 | |
| 230 | // TestIdleListenerAcceptCloseRace checks for the Accept/Close race fixed in CL 388597. |
| 231 | // |
| 232 | // (A bug in the idleListener implementation caused a successful Accept to block |
| 233 | // on sending to a background goroutine that could have already exited.) |
| 234 | func TestIdleListenerAcceptCloseRace(t *testing.T) { |
| 235 | ctx := context.Background() |
| 236 | |
| 237 | n := 10 |
| 238 | |
| 239 | // Each iteration of the loop appears to take around a millisecond, so to |
| 240 | // avoid spurious failures we'll set the watchdog for three orders of |
| 241 | // magnitude longer. When the bug was present, this reproduced the deadlock |
| 242 | // reliably on a Linux workstation when run with -count=100, which should be |
| 243 | // frequent enough to show up on the Go build dashboard if it regresses. |
| 244 | watchdog := time.Duration(n) * 1000 * time.Millisecond |
| 245 | timer := time.AfterFunc(watchdog, func() { |
| 246 | debug.SetTraceback("all") |
| 247 | panic(fmt.Sprintf("%s deadlocked after %v", t.Name(), watchdog)) |
| 248 | }) |
| 249 | defer timer.Stop() |
| 250 | |
| 251 | for ; n > 0; n-- { |
| 252 | listener, err := jsonrpc2.NetPipeListener(ctx) |
| 253 | if err != nil { |
| 254 | t.Fatal(err) |
| 255 | } |
| 256 | listener = jsonrpc2.NewIdleListener(24*time.Hour, listener) |
| 257 | |
| 258 | done := make(chan struct{}) |
| 259 | go func() { |
| 260 | conn, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{}, nil) |
| 261 | listener.Close() |
| 262 | if err == nil { |
| 263 | conn.Close() |
| 264 | } |
| 265 | close(done) |
| 266 | }() |
| 267 | |
| 268 | // Accept may return a non-nil error if Close closes the underlying network |
| 269 | // connection before the wrapped Accept call unblocks. However, it must not |
| 270 | // deadlock! |
| 271 | c, err := listener.Accept(ctx) |
| 272 | if err == nil { |
| 273 | c.Close() |
| 274 | } |
| 275 | <-done |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | // TestCloseCallRace checks for a race resulting in a deadlock when a Call on |
| 280 | // one side of the connection races with a Close (or otherwise broken |
| 281 | // connection) initiated from the other side. |
| 282 | // |
| 283 | // (The Call method was waiting for a result from the Read goroutine to |
| 284 | // determine which error value to return, but the Read goroutine was waiting for |
| 285 | // in-flight calls to complete before reporting that result.) |
| 286 | func TestCloseCallRace(t *testing.T) { |
| 287 | ctx := context.Background() |
| 288 | n := 10 |
| 289 | |
| 290 | watchdog := time.Duration(n) * 1000 * time.Millisecond |
| 291 | timer := time.AfterFunc(watchdog, func() { |
| 292 | debug.SetTraceback("all") |
| 293 | panic(fmt.Sprintf("%s deadlocked after %v", t.Name(), watchdog)) |
| 294 | }) |
| 295 | defer timer.Stop() |
| 296 | |
| 297 | for ; n > 0; n-- { |
| 298 | listener, err := jsonrpc2.NetPipeListener(ctx) |
| 299 | if err != nil { |
| 300 | t.Fatal(err) |
| 301 | } |
| 302 | |
| 303 | pokec := make(chan *jsonrpc2.AsyncCall, 1) |
| 304 | |
| 305 | s := jsonrpc2.NewServer(ctx, listener, jsonrpc2.BinderFunc(func(_ context.Context, srvConn *jsonrpc2.Connection) jsonrpc2.ConnectionOptions { |
| 306 | h := jsonrpc2.HandlerFunc(func(ctx context.Context, _ *jsonrpc2.Request) (any, error) { |
| 307 | // Start a concurrent call from the server to the client. |
| 308 | // The point of this test is to ensure this doesn't deadlock |
| 309 | // if the client shuts down the connection concurrently. |
| 310 | // |
| 311 | // The racing Call may or may not receive a response: it should get a |
| 312 | // response if it is sent before the client closes the connection, and |
| 313 | // it should fail with some kind of "connection closed" error otherwise. |
| 314 | go func() { |
| 315 | pokec <- srvConn.Call(ctx, "poke", nil) |
| 316 | }() |
| 317 | |
| 318 | return &msg{"pong"}, nil |
| 319 | }) |
| 320 | return jsonrpc2.ConnectionOptions{Handler: h} |
| 321 | })) |
| 322 | |
| 323 | dialConn, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{}, nil) |
| 324 | if err != nil { |
| 325 | listener.Close() |
| 326 | s.Wait() |
| 327 | t.Fatal(err) |
| 328 | } |
| 329 | |
| 330 | // Calling any method on the server should provoke it to asynchronously call |
| 331 | // us back. While it is starting that call, we will close the connection. |
| 332 | if err := dialConn.Call(ctx, "ping", nil).Await(ctx, nil); err != nil { |
| 333 | t.Error(err) |
| 334 | } |
| 335 | if err := dialConn.Close(); err != nil { |
| 336 | t.Error(err) |
| 337 | } |
| 338 | |
| 339 | // Ensure that the Call on the server side did not block forever when the |
| 340 | // connection closed. |
| 341 | pokeCall := <-pokec |
| 342 | if err := pokeCall.Await(ctx, nil); err == nil { |
| 343 | t.Errorf("unexpected nil error from server-initited call") |
| 344 | } else if errors.Is(err, jsonrpc2.ErrMethodNotFound) { |
| 345 | // The call completed before the Close reached the handler. |
| 346 | } else { |
| 347 | // The error was something else. |
| 348 | t.Logf("server-initiated call completed with expected error: %v", err) |
| 349 | } |
| 350 | |
| 351 | listener.Close() |
| 352 | s.Wait() |
| 353 | } |
| 354 | } |