1
0
mirror of https://github.com/golang/go synced 2024-10-01 04:18:33 -06:00
go/internal/jsonrpc2/serve_test.go
Rob Findley 9ffc0ab4ef internal/jsonrpc2: add an idle timeout for stream serving
When running gopls against an automatically started remote instance, we
want the lifecycle of the remote to be detached from that of its
clients, so that it doesn't shut down while clients are still connected.
On the other hand, a gopls process can consume significant resources, so
we don't want it to remain when there are no more connected clients.

The jsonrpc2 package is updated to support the concept of idle timeout:
a duration after which the server is shut down when there are no
connected clients. This is exposed in the gopls serve command via the
-listen.timeout flag.

Update golang/go#34111

Change-Id: Id62b3d4a2fa66de2c9306d130ca431717f01d1e5
Reviewed-on: https://go-review.googlesource.com/c/tools/+/220281
Run-TryBot: Robert Findley <rfindley@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-02-24 23:06:35 +00:00

60 lines
1.2 KiB
Go

// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package jsonrpc2
import (
"context"
"net"
"sync"
"testing"
"time"
)
func TestIdleTimeout(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
ln, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
connect := func() net.Conn {
conn, err := net.DialTimeout("tcp", ln.Addr().String(), 5*time.Second)
if err != nil {
panic(err)
}
return conn
}
server := HandlerServer(EmptyHandler{})
// connTimer := &fakeTimer{c: make(chan time.Time, 1)}
var (
runErr error
wg sync.WaitGroup
)
wg.Add(1)
go func() {
defer wg.Done()
runErr = Serve(ctx, ln, server, 100*time.Millisecond)
}()
// Exercise some connection/disconnection patterns, and then assert that when
// our timer fires, the server exits.
conn1 := connect()
conn2 := connect()
conn1.Close()
conn2.Close()
conn3 := connect()
conn3.Close()
wg.Wait()
if runErr != ErrIdleTimeout {
t.Errorf("run() returned error %v, want %v", runErr, ErrIdleTimeout)
}
}