git.pirl.io/community/pirl@v0.0.0-20201111064343-9d3d31ff74be/rpc/client_test.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"math/rand"
    23  	"net"
    24  	"net/http"
    25  	"net/http/httptest"
    26  	"os"
    27  	"reflect"
    28  	"runtime"
    29  	"sync"
    30  	"testing"
    31  	"time"
    32  
    33  	"github.com/davecgh/go-spew/spew"
    34  	"git.pirl.io/community/pirl/log"
    35  )
    36  
    37  func TestClientRequest(t *testing.T) {
    38  	server := newTestServer()
    39  	defer server.Stop()
    40  	client := DialInProc(server)
    41  	defer client.Close()
    42  
    43  	var resp echoResult
    44  	if err := client.Call(&resp, "test_echo", "hello", 10, &echoArgs{"world"}); err != nil {
    45  		t.Fatal(err)
    46  	}
    47  	if !reflect.DeepEqual(resp, echoResult{"hello", 10, &echoArgs{"world"}}) {
    48  		t.Errorf("incorrect result %#v", resp)
    49  	}
    50  }
    51  
    52  func TestClientResponseType(t *testing.T) {
    53  	server := newTestServer()
    54  	defer server.Stop()
    55  	client := DialInProc(server)
    56  	defer client.Close()
    57  
    58  	if err := client.Call(nil, "test_echo", "hello", 10, &echoArgs{"world"}); err != nil {
    59  		t.Errorf("Passing nil as result should be fine, but got an error: %v", err)
    60  	}
    61  	var resultVar echoResult
    62  	// Note: passing the var, not a ref
    63  	err := client.Call(resultVar, "test_echo", "hello", 10, &echoArgs{"world"})
    64  	if err == nil {
    65  		t.Error("Passing a var as result should be an error")
    66  	}
    67  }
    68  
    69  func TestClientBatchRequest(t *testing.T) {
    70  	server := newTestServer()
    71  	defer server.Stop()
    72  	client := DialInProc(server)
    73  	defer client.Close()
    74  
    75  	batch := []BatchElem{
    76  		{
    77  			Method: "test_echo",
    78  			Args:   []interface{}{"hello", 10, &echoArgs{"world"}},
    79  			Result: new(echoResult),
    80  		},
    81  		{
    82  			Method: "test_echo",
    83  			Args:   []interface{}{"hello2", 11, &echoArgs{"world"}},
    84  			Result: new(echoResult),
    85  		},
    86  		{
    87  			Method: "no_such_method",
    88  			Args:   []interface{}{1, 2, 3},
    89  			Result: new(int),
    90  		},
    91  	}
    92  	if err := client.BatchCall(batch); err != nil {
    93  		t.Fatal(err)
    94  	}
    95  	wantResult := []BatchElem{
    96  		{
    97  			Method: "test_echo",
    98  			Args:   []interface{}{"hello", 10, &echoArgs{"world"}},
    99  			Result: &echoResult{"hello", 10, &echoArgs{"world"}},
   100  		},
   101  		{
   102  			Method: "test_echo",
   103  			Args:   []interface{}{"hello2", 11, &echoArgs{"world"}},
   104  			Result: &echoResult{"hello2", 11, &echoArgs{"world"}},
   105  		},
   106  		{
   107  			Method: "no_such_method",
   108  			Args:   []interface{}{1, 2, 3},
   109  			Result: new(int),
   110  			Error:  &jsonError{Code: -32601, Message: "the method no_such_method does not exist/is not available"},
   111  		},
   112  	}
   113  	if !reflect.DeepEqual(batch, wantResult) {
   114  		t.Errorf("batch results mismatch:\ngot %swant %s", spew.Sdump(batch), spew.Sdump(wantResult))
   115  	}
   116  }
   117  
   118  func TestClientNotify(t *testing.T) {
   119  	server := newTestServer()
   120  	defer server.Stop()
   121  	client := DialInProc(server)
   122  	defer client.Close()
   123  
   124  	if err := client.Notify(context.Background(), "test_echo", "hello", 10, &echoArgs{"world"}); err != nil {
   125  		t.Fatal(err)
   126  	}
   127  }
   128  
   129  // func TestClientCancelInproc(t *testing.T) { testClientCancel("inproc", t) }
   130  func TestClientCancelWebsocket(t *testing.T) { testClientCancel("ws", t) }
   131  func TestClientCancelHTTP(t *testing.T)      { testClientCancel("http", t) }
   132  func TestClientCancelIPC(t *testing.T)       { testClientCancel("ipc", t) }
   133  
   134  // This test checks that requests made through CallContext can be canceled by canceling
   135  // the context.
   136  func testClientCancel(transport string, t *testing.T) {
   137  	// These tests take a lot of time, run them all at once.
   138  	// You probably want to run with -parallel 1 or comment out
   139  	// the call to t.Parallel if you enable the logging.
   140  	t.Parallel()
   141  
   142  	server := newTestServer()
   143  	defer server.Stop()
   144  
   145  	// What we want to achieve is that the context gets canceled
   146  	// at various stages of request processing. The interesting cases
   147  	// are:
   148  	//  - cancel during dial
   149  	//  - cancel while performing a HTTP request
   150  	//  - cancel while waiting for a response
   151  	//
   152  	// To trigger those, the times are chosen such that connections
   153  	// are killed within the deadline for every other call (maxKillTimeout
   154  	// is 2x maxCancelTimeout).
   155  	//
   156  	// Once a connection is dead, there is a fair chance it won't connect
   157  	// successfully because the accept is delayed by 1s.
   158  	maxContextCancelTimeout := 300 * time.Millisecond
   159  	fl := &flakeyListener{
   160  		maxAcceptDelay: 1 * time.Second,
   161  		maxKillTimeout: 600 * time.Millisecond,
   162  	}
   163  
   164  	var client *Client
   165  	switch transport {
   166  	case "ws", "http":
   167  		c, hs := httpTestClient(server, transport, fl)
   168  		defer hs.Close()
   169  		client = c
   170  	case "ipc":
   171  		c, l := ipcTestClient(server, fl)
   172  		defer l.Close()
   173  		client = c
   174  	default:
   175  		panic("unknown transport: " + transport)
   176  	}
   177  
   178  	// The actual test starts here.
   179  	var (
   180  		wg       sync.WaitGroup
   181  		nreqs    = 10
   182  		ncallers = 6
   183  	)
   184  	caller := func(index int) {
   185  		defer wg.Done()
   186  		for i := 0; i < nreqs; i++ {
   187  			var (
   188  				ctx     context.Context
   189  				cancel  func()
   190  				timeout = time.Duration(rand.Int63n(int64(maxContextCancelTimeout)))
   191  			)
   192  			if index < ncallers/2 {
   193  				// For half of the callers, create a context without deadline
   194  				// and cancel it later.
   195  				ctx, cancel = context.WithCancel(context.Background())
   196  				time.AfterFunc(timeout, cancel)
   197  			} else {
   198  				// For the other half, create a context with a deadline instead. This is
   199  				// different because the context deadline is used to set the socket write
   200  				// deadline.
   201  				ctx, cancel = context.WithTimeout(context.Background(), timeout)
   202  			}
   203  			// Now perform a call with the context.
   204  			// The key thing here is that no call will ever complete successfully.
   205  			sleepTime := maxContextCancelTimeout + 20*time.Millisecond
   206  			err := client.CallContext(ctx, nil, "test_sleep", sleepTime)
   207  			if err != nil {
   208  				log.Debug(fmt.Sprint("got expected error:", err))
   209  			} else {
   210  				t.Errorf("no error for call with %v wait time", timeout)
   211  			}
   212  			cancel()
   213  		}
   214  	}
   215  	wg.Add(ncallers)
   216  	for i := 0; i < ncallers; i++ {
   217  		go caller(i)
   218  	}
   219  	wg.Wait()
   220  }
   221  
   222  func TestClientSubscribeInvalidArg(t *testing.T) {
   223  	server := newTestServer()
   224  	defer server.Stop()
   225  	client := DialInProc(server)
   226  	defer client.Close()
   227  
   228  	check := func(shouldPanic bool, arg interface{}) {
   229  		defer func() {
   230  			err := recover()
   231  			if shouldPanic && err == nil {
   232  				t.Errorf("EthSubscribe should've panicked for %#v", arg)
   233  			}
   234  			if !shouldPanic && err != nil {
   235  				t.Errorf("EthSubscribe shouldn't have panicked for %#v", arg)
   236  				buf := make([]byte, 1024*1024)
   237  				buf = buf[:runtime.Stack(buf, false)]
   238  				t.Error(err)
   239  				t.Error(string(buf))
   240  			}
   241  		}()
   242  		client.EthSubscribe(context.Background(), arg, "foo_bar")
   243  	}
   244  	check(true, nil)
   245  	check(true, 1)
   246  	check(true, (chan int)(nil))
   247  	check(true, make(<-chan int))
   248  	check(false, make(chan int))
   249  	check(false, make(chan<- int))
   250  }
   251  
   252  func TestClientSubscribe(t *testing.T) {
   253  	server := newTestServer()
   254  	defer server.Stop()
   255  	client := DialInProc(server)
   256  	defer client.Close()
   257  
   258  	nc := make(chan int)
   259  	count := 10
   260  	sub, err := client.Subscribe(context.Background(), "nftest", nc, "someSubscription", count, 0)
   261  	if err != nil {
   262  		t.Fatal("can't subscribe:", err)
   263  	}
   264  	for i := 0; i < count; i++ {
   265  		if val := <-nc; val != i {
   266  			t.Fatalf("value mismatch: got %d, want %d", val, i)
   267  		}
   268  	}
   269  
   270  	sub.Unsubscribe()
   271  	select {
   272  	case v := <-nc:
   273  		t.Fatal("received value after unsubscribe:", v)
   274  	case err := <-sub.Err():
   275  		if err != nil {
   276  			t.Fatalf("Err returned a non-nil error after explicit unsubscribe: %q", err)
   277  		}
   278  	case <-time.After(1 * time.Second):
   279  		t.Fatalf("subscription not closed within 1s after unsubscribe")
   280  	}
   281  }
   282  
   283  // In this test, the connection drops while Subscribe is waiting for a response.
   284  func TestClientSubscribeClose(t *testing.T) {
   285  	server := newTestServer()
   286  	service := &notificationTestService{
   287  		gotHangSubscriptionReq:  make(chan struct{}),
   288  		unblockHangSubscription: make(chan struct{}),
   289  	}
   290  	if err := server.RegisterName("nftest2", service); err != nil {
   291  		t.Fatal(err)
   292  	}
   293  
   294  	defer server.Stop()
   295  	client := DialInProc(server)
   296  	defer client.Close()
   297  
   298  	var (
   299  		nc   = make(chan int)
   300  		errc = make(chan error, 1)
   301  		sub  *ClientSubscription
   302  		err  error
   303  	)
   304  	go func() {
   305  		sub, err = client.Subscribe(context.Background(), "nftest2", nc, "hangSubscription", 999)
   306  		errc <- err
   307  	}()
   308  
   309  	<-service.gotHangSubscriptionReq
   310  	client.Close()
   311  	service.unblockHangSubscription <- struct{}{}
   312  
   313  	select {
   314  	case err := <-errc:
   315  		if err == nil {
   316  			t.Errorf("Subscribe returned nil error after Close")
   317  		}
   318  		if sub != nil {
   319  			t.Error("Subscribe returned non-nil subscription after Close")
   320  		}
   321  	case <-time.After(1 * time.Second):
   322  		t.Fatalf("Subscribe did not return within 1s after Close")
   323  	}
   324  }
   325  
   326  // This test reproduces https://git.pirl.io/community/pirl/issues/17837 where the
   327  // client hangs during shutdown when Unsubscribe races with Client.Close.
   328  func TestClientCloseUnsubscribeRace(t *testing.T) {
   329  	server := newTestServer()
   330  	defer server.Stop()
   331  
   332  	for i := 0; i < 20; i++ {
   333  		client := DialInProc(server)
   334  		nc := make(chan int)
   335  		sub, err := client.Subscribe(context.Background(), "nftest", nc, "someSubscription", 3, 1)
   336  		if err != nil {
   337  			t.Fatal(err)
   338  		}
   339  		go client.Close()
   340  		go sub.Unsubscribe()
   341  		select {
   342  		case <-sub.Err():
   343  		case <-time.After(5 * time.Second):
   344  			t.Fatal("subscription not closed within timeout")
   345  		}
   346  	}
   347  }
   348  
   349  // This test checks that Client doesn't lock up when a single subscriber
   350  // doesn't read subscription events.
   351  func TestClientNotificationStorm(t *testing.T) {
   352  	server := newTestServer()
   353  	defer server.Stop()
   354  
   355  	doTest := func(count int, wantError bool) {
   356  		client := DialInProc(server)
   357  		defer client.Close()
   358  		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
   359  		defer cancel()
   360  
   361  		// Subscribe on the server. It will start sending many notifications
   362  		// very quickly.
   363  		nc := make(chan int)
   364  		sub, err := client.Subscribe(ctx, "nftest", nc, "someSubscription", count, 0)
   365  		if err != nil {
   366  			t.Fatal("can't subscribe:", err)
   367  		}
   368  		defer sub.Unsubscribe()
   369  
   370  		// Process each notification, try to run a call in between each of them.
   371  		for i := 0; i < count; i++ {
   372  			select {
   373  			case val := <-nc:
   374  				if val != i {
   375  					t.Fatalf("(%d/%d) unexpected value %d", i, count, val)
   376  				}
   377  			case err := <-sub.Err():
   378  				if wantError && err != ErrSubscriptionQueueOverflow {
   379  					t.Fatalf("(%d/%d) got error %q, want %q", i, count, err, ErrSubscriptionQueueOverflow)
   380  				} else if !wantError {
   381  					t.Fatalf("(%d/%d) got unexpected error %q", i, count, err)
   382  				}
   383  				return
   384  			}
   385  			var r int
   386  			err := client.CallContext(ctx, &r, "nftest_echo", i)
   387  			if err != nil {
   388  				if !wantError {
   389  					t.Fatalf("(%d/%d) call error: %v", i, count, err)
   390  				}
   391  				return
   392  			}
   393  		}
   394  		if wantError {
   395  			t.Fatalf("didn't get expected error")
   396  		}
   397  	}
   398  
   399  	doTest(8000, false)
   400  	doTest(23000, true)
   401  }
   402  
   403  func TestClientHTTP(t *testing.T) {
   404  	server := newTestServer()
   405  	defer server.Stop()
   406  
   407  	client, hs := httpTestClient(server, "http", nil)
   408  	defer hs.Close()
   409  	defer client.Close()
   410  
   411  	// Launch concurrent requests.
   412  	var (
   413  		results    = make([]echoResult, 100)
   414  		errc       = make(chan error)
   415  		wantResult = echoResult{"a", 1, new(echoArgs)}
   416  	)
   417  	defer client.Close()
   418  	for i := range results {
   419  		i := i
   420  		go func() {
   421  			errc <- client.Call(&results[i], "test_echo",
   422  				wantResult.String, wantResult.Int, wantResult.Args)
   423  		}()
   424  	}
   425  
   426  	// Wait for all of them to complete.
   427  	timeout := time.NewTimer(5 * time.Second)
   428  	defer timeout.Stop()
   429  	for i := range results {
   430  		select {
   431  		case err := <-errc:
   432  			if err != nil {
   433  				t.Fatal(err)
   434  			}
   435  		case <-timeout.C:
   436  			t.Fatalf("timeout (got %d/%d) results)", i+1, len(results))
   437  		}
   438  	}
   439  
   440  	// Check results.
   441  	for i := range results {
   442  		if !reflect.DeepEqual(results[i], wantResult) {
   443  			t.Errorf("result %d mismatch: got %#v, want %#v", i, results[i], wantResult)
   444  		}
   445  	}
   446  }
   447  
   448  func TestClientReconnect(t *testing.T) {
   449  	startServer := func(addr string) (*Server, net.Listener) {
   450  		srv := newTestServer()
   451  		l, err := net.Listen("tcp", addr)
   452  		if err != nil {
   453  			t.Fatal("can't listen:", err)
   454  		}
   455  		go http.Serve(l, srv.WebsocketHandler([]string{"*"}))
   456  		return srv, l
   457  	}
   458  
   459  	ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
   460  	defer cancel()
   461  
   462  	// Start a server and corresponding client.
   463  	s1, l1 := startServer("127.0.0.1:0")
   464  	client, err := DialContext(ctx, "ws://"+l1.Addr().String())
   465  	if err != nil {
   466  		t.Fatal("can't dial", err)
   467  	}
   468  
   469  	// Perform a call. This should work because the server is up.
   470  	var resp echoResult
   471  	if err := client.CallContext(ctx, &resp, "test_echo", "", 1, nil); err != nil {
   472  		t.Fatal(err)
   473  	}
   474  
   475  	// Shut down the server and allow for some cool down time so we can listen on the same
   476  	// address again.
   477  	l1.Close()
   478  	s1.Stop()
   479  	time.Sleep(2 * time.Second)
   480  
   481  	// Try calling again. It shouldn't work.
   482  	if err := client.CallContext(ctx, &resp, "test_echo", "", 2, nil); err == nil {
   483  		t.Error("successful call while the server is down")
   484  		t.Logf("resp: %#v", resp)
   485  	}
   486  
   487  	// Start it up again and call again. The connection should be reestablished.
   488  	// We spawn multiple calls here to check whether this hangs somehow.
   489  	s2, l2 := startServer(l1.Addr().String())
   490  	defer l2.Close()
   491  	defer s2.Stop()
   492  
   493  	start := make(chan struct{})
   494  	errors := make(chan error, 20)
   495  	for i := 0; i < cap(errors); i++ {
   496  		go func() {
   497  			<-start
   498  			var resp echoResult
   499  			errors <- client.CallContext(ctx, &resp, "test_echo", "", 3, nil)
   500  		}()
   501  	}
   502  	close(start)
   503  	errcount := 0
   504  	for i := 0; i < cap(errors); i++ {
   505  		if err = <-errors; err != nil {
   506  			errcount++
   507  		}
   508  	}
   509  	t.Logf("%d errors, last error: %v", errcount, err)
   510  	if errcount > 1 {
   511  		t.Errorf("expected one error after disconnect, got %d", errcount)
   512  	}
   513  }
   514  
   515  func httpTestClient(srv *Server, transport string, fl *flakeyListener) (*Client, *httptest.Server) {
   516  	// Create the HTTP server.
   517  	var hs *httptest.Server
   518  	switch transport {
   519  	case "ws":
   520  		hs = httptest.NewUnstartedServer(srv.WebsocketHandler([]string{"*"}))
   521  	case "http":
   522  		hs = httptest.NewUnstartedServer(srv)
   523  	default:
   524  		panic("unknown HTTP transport: " + transport)
   525  	}
   526  	// Wrap the listener if required.
   527  	if fl != nil {
   528  		fl.Listener = hs.Listener
   529  		hs.Listener = fl
   530  	}
   531  	// Connect the client.
   532  	hs.Start()
   533  	client, err := Dial(transport + "://" + hs.Listener.Addr().String())
   534  	if err != nil {
   535  		panic(err)
   536  	}
   537  	return client, hs
   538  }
   539  
   540  func ipcTestClient(srv *Server, fl *flakeyListener) (*Client, net.Listener) {
   541  	// Listen on a random endpoint.
   542  	endpoint := fmt.Sprintf("go-ethereum-test-ipc-%d-%d", os.Getpid(), rand.Int63())
   543  	if runtime.GOOS == "windows" {
   544  		endpoint = `\\.\pipe\` + endpoint
   545  	} else {
   546  		endpoint = os.TempDir() + "/" + endpoint
   547  	}
   548  	l, err := ipcListen(endpoint)
   549  	if err != nil {
   550  		panic(err)
   551  	}
   552  	// Connect the listener to the server.
   553  	if fl != nil {
   554  		fl.Listener = l
   555  		l = fl
   556  	}
   557  	go srv.ServeListener(l)
   558  	// Connect the client.
   559  	client, err := Dial(endpoint)
   560  	if err != nil {
   561  		panic(err)
   562  	}
   563  	return client, l
   564  }
   565  
   566  // flakeyListener kills accepted connections after a random timeout.
   567  type flakeyListener struct {
   568  	net.Listener
   569  	maxKillTimeout time.Duration
   570  	maxAcceptDelay time.Duration
   571  }
   572  
   573  func (l *flakeyListener) Accept() (net.Conn, error) {
   574  	delay := time.Duration(rand.Int63n(int64(l.maxAcceptDelay)))
   575  	time.Sleep(delay)
   576  
   577  	c, err := l.Listener.Accept()
   578  	if err == nil {
   579  		timeout := time.Duration(rand.Int63n(int64(l.maxKillTimeout)))
   580  		time.AfterFunc(timeout, func() {
   581  			log.Debug(fmt.Sprintf("killing conn %v after %v", c.LocalAddr(), timeout))
   582  			c.Close()
   583  		})
   584  	}
   585  	return c, err
   586  }