subscription_test.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. package rpc
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "net"
  21. "strings"
  22. "testing"
  23. "time"
  24. )
  25. func TestNewID(t *testing.T) {
  26. hexchars := "0123456789ABCDEFabcdef"
  27. for i := 0; i < 100; i++ {
  28. id := string(NewID())
  29. if !strings.HasPrefix(id, "0x") {
  30. t.Fatalf("invalid ID prefix, want '0x...', got %s", id)
  31. }
  32. id = id[2:]
  33. if len(id) == 0 || len(id) > 32 {
  34. t.Fatalf("invalid ID length, want len(id) > 0 && len(id) <= 32), got %d", len(id))
  35. }
  36. for i := 0; i < len(id); i++ {
  37. if strings.IndexByte(hexchars, id[i]) == -1 {
  38. t.Fatalf("unexpected byte, want any valid hex char, got %c", id[i])
  39. }
  40. }
  41. }
  42. }
  43. func TestSubscriptions(t *testing.T) {
  44. var (
  45. namespaces = []string{"eth", "bzz"}
  46. service = &notificationTestService{}
  47. subCount = len(namespaces)
  48. notificationCount = 3
  49. server = NewServer()
  50. clientConn, serverConn = net.Pipe()
  51. out = json.NewEncoder(clientConn)
  52. in = json.NewDecoder(clientConn)
  53. successes = make(chan subConfirmation)
  54. notifications = make(chan subscriptionResult)
  55. errors = make(chan error, subCount*notificationCount+1)
  56. )
  57. // setup and start server
  58. for _, namespace := range namespaces {
  59. if err := server.RegisterName(namespace, service); err != nil {
  60. t.Fatalf("unable to register test service %v", err)
  61. }
  62. }
  63. go server.ServeCodec(NewCodec(serverConn), 0)
  64. defer server.Stop()
  65. // wait for message and write them to the given channels
  66. go waitForMessages(in, successes, notifications, errors)
  67. // create subscriptions one by one
  68. for i, namespace := range namespaces {
  69. request := map[string]interface{}{
  70. "id": i,
  71. "method": fmt.Sprintf("%s_subscribe", namespace),
  72. "version": "2.0",
  73. "params": []interface{}{"someSubscription", notificationCount, i},
  74. }
  75. if err := out.Encode(&request); err != nil {
  76. t.Fatalf("Could not create subscription: %v", err)
  77. }
  78. }
  79. timeout := time.After(30 * time.Second)
  80. subids := make(map[string]string, subCount)
  81. count := make(map[string]int, subCount)
  82. allReceived := func() bool {
  83. done := len(count) == subCount
  84. for _, c := range count {
  85. if c < notificationCount {
  86. done = false
  87. }
  88. }
  89. return done
  90. }
  91. for !allReceived() {
  92. select {
  93. case confirmation := <-successes: // subscription created
  94. subids[namespaces[confirmation.reqid]] = string(confirmation.subid)
  95. case notification := <-notifications:
  96. count[notification.ID]++
  97. case err := <-errors:
  98. t.Fatal(err)
  99. case <-timeout:
  100. for _, namespace := range namespaces {
  101. subid, found := subids[namespace]
  102. if !found {
  103. t.Errorf("subscription for %q not created", namespace)
  104. continue
  105. }
  106. if count, found := count[subid]; !found || count < notificationCount {
  107. t.Errorf("didn't receive all notifications (%d<%d) in time for namespace %q", count, notificationCount, namespace)
  108. }
  109. }
  110. t.Fatal("timed out")
  111. }
  112. }
  113. }
  114. // This test checks that unsubscribing works.
  115. func TestServerUnsubscribe(t *testing.T) {
  116. p1, p2 := net.Pipe()
  117. defer p2.Close()
  118. // Start the server.
  119. server := newTestServer()
  120. service := &notificationTestService{unsubscribed: make(chan string, 1)}
  121. server.RegisterName("nftest2", service)
  122. go server.ServeCodec(NewCodec(p1), 0)
  123. // Subscribe.
  124. p2.SetDeadline(time.Now().Add(10 * time.Second))
  125. p2.Write([]byte(`{"jsonrpc":"2.0","id":1,"method":"nftest2_subscribe","params":["someSubscription",0,10]}`))
  126. // Handle received messages.
  127. var (
  128. resps = make(chan subConfirmation)
  129. notifications = make(chan subscriptionResult)
  130. errors = make(chan error, 1)
  131. )
  132. go waitForMessages(json.NewDecoder(p2), resps, notifications, errors)
  133. // Receive the subscription ID.
  134. var sub subConfirmation
  135. select {
  136. case sub = <-resps:
  137. case err := <-errors:
  138. t.Fatal(err)
  139. }
  140. // Unsubscribe and check that it is handled on the server side.
  141. p2.Write([]byte(`{"jsonrpc":"2.0","method":"nftest2_unsubscribe","params":["` + sub.subid + `"]}`))
  142. for {
  143. select {
  144. case id := <-service.unsubscribed:
  145. if id != string(sub.subid) {
  146. t.Errorf("wrong subscription ID unsubscribed")
  147. }
  148. return
  149. case err := <-errors:
  150. t.Fatal(err)
  151. case <-notifications:
  152. // drop notifications
  153. }
  154. }
  155. }
  156. type subConfirmation struct {
  157. reqid int
  158. subid ID
  159. }
  160. // waitForMessages reads RPC messages from 'in' and dispatches them into the given channels.
  161. // It stops if there is an error.
  162. func waitForMessages(in *json.Decoder, successes chan subConfirmation, notifications chan subscriptionResult, errors chan error) {
  163. for {
  164. resp, notification, err := readAndValidateMessage(in)
  165. if err != nil {
  166. errors <- err
  167. return
  168. } else if resp != nil {
  169. successes <- *resp
  170. } else {
  171. notifications <- *notification
  172. }
  173. }
  174. }
  175. func readAndValidateMessage(in *json.Decoder) (*subConfirmation, *subscriptionResult, error) {
  176. var msg jsonrpcMessage
  177. if err := in.Decode(&msg); err != nil {
  178. return nil, nil, fmt.Errorf("decode error: %v", err)
  179. }
  180. switch {
  181. case msg.isNotification():
  182. var res subscriptionResult
  183. if err := json.Unmarshal(msg.Params, &res); err != nil {
  184. return nil, nil, fmt.Errorf("invalid subscription result: %v", err)
  185. }
  186. return nil, &res, nil
  187. case msg.isResponse():
  188. var c subConfirmation
  189. if msg.Error != nil {
  190. return nil, nil, msg.Error
  191. } else if err := json.Unmarshal(msg.Result, &c.subid); err != nil {
  192. return nil, nil, fmt.Errorf("invalid response: %v", err)
  193. } else {
  194. json.Unmarshal(msg.ID, &c.reqid)
  195. return &c, nil, nil
  196. }
  197. default:
  198. return nil, nil, fmt.Errorf("unrecognized message: %v", msg)
  199. }
  200. }