call_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpc
  19. import (
  20. "context"
  21. "fmt"
  22. "io"
  23. "math"
  24. "net"
  25. "strconv"
  26. "strings"
  27. "sync"
  28. "testing"
  29. "time"
  30. "google.golang.org/grpc/codes"
  31. "google.golang.org/grpc/internal/transport"
  32. "google.golang.org/grpc/status"
  33. )
  34. var (
  35. expectedRequest = "ping"
  36. expectedResponse = "pong"
  37. weirdError = "format verbs: %v%s"
  38. sizeLargeErr = 1024 * 1024
  39. canceled = 0
  40. )
  41. type testCodec struct {
  42. }
  43. func (testCodec) Marshal(v interface{}) ([]byte, error) {
  44. return []byte(*(v.(*string))), nil
  45. }
  46. func (testCodec) Unmarshal(data []byte, v interface{}) error {
  47. *(v.(*string)) = string(data)
  48. return nil
  49. }
  50. func (testCodec) String() string {
  51. return "test"
  52. }
  53. type testStreamHandler struct {
  54. port string
  55. t transport.ServerTransport
  56. }
  57. func (h *testStreamHandler) handleStream(t *testing.T, s *transport.Stream) {
  58. p := &parser{r: s}
  59. for {
  60. pf, req, err := p.recvMsg(math.MaxInt32)
  61. if err == io.EOF {
  62. break
  63. }
  64. if err != nil {
  65. return
  66. }
  67. if pf != compressionNone {
  68. t.Errorf("Received the mistaken message format %d, want %d", pf, compressionNone)
  69. return
  70. }
  71. var v string
  72. codec := testCodec{}
  73. if err := codec.Unmarshal(req, &v); err != nil {
  74. t.Errorf("Failed to unmarshal the received message: %v", err)
  75. return
  76. }
  77. if v == "weird error" {
  78. h.t.WriteStatus(s, status.New(codes.Internal, weirdError))
  79. return
  80. }
  81. if v == "canceled" {
  82. canceled++
  83. h.t.WriteStatus(s, status.New(codes.Internal, ""))
  84. return
  85. }
  86. if v == "port" {
  87. h.t.WriteStatus(s, status.New(codes.Internal, h.port))
  88. return
  89. }
  90. if v != expectedRequest {
  91. h.t.WriteStatus(s, status.New(codes.Internal, strings.Repeat("A", sizeLargeErr)))
  92. return
  93. }
  94. }
  95. // send a response back to end the stream.
  96. data, err := encode(testCodec{}, &expectedResponse)
  97. if err != nil {
  98. t.Errorf("Failed to encode the response: %v", err)
  99. return
  100. }
  101. hdr, payload := msgHeader(data, nil)
  102. h.t.Write(s, hdr, payload, &transport.Options{})
  103. h.t.WriteStatus(s, status.New(codes.OK, ""))
  104. }
  105. type server struct {
  106. lis net.Listener
  107. port string
  108. addr string
  109. startedErr chan error // sent nil or an error after server starts
  110. mu sync.Mutex
  111. conns map[transport.ServerTransport]bool
  112. }
  113. type ctxKey string
  114. func newTestServer() *server {
  115. return &server{startedErr: make(chan error, 1)}
  116. }
  117. // start starts server. Other goroutines should block on s.startedErr for further operations.
  118. func (s *server) start(t *testing.T, port int, maxStreams uint32) {
  119. var err error
  120. if port == 0 {
  121. s.lis, err = net.Listen("tcp", "localhost:0")
  122. } else {
  123. s.lis, err = net.Listen("tcp", "localhost:"+strconv.Itoa(port))
  124. }
  125. if err != nil {
  126. s.startedErr <- fmt.Errorf("failed to listen: %v", err)
  127. return
  128. }
  129. s.addr = s.lis.Addr().String()
  130. _, p, err := net.SplitHostPort(s.addr)
  131. if err != nil {
  132. s.startedErr <- fmt.Errorf("failed to parse listener address: %v", err)
  133. return
  134. }
  135. s.port = p
  136. s.conns = make(map[transport.ServerTransport]bool)
  137. s.startedErr <- nil
  138. for {
  139. conn, err := s.lis.Accept()
  140. if err != nil {
  141. return
  142. }
  143. config := &transport.ServerConfig{
  144. MaxStreams: maxStreams,
  145. }
  146. st, err := transport.NewServerTransport("http2", conn, config)
  147. if err != nil {
  148. continue
  149. }
  150. s.mu.Lock()
  151. if s.conns == nil {
  152. s.mu.Unlock()
  153. st.Close()
  154. return
  155. }
  156. s.conns[st] = true
  157. s.mu.Unlock()
  158. h := &testStreamHandler{
  159. port: s.port,
  160. t: st,
  161. }
  162. go st.HandleStreams(func(s *transport.Stream) {
  163. go h.handleStream(t, s)
  164. }, func(ctx context.Context, method string) context.Context {
  165. return ctx
  166. })
  167. }
  168. }
  169. func (s *server) wait(t *testing.T, timeout time.Duration) {
  170. select {
  171. case err := <-s.startedErr:
  172. if err != nil {
  173. t.Fatal(err)
  174. }
  175. case <-time.After(timeout):
  176. t.Fatalf("Timed out after %v waiting for server to be ready", timeout)
  177. }
  178. }
  179. func (s *server) stop() {
  180. s.lis.Close()
  181. s.mu.Lock()
  182. for c := range s.conns {
  183. c.Close()
  184. }
  185. s.conns = nil
  186. s.mu.Unlock()
  187. }
  188. func setUp(t *testing.T, port int, maxStreams uint32) (*server, *ClientConn) {
  189. return setUpWithOptions(t, port, maxStreams)
  190. }
  191. func setUpWithOptions(t *testing.T, port int, maxStreams uint32, dopts ...DialOption) (*server, *ClientConn) {
  192. server := newTestServer()
  193. go server.start(t, port, maxStreams)
  194. server.wait(t, 2*time.Second)
  195. addr := "localhost:" + server.port
  196. dopts = append(dopts, WithBlock(), WithInsecure(), WithCodec(testCodec{}))
  197. cc, err := Dial(addr, dopts...)
  198. if err != nil {
  199. t.Fatalf("Failed to create ClientConn: %v", err)
  200. }
  201. return server, cc
  202. }
  203. func (s) TestUnaryClientInterceptor(t *testing.T) {
  204. parentKey := ctxKey("parentKey")
  205. interceptor := func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error {
  206. if ctx.Value(parentKey) == nil {
  207. t.Fatalf("interceptor should have %v in context", parentKey)
  208. }
  209. return invoker(ctx, method, req, reply, cc, opts...)
  210. }
  211. server, cc := setUpWithOptions(t, 0, math.MaxUint32, WithUnaryInterceptor(interceptor))
  212. defer func() {
  213. cc.Close()
  214. server.stop()
  215. }()
  216. var reply string
  217. ctx := context.Background()
  218. parentCtx := context.WithValue(ctx, ctxKey("parentKey"), 0)
  219. if err := cc.Invoke(parentCtx, "/foo/bar", &expectedRequest, &reply); err != nil || reply != expectedResponse {
  220. t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want <nil>", err)
  221. }
  222. }
  223. func (s) TestChainUnaryClientInterceptor(t *testing.T) {
  224. var (
  225. parentKey = ctxKey("parentKey")
  226. firstIntKey = ctxKey("firstIntKey")
  227. secondIntKey = ctxKey("secondIntKey")
  228. )
  229. firstInt := func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error {
  230. if ctx.Value(parentKey) == nil {
  231. t.Fatalf("first interceptor should have %v in context", parentKey)
  232. }
  233. if ctx.Value(firstIntKey) != nil {
  234. t.Fatalf("first interceptor should not have %v in context", firstIntKey)
  235. }
  236. if ctx.Value(secondIntKey) != nil {
  237. t.Fatalf("first interceptor should not have %v in context", secondIntKey)
  238. }
  239. firstCtx := context.WithValue(ctx, firstIntKey, 1)
  240. err := invoker(firstCtx, method, req, reply, cc, opts...)
  241. *(reply.(*string)) += "1"
  242. return err
  243. }
  244. secondInt := func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error {
  245. if ctx.Value(parentKey) == nil {
  246. t.Fatalf("second interceptor should have %v in context", parentKey)
  247. }
  248. if ctx.Value(firstIntKey) == nil {
  249. t.Fatalf("second interceptor should have %v in context", firstIntKey)
  250. }
  251. if ctx.Value(secondIntKey) != nil {
  252. t.Fatalf("second interceptor should not have %v in context", secondIntKey)
  253. }
  254. secondCtx := context.WithValue(ctx, secondIntKey, 2)
  255. err := invoker(secondCtx, method, req, reply, cc, opts...)
  256. *(reply.(*string)) += "2"
  257. return err
  258. }
  259. lastInt := func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error {
  260. if ctx.Value(parentKey) == nil {
  261. t.Fatalf("last interceptor should have %v in context", parentKey)
  262. }
  263. if ctx.Value(firstIntKey) == nil {
  264. t.Fatalf("last interceptor should have %v in context", firstIntKey)
  265. }
  266. if ctx.Value(secondIntKey) == nil {
  267. t.Fatalf("last interceptor should have %v in context", secondIntKey)
  268. }
  269. err := invoker(ctx, method, req, reply, cc, opts...)
  270. *(reply.(*string)) += "3"
  271. return err
  272. }
  273. server, cc := setUpWithOptions(t, 0, math.MaxUint32, WithChainUnaryInterceptor(firstInt, secondInt, lastInt))
  274. defer func() {
  275. cc.Close()
  276. server.stop()
  277. }()
  278. var reply string
  279. ctx := context.Background()
  280. parentCtx := context.WithValue(ctx, ctxKey("parentKey"), 0)
  281. if err := cc.Invoke(parentCtx, "/foo/bar", &expectedRequest, &reply); err != nil || reply != expectedResponse+"321" {
  282. t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want <nil>", err)
  283. }
  284. }
  285. func (s) TestChainOnBaseUnaryClientInterceptor(t *testing.T) {
  286. var (
  287. parentKey = ctxKey("parentKey")
  288. baseIntKey = ctxKey("baseIntKey")
  289. )
  290. baseInt := func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error {
  291. if ctx.Value(parentKey) == nil {
  292. t.Fatalf("base interceptor should have %v in context", parentKey)
  293. }
  294. if ctx.Value(baseIntKey) != nil {
  295. t.Fatalf("base interceptor should not have %v in context", baseIntKey)
  296. }
  297. baseCtx := context.WithValue(ctx, baseIntKey, 1)
  298. return invoker(baseCtx, method, req, reply, cc, opts...)
  299. }
  300. chainInt := func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error {
  301. if ctx.Value(parentKey) == nil {
  302. t.Fatalf("chain interceptor should have %v in context", parentKey)
  303. }
  304. if ctx.Value(baseIntKey) == nil {
  305. t.Fatalf("chain interceptor should have %v in context", baseIntKey)
  306. }
  307. return invoker(ctx, method, req, reply, cc, opts...)
  308. }
  309. server, cc := setUpWithOptions(t, 0, math.MaxUint32, WithUnaryInterceptor(baseInt), WithChainUnaryInterceptor(chainInt))
  310. defer func() {
  311. cc.Close()
  312. server.stop()
  313. }()
  314. var reply string
  315. ctx := context.Background()
  316. parentCtx := context.WithValue(ctx, ctxKey("parentKey"), 0)
  317. if err := cc.Invoke(parentCtx, "/foo/bar", &expectedRequest, &reply); err != nil || reply != expectedResponse {
  318. t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want <nil>", err)
  319. }
  320. }
  321. func (s) TestChainStreamClientInterceptor(t *testing.T) {
  322. var (
  323. parentKey = ctxKey("parentKey")
  324. firstIntKey = ctxKey("firstIntKey")
  325. secondIntKey = ctxKey("secondIntKey")
  326. )
  327. firstInt := func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) {
  328. if ctx.Value(parentKey) == nil {
  329. t.Fatalf("first interceptor should have %v in context", parentKey)
  330. }
  331. if ctx.Value(firstIntKey) != nil {
  332. t.Fatalf("first interceptor should not have %v in context", firstIntKey)
  333. }
  334. if ctx.Value(secondIntKey) != nil {
  335. t.Fatalf("first interceptor should not have %v in context", secondIntKey)
  336. }
  337. firstCtx := context.WithValue(ctx, firstIntKey, 1)
  338. return streamer(firstCtx, desc, cc, method, opts...)
  339. }
  340. secondInt := func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) {
  341. if ctx.Value(parentKey) == nil {
  342. t.Fatalf("second interceptor should have %v in context", parentKey)
  343. }
  344. if ctx.Value(firstIntKey) == nil {
  345. t.Fatalf("second interceptor should have %v in context", firstIntKey)
  346. }
  347. if ctx.Value(secondIntKey) != nil {
  348. t.Fatalf("second interceptor should not have %v in context", secondIntKey)
  349. }
  350. secondCtx := context.WithValue(ctx, secondIntKey, 2)
  351. return streamer(secondCtx, desc, cc, method, opts...)
  352. }
  353. lastInt := func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) {
  354. if ctx.Value(parentKey) == nil {
  355. t.Fatalf("last interceptor should have %v in context", parentKey)
  356. }
  357. if ctx.Value(firstIntKey) == nil {
  358. t.Fatalf("last interceptor should have %v in context", firstIntKey)
  359. }
  360. if ctx.Value(secondIntKey) == nil {
  361. t.Fatalf("last interceptor should have %v in context", secondIntKey)
  362. }
  363. return streamer(ctx, desc, cc, method, opts...)
  364. }
  365. server, cc := setUpWithOptions(t, 0, math.MaxUint32, WithChainStreamInterceptor(firstInt, secondInt, lastInt))
  366. defer func() {
  367. cc.Close()
  368. server.stop()
  369. }()
  370. ctx := context.Background()
  371. parentCtx := context.WithValue(ctx, ctxKey("parentKey"), 0)
  372. _, err := cc.NewStream(parentCtx, &StreamDesc{}, "/foo/bar")
  373. if err != nil {
  374. t.Fatalf("grpc.NewStream(_, _, _) = %v, want <nil>", err)
  375. }
  376. }
  377. func (s) TestInvoke(t *testing.T) {
  378. server, cc := setUp(t, 0, math.MaxUint32)
  379. var reply string
  380. if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply); err != nil || reply != expectedResponse {
  381. t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want <nil>", err)
  382. }
  383. cc.Close()
  384. server.stop()
  385. }
  386. func (s) TestInvokeLargeErr(t *testing.T) {
  387. server, cc := setUp(t, 0, math.MaxUint32)
  388. var reply string
  389. req := "hello"
  390. err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply)
  391. if _, ok := status.FromError(err); !ok {
  392. t.Fatalf("grpc.Invoke(_, _, _, _, _) receives non rpc error.")
  393. }
  394. if status.Code(err) != codes.Internal || len(errorDesc(err)) != sizeLargeErr {
  395. t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want an error of code %d and desc size %d", err, codes.Internal, sizeLargeErr)
  396. }
  397. cc.Close()
  398. server.stop()
  399. }
  400. // TestInvokeErrorSpecialChars checks that error messages don't get mangled.
  401. func (s) TestInvokeErrorSpecialChars(t *testing.T) {
  402. server, cc := setUp(t, 0, math.MaxUint32)
  403. var reply string
  404. req := "weird error"
  405. err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply)
  406. if _, ok := status.FromError(err); !ok {
  407. t.Fatalf("grpc.Invoke(_, _, _, _, _) receives non rpc error.")
  408. }
  409. if got, want := errorDesc(err), weirdError; got != want {
  410. t.Fatalf("grpc.Invoke(_, _, _, _, _) error = %q, want %q", got, want)
  411. }
  412. cc.Close()
  413. server.stop()
  414. }
  415. // TestInvokeCancel checks that an Invoke with a canceled context is not sent.
  416. func (s) TestInvokeCancel(t *testing.T) {
  417. server, cc := setUp(t, 0, math.MaxUint32)
  418. var reply string
  419. req := "canceled"
  420. for i := 0; i < 100; i++ {
  421. ctx, cancel := context.WithCancel(context.Background())
  422. cancel()
  423. cc.Invoke(ctx, "/foo/bar", &req, &reply)
  424. }
  425. if canceled != 0 {
  426. t.Fatalf("received %d of 100 canceled requests", canceled)
  427. }
  428. cc.Close()
  429. server.stop()
  430. }
  431. // TestInvokeCancelClosedNonFail checks that a canceled non-failfast RPC
  432. // on a closed client will terminate.
  433. func (s) TestInvokeCancelClosedNonFailFast(t *testing.T) {
  434. server, cc := setUp(t, 0, math.MaxUint32)
  435. var reply string
  436. cc.Close()
  437. req := "hello"
  438. ctx, cancel := context.WithCancel(context.Background())
  439. cancel()
  440. if err := cc.Invoke(ctx, "/foo/bar", &req, &reply, WaitForReady(true)); err == nil {
  441. t.Fatalf("canceled invoke on closed connection should fail")
  442. }
  443. server.stop()
  444. }