gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/rpc/rpcclient/client_test.go (about)

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