You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

136 lines
3.8 KiB

  1. /*
  2. Copyright 2016 Google LLC
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package testutil
  14. import (
  15. "fmt"
  16. "log"
  17. "net"
  18. "regexp"
  19. "strconv"
  20. "google.golang.org/grpc"
  21. "google.golang.org/grpc/codes"
  22. "google.golang.org/grpc/status"
  23. )
  24. // A Server is an in-process gRPC server, listening on a system-chosen port on
  25. // the local loopback interface. Servers are for testing only and are not
  26. // intended to be used in production code.
  27. //
  28. // To create a server, make a new Server, register your handlers, then call
  29. // Start:
  30. //
  31. // srv, err := NewServer()
  32. // ...
  33. // mypb.RegisterMyServiceServer(srv.Gsrv, &myHandler)
  34. // ....
  35. // srv.Start()
  36. //
  37. // Clients should connect to the server with no security:
  38. //
  39. // conn, err := grpc.Dial(srv.Addr, grpc.WithInsecure())
  40. // ...
  41. type Server struct {
  42. Addr string
  43. Port int
  44. l net.Listener
  45. Gsrv *grpc.Server
  46. }
  47. // NewServer creates a new Server. The Server will be listening for gRPC connections
  48. // at the address named by the Addr field, without TLS.
  49. func NewServer(opts ...grpc.ServerOption) (*Server, error) {
  50. return NewServerWithPort(0, opts...)
  51. }
  52. // NewServerWithPort creates a new Server at a specific port. The Server will be listening
  53. // for gRPC connections at the address named by the Addr field, without TLS.
  54. func NewServerWithPort(port int, opts ...grpc.ServerOption) (*Server, error) {
  55. l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
  56. if err != nil {
  57. return nil, err
  58. }
  59. s := &Server{
  60. Addr: l.Addr().String(),
  61. Port: parsePort(l.Addr().String()),
  62. l: l,
  63. Gsrv: grpc.NewServer(opts...),
  64. }
  65. return s, nil
  66. }
  67. // Start causes the server to start accepting incoming connections.
  68. // Call Start after registering handlers.
  69. func (s *Server) Start() {
  70. go func() {
  71. if err := s.Gsrv.Serve(s.l); err != nil {
  72. log.Printf("testutil.Server.Start: %v", err)
  73. }
  74. }()
  75. }
  76. // Close shuts down the server.
  77. func (s *Server) Close() {
  78. s.Gsrv.Stop()
  79. s.l.Close()
  80. }
  81. // PageBounds converts an incoming page size and token from an RPC request into
  82. // slice bounds and the outgoing next-page token.
  83. //
  84. // PageBounds assumes that the complete, unpaginated list of items exists as a
  85. // single slice. In addition to the page size and token, PageBounds needs the
  86. // length of that slice.
  87. //
  88. // PageBounds's first two return values should be used to construct a sub-slice of
  89. // the complete, unpaginated slice. E.g. if the complete slice is s, then
  90. // s[from:to] is the desired page. Its third return value should be set as the
  91. // NextPageToken field of the RPC response.
  92. func PageBounds(pageSize int, pageToken string, length int) (from, to int, nextPageToken string, err error) {
  93. from, to = 0, length
  94. if pageToken != "" {
  95. from, err = strconv.Atoi(pageToken)
  96. if err != nil {
  97. return 0, 0, "", status.Errorf(codes.InvalidArgument, "bad page token: %v", err)
  98. }
  99. if from >= length {
  100. return length, length, "", nil
  101. }
  102. }
  103. if pageSize > 0 && from+pageSize < length {
  104. to = from + pageSize
  105. nextPageToken = strconv.Itoa(to)
  106. }
  107. return from, to, nextPageToken, nil
  108. }
  109. var portParser = regexp.MustCompile(`:[0-9]+`)
  110. func parsePort(addr string) int {
  111. res := portParser.FindAllString(addr, -1)
  112. if len(res) == 0 {
  113. panic(fmt.Errorf("parsePort: found no numbers in %s", addr))
  114. }
  115. stringPort := res[0][1:] // strip the :
  116. p, err := strconv.ParseInt(stringPort, 10, 32)
  117. if err != nil {
  118. panic(err)
  119. }
  120. return int(p)
  121. }