[
  {
    "path": ".gitignore",
    "content": "# Binaries for programs and plugins\n*.exe\n*.exe~\n*.dll\n*.so\n*.dylib\n\n# Test binary, build with `go test -c`\n*.test\n\n# Output of the go coverage tool, specifically when used with LiteIDE\n*.out\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Pool\n[![GoDoc](https://godoc.org/github.com/shimingyah/pool?status.svg)](https://godoc.org/github.com/shimingyah/pool)\n[![Go Report Card](https://goreportcard.com/badge/github.com/shimingyah/pool?style=flat-square)](https://goreportcard.com/report/github.com/shimingyah/pool)\n[![LICENSE](https://img.shields.io/badge/licence-Apache%202.0-brightgreen.svg?style=flat-square)](https://github.com/shimingyah/pool/blob/master/LICENSE)\n\nConnection pool for Go's grpc client that supports connection reuse.\n\nPool provides additional features:\n\n* `Connection reuse` supported by specific MaxConcurrentStreams param.\n* `Failure reconnection` supported by grpc's keepalive.\n\n# Getting started\n\n## Install\n\nImport package:\n\n```\nimport (\n    \"github.com/shimingyah/pool\"\n)\n```\n\n```\ngo get github.com/shimingyah/pool\n```\n\n# Usage\n\n```\np, err := pool.New(\"127.0.0.1:8080\", pool.DefaultOptions)\nif err != nil {\n    log.Fatalf(\"failed to new pool: %v\", err)\n}\ndefer p.Close()\n\nconn, err := p.Get()\nif err != nil {\n    log.Fatalf(\"failed to get conn: %v\", err)\n}\ndefer conn.Close()\n\n// cc := conn.Value()\n// client := pb.NewClient(conn.Value())\n```\nSee the complete example: [https://github.com/shimingyah/pool/tree/master/example](https://github.com/shimingyah/pool/tree/master/example)\n\n# Reference\n* [https://github.com/fatih/pool](https://github.com/fatih/pool)\n* [https://github.com/silenceper/pool](https://github.com/silenceper/pool)\n\n# License\n\nPool is under the Apache 2.0 license. See the [LICENSE](https://github.com/shimingyah/pool/blob/master/LICENSE) file for details."
  },
  {
    "path": "conn.go",
    "content": "// Copyright 2019 shimingyah. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// ee the License for the specific language governing permissions and\n// limitations under the License.\n\npackage pool\n\nimport (\n\t\"google.golang.org/grpc\"\n)\n\n// Conn single grpc connection inerface\ntype Conn interface {\n\t// Value return the actual grpc connection type *grpc.ClientConn.\n\tValue() *grpc.ClientConn\n\n\t// Close decrease the reference of grpc connection, instead of close it.\n\t// if the pool is full, just close it.\n\tClose() error\n}\n\n// Conn is wrapped grpc.ClientConn. to provide close and value method.\ntype conn struct {\n\tcc   *grpc.ClientConn\n\tpool *pool\n\tonce bool\n}\n\n// Value see Conn interface.\nfunc (c *conn) Value() *grpc.ClientConn {\n\treturn c.cc\n}\n\n// Close see Conn interface.\nfunc (c *conn) Close() error {\n\tc.pool.decrRef()\n\tif c.once {\n\t\treturn c.reset()\n\t}\n\treturn nil\n}\n\nfunc (c *conn) reset() error {\n\tcc := c.cc\n\tc.cc = nil\n\tc.once = false\n\tif cc != nil {\n\t\treturn cc.Close()\n\t}\n\treturn nil\n}\n\nfunc (p *pool) wrapConn(cc *grpc.ClientConn, once bool) *conn {\n\treturn &conn{\n\t\tcc:   cc,\n\t\tpool: p,\n\t\tonce: once,\n\t}\n}\n"
  },
  {
    "path": "example/client/main.go",
    "content": "// Copyright 2019 shimingyah. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// ee the License for the specific language governing permissions and\n// limitations under the License.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/shimingyah/pool\"\n\t\"github.com/shimingyah/pool/example/pb\"\n)\n\nvar addr = flag.String(\"addr\", \"127.0.0.1:50000\", \"the address to connect to\")\n\nfunc main() {\n\tflag.Parse()\n\n\tp, err := pool.New(*addr, pool.DefaultOptions)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to new pool: %v\", err)\n\t}\n\tdefer p.Close()\n\n\tconn, err := p.Get()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to get conn: %v\", err)\n\t}\n\tdefer conn.Close()\n\n\tclient := pb.NewEchoClient(conn.Value())\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tres, err := client.Say(ctx, &pb.EchoRequest{Message: []byte(\"hi\")})\n\tif err != nil {\n\t\tlog.Fatalf(\"unexpected error from Say: %v\", err)\n\t}\n\tfmt.Println(\"rpc response:\", res)\n}\n"
  },
  {
    "path": "example/pb/example.pb.go",
    "content": "// Code generated by protoc-gen-go. DO NOT EDIT.\n// source: example.proto\n\npackage pb\n\nimport proto \"github.com/golang/protobuf/proto\"\nimport fmt \"fmt\"\nimport math \"math\"\n\nimport (\n\tcontext \"golang.org/x/net/context\"\n\tgrpc \"google.golang.org/grpc\"\n)\n\n// Reference imports to suppress errors if they are not otherwise used.\nvar _ = proto.Marshal\nvar _ = fmt.Errorf\nvar _ = math.Inf\n\n// This is a compile-time assertion to ensure that this generated file\n// is compatible with the proto package it is being compiled against.\n// A compilation error at this line likely means your copy of the\n// proto package needs to be updated.\nconst _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package\n\n// EchoRequest is the request for echo.\ntype EchoRequest struct {\n\tMessage              []byte   `protobuf:\"bytes,1,opt,name=message,proto3\" json:\"message,omitempty\"`\n\tXXX_NoUnkeyedLiteral struct{} `json:\"-\"`\n\tXXX_unrecognized     []byte   `json:\"-\"`\n\tXXX_sizecache        int32    `json:\"-\"`\n}\n\nfunc (m *EchoRequest) Reset()         { *m = EchoRequest{} }\nfunc (m *EchoRequest) String() string { return proto.CompactTextString(m) }\nfunc (*EchoRequest) ProtoMessage()    {}\nfunc (*EchoRequest) Descriptor() ([]byte, []int) {\n\treturn fileDescriptor_example_d72c2831d52b7689, []int{0}\n}\nfunc (m *EchoRequest) XXX_Unmarshal(b []byte) error {\n\treturn xxx_messageInfo_EchoRequest.Unmarshal(m, b)\n}\nfunc (m *EchoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {\n\treturn xxx_messageInfo_EchoRequest.Marshal(b, m, deterministic)\n}\nfunc (dst *EchoRequest) XXX_Merge(src proto.Message) {\n\txxx_messageInfo_EchoRequest.Merge(dst, src)\n}\nfunc (m *EchoRequest) XXX_Size() int {\n\treturn xxx_messageInfo_EchoRequest.Size(m)\n}\nfunc (m *EchoRequest) XXX_DiscardUnknown() {\n\txxx_messageInfo_EchoRequest.DiscardUnknown(m)\n}\n\nvar xxx_messageInfo_EchoRequest proto.InternalMessageInfo\n\nfunc (m *EchoRequest) GetMessage() []byte {\n\tif m != nil {\n\t\treturn m.Message\n\t}\n\treturn nil\n}\n\n// EchoResponse is the response for echo.\ntype EchoResponse struct {\n\tMessage              []byte   `protobuf:\"bytes,1,opt,name=message,proto3\" json:\"message,omitempty\"`\n\tXXX_NoUnkeyedLiteral struct{} `json:\"-\"`\n\tXXX_unrecognized     []byte   `json:\"-\"`\n\tXXX_sizecache        int32    `json:\"-\"`\n}\n\nfunc (m *EchoResponse) Reset()         { *m = EchoResponse{} }\nfunc (m *EchoResponse) String() string { return proto.CompactTextString(m) }\nfunc (*EchoResponse) ProtoMessage()    {}\nfunc (*EchoResponse) Descriptor() ([]byte, []int) {\n\treturn fileDescriptor_example_d72c2831d52b7689, []int{1}\n}\nfunc (m *EchoResponse) XXX_Unmarshal(b []byte) error {\n\treturn xxx_messageInfo_EchoResponse.Unmarshal(m, b)\n}\nfunc (m *EchoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {\n\treturn xxx_messageInfo_EchoResponse.Marshal(b, m, deterministic)\n}\nfunc (dst *EchoResponse) XXX_Merge(src proto.Message) {\n\txxx_messageInfo_EchoResponse.Merge(dst, src)\n}\nfunc (m *EchoResponse) XXX_Size() int {\n\treturn xxx_messageInfo_EchoResponse.Size(m)\n}\nfunc (m *EchoResponse) XXX_DiscardUnknown() {\n\txxx_messageInfo_EchoResponse.DiscardUnknown(m)\n}\n\nvar xxx_messageInfo_EchoResponse proto.InternalMessageInfo\n\nfunc (m *EchoResponse) GetMessage() []byte {\n\tif m != nil {\n\t\treturn m.Message\n\t}\n\treturn nil\n}\n\nfunc init() {\n\tproto.RegisterType((*EchoRequest)(nil), \"pb.EchoRequest\")\n\tproto.RegisterType((*EchoResponse)(nil), \"pb.EchoResponse\")\n}\n\n// Reference imports to suppress errors if they are not otherwise used.\nvar _ context.Context\nvar _ grpc.ClientConn\n\n// This is a compile-time assertion to ensure that this generated file\n// is compatible with the grpc package it is being compiled against.\nconst _ = grpc.SupportPackageIsVersion4\n\n// EchoClient is the client API for Echo service.\n//\n// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.\ntype EchoClient interface {\n\t// Say is simple request.\n\tSay(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoResponse, error)\n}\n\ntype echoClient struct {\n\tcc *grpc.ClientConn\n}\n\nfunc NewEchoClient(cc *grpc.ClientConn) EchoClient {\n\treturn &echoClient{cc}\n}\n\nfunc (c *echoClient) Say(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoResponse, error) {\n\tout := new(EchoResponse)\n\terr := c.cc.Invoke(ctx, \"/pb.Echo/Say\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n// EchoServer is the server API for Echo service.\ntype EchoServer interface {\n\t// Say is simple request.\n\tSay(context.Context, *EchoRequest) (*EchoResponse, error)\n}\n\nfunc RegisterEchoServer(s *grpc.Server, srv EchoServer) {\n\ts.RegisterService(&_Echo_serviceDesc, srv)\n}\n\nfunc _Echo_Say_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {\n\tin := new(EchoRequest)\n\tif err := dec(in); err != nil {\n\t\treturn nil, err\n\t}\n\tif interceptor == nil {\n\t\treturn srv.(EchoServer).Say(ctx, in)\n\t}\n\tinfo := &grpc.UnaryServerInfo{\n\t\tServer:     srv,\n\t\tFullMethod: \"/pb.Echo/Say\",\n\t}\n\thandler := func(ctx context.Context, req interface{}) (interface{}, error) {\n\t\treturn srv.(EchoServer).Say(ctx, req.(*EchoRequest))\n\t}\n\treturn interceptor(ctx, in, info, handler)\n}\n\nvar _Echo_serviceDesc = grpc.ServiceDesc{\n\tServiceName: \"pb.Echo\",\n\tHandlerType: (*EchoServer)(nil),\n\tMethods: []grpc.MethodDesc{\n\t\t{\n\t\t\tMethodName: \"Say\",\n\t\t\tHandler:    _Echo_Say_Handler,\n\t\t},\n\t},\n\tStreams:  []grpc.StreamDesc{},\n\tMetadata: \"example.proto\",\n}\n\nfunc init() { proto.RegisterFile(\"example.proto\", fileDescriptor_example_d72c2831d52b7689) }\n\nvar fileDescriptor_example_d72c2831d52b7689 = []byte{\n\t// 127 bytes of a gzipped FileDescriptorProto\n\t0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4d, 0xad, 0x48, 0xcc,\n\t0x2d, 0xc8, 0x49, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2a, 0x48, 0x52, 0x52, 0xe7,\n\t0xe2, 0x76, 0x4d, 0xce, 0xc8, 0x0f, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x11, 0x92, 0xe0, 0x62,\n\t0xcf, 0x4d, 0x2d, 0x2e, 0x4e, 0x4c, 0x4f, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x09, 0x82, 0x71,\n\t0x95, 0x34, 0xb8, 0x78, 0x20, 0x0a, 0x8b, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0x71, 0xab, 0x34, 0x32,\n\t0xe2, 0x62, 0x01, 0xa9, 0x14, 0xd2, 0xe2, 0x62, 0x0e, 0x4e, 0xac, 0x14, 0xe2, 0xd7, 0x2b, 0x48,\n\t0xd2, 0x43, 0xb2, 0x43, 0x4a, 0x00, 0x21, 0x00, 0x31, 0x4b, 0x89, 0x21, 0x89, 0x0d, 0xec, 0x22,\n\t0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xba, 0x45, 0x75, 0x9d, 0xa2, 0x00, 0x00, 0x00,\n}\n"
  },
  {
    "path": "example/pb/example.proto",
    "content": "// Copyright 2019 shimingyah. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// ee the License for the specific language governing permissions and\n// limitations under the License.\n\nsyntax = \"proto3\";\n\npackage pb;\n\n// EchoRequest is the request for echo.\nmessage EchoRequest {\n  bytes message = 1;\n}\n\n// EchoResponse is the response for echo.\nmessage EchoResponse {\n  bytes message = 1;\n}\n\n// Echo is the echo service.\nservice Echo {\n  // Say is simple request.\n  rpc Say(EchoRequest) returns (EchoResponse) {}\n}"
  },
  {
    "path": "example/server/main.go",
    "content": "// Copyright 2019 shimingyah. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// ee the License for the specific language governing permissions and\n// limitations under the License.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/keepalive\"\n\n\t\"github.com/shimingyah/pool\"\n\t\"github.com/shimingyah/pool/example/pb\"\n)\n\nvar port = flag.Int(\"port\", 50000, \"port number\")\n\n// server implements EchoServer.\ntype server struct{}\n\nfunc (s *server) Say(context.Context, *pb.EchoRequest) (*pb.EchoResponse, error) {\n\treturn &pb.EchoResponse{Message: []byte(\"hello world\")}, nil\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tlisten, err := net.Listen(\"tcp\", fmt.Sprintf(\"127.0.0.1:%v\", *port))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\ts := grpc.NewServer(\n\t\tgrpc.InitialWindowSize(pool.InitialWindowSize),\n\t\tgrpc.InitialConnWindowSize(pool.InitialConnWindowSize),\n\t\tgrpc.MaxSendMsgSize(pool.MaxSendMsgSize),\n\t\tgrpc.MaxRecvMsgSize(pool.MaxRecvMsgSize),\n\t\tgrpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{\n\t\t\tPermitWithoutStream: true,\n\t\t}),\n\t\tgrpc.KeepaliveParams(keepalive.ServerParameters{\n\t\t\tTime:    pool.KeepAliveTime,\n\t\t\tTimeout: pool.KeepAliveTimeout,\n\t\t}),\n\t)\n\tpb.RegisterEchoServer(s, &server{})\n\n\tif err := s.Serve(listen); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/shimingyah/pool\n\ngo 1.12\n\nrequire (\n\tgithub.com/golang/protobuf v1.2.0\n\tgithub.com/stretchr/testify v1.3.0\n\tgolang.org/x/net v0.0.0-20190311183353-d8887717615a\n\tgoogle.golang.org/grpc v1.22.0\n)\n"
  },
  {
    "path": "go.sum",
    "content": "cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=\ngithub.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=\ngithub.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=\ngithub.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=\ngithub.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=\ngithub.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=\ngithub.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=\ngithub.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=\ngithub.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=\ngolang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628=\ngolang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=\ngolang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\ngolang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=\ngolang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=\ngoogle.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=\ngoogle.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc=\ngoogle.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=\ngoogle.golang.org/grpc v1.22.0 h1:J0UbZOIrCAl+fpTOf8YLs4dJo8L/owV4LYVtAXQoPkw=\ngoogle.golang.org/grpc v1.22.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=\nhonnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=\n"
  },
  {
    "path": "options.go",
    "content": "// Copyright 2019 shimingyah. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// ee the License for the specific language governing permissions and\n// limitations under the License.\n\npackage pool\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/keepalive\"\n)\n\nconst (\n\t// DialTimeout the timeout of create connection\n\tDialTimeout = 5 * time.Second\n\n\t// BackoffMaxDelay provided maximum delay when backing off after failed connection attempts.\n\tBackoffMaxDelay = 3 * time.Second\n\n\t// KeepAliveTime is the duration of time after which if the client doesn't see\n\t// any activity it pings the server to see if the transport is still alive.\n\tKeepAliveTime = time.Duration(10) * time.Second\n\n\t// KeepAliveTimeout is the duration of time for which the client waits after having\n\t// pinged for keepalive check and if no activity is seen even after that the connection\n\t// is closed.\n\tKeepAliveTimeout = time.Duration(3) * time.Second\n\n\t// InitialWindowSize we set it 1GB is to provide system's throughput.\n\tInitialWindowSize = 1 << 30\n\n\t// InitialConnWindowSize we set it 1GB is to provide system's throughput.\n\tInitialConnWindowSize = 1 << 30\n\n\t// MaxSendMsgSize set max gRPC request message size sent to server.\n\t// If any request message size is larger than current value, an error will be reported from gRPC.\n\tMaxSendMsgSize = 4 << 30\n\n\t// MaxRecvMsgSize set max gRPC receive message size received from server.\n\t// If any message size is larger than current value, an error will be reported from gRPC.\n\tMaxRecvMsgSize = 4 << 30\n)\n\n// Options are params for creating grpc connect pool.\ntype Options struct {\n\t// Dial is an application supplied function for creating and configuring a connection.\n\tDial func(address string) (*grpc.ClientConn, error)\n\n\t// Maximum number of idle connections in the pool.\n\tMaxIdle int\n\n\t// Maximum number of connections allocated by the pool at a given time.\n\t// When zero, there is no limit on the number of connections in the pool.\n\tMaxActive int\n\n\t// MaxConcurrentStreams limit on the number of concurrent streams to each single connection\n\tMaxConcurrentStreams int\n\n\t// If Reuse is true and the pool is at the MaxActive limit, then Get() reuse\n\t// the connection to return, If Reuse is false and the pool is at the MaxActive limit,\n\t// create a one-time connection to return.\n\tReuse bool\n}\n\n// DefaultOptions sets a list of recommended options for good performance.\n// Feel free to modify these to suit your needs.\nvar DefaultOptions = Options{\n\tDial:                 Dial,\n\tMaxIdle:              8,\n\tMaxActive:            64,\n\tMaxConcurrentStreams: 64,\n\tReuse:                true,\n}\n\n// Dial return a grpc connection with defined configurations.\nfunc Dial(address string) (*grpc.ClientConn, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), DialTimeout)\n\tdefer cancel()\n\treturn grpc.DialContext(ctx, address, grpc.WithInsecure(),\n\t\tgrpc.WithBackoffMaxDelay(BackoffMaxDelay),\n\t\tgrpc.WithInitialWindowSize(InitialWindowSize),\n\t\tgrpc.WithInitialConnWindowSize(InitialConnWindowSize),\n\t\tgrpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(MaxSendMsgSize)),\n\t\tgrpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(MaxRecvMsgSize)),\n\t\tgrpc.WithKeepaliveParams(keepalive.ClientParameters{\n\t\t\tTime:                KeepAliveTime,\n\t\t\tTimeout:             KeepAliveTimeout,\n\t\t\tPermitWithoutStream: true,\n\t\t}))\n}\n\n// DialTest return a simple grpc connection with defined configurations.\nfunc DialTest(address string) (*grpc.ClientConn, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), DialTimeout)\n\tdefer cancel()\n\treturn grpc.DialContext(ctx, address, grpc.WithInsecure())\n}\n"
  },
  {
    "path": "pool.go",
    "content": "// Copyright 2019 shimingyah. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// ee the License for the specific language governing permissions and\n// limitations under the License.\n\npackage pool\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\n// ErrClosed is the error resulting if the pool is closed via pool.Close().\nvar ErrClosed = errors.New(\"pool is closed\")\n\n// Pool interface describes a pool implementation.\n// An ideal pool is threadsafe and easy to use.\ntype Pool interface {\n\t// Get returns a new connection from the pool. Closing the connections puts\n\t// it back to the Pool. Closing it when the pool is destroyed or full will\n\t// be counted as an error. we guarantee the conn.Value() isn't nil when conn isn't nil.\n\tGet() (Conn, error)\n\n\t// Close closes the pool and all its connections. After Close() the pool is\n\t// no longer usable. You can't make concurrent calls Close and Get method.\n\t// It will be cause panic.\n\tClose() error\n\n\t// Status returns the current status of the pool.\n\tStatus() string\n}\n\ntype pool struct {\n\t// atomic, used to get connection random\n\tindex uint32\n\n\t// atomic, the current physical connection of pool\n\tcurrent int32\n\n\t// atomic, the using logic connection of pool\n\t// logic connection = physical connection * MaxConcurrentStreams\n\tref int32\n\n\t// pool options\n\topt Options\n\n\t// all of created physical connections\n\tconns []*conn\n\n\t// the server address is to create connection.\n\taddress string\n\n\t// closed set true when Close is called.\n\tclosed int32\n\n\t// control the atomic var current's concurrent read write.\n\tsync.RWMutex\n}\n\n// New return a connection pool.\nfunc New(address string, option Options) (Pool, error) {\n\tif address == \"\" {\n\t\treturn nil, errors.New(\"invalid address settings\")\n\t}\n\tif option.Dial == nil {\n\t\treturn nil, errors.New(\"invalid dial settings\")\n\t}\n\tif option.MaxIdle <= 0 || option.MaxActive <= 0 || option.MaxIdle > option.MaxActive {\n\t\treturn nil, errors.New(\"invalid maximum settings\")\n\t}\n\tif option.MaxConcurrentStreams <= 0 {\n\t\treturn nil, errors.New(\"invalid maximun settings\")\n\t}\n\n\tp := &pool{\n\t\tindex:   0,\n\t\tcurrent: int32(option.MaxIdle),\n\t\tref:     0,\n\t\topt:     option,\n\t\tconns:   make([]*conn, option.MaxActive),\n\t\taddress: address,\n\t\tclosed:  0,\n\t}\n\n\tfor i := 0; i < p.opt.MaxIdle; i++ {\n\t\tc, err := p.opt.Dial(address)\n\t\tif err != nil {\n\t\t\tp.Close()\n\t\t\treturn nil, fmt.Errorf(\"dial is not able to fill the pool: %s\", err)\n\t\t}\n\t\tp.conns[i] = p.wrapConn(c, false)\n\t}\n\tlog.Printf(\"new pool success: %v\\n\", p.Status())\n\n\treturn p, nil\n}\n\nfunc (p *pool) incrRef() int32 {\n\tnewRef := atomic.AddInt32(&p.ref, 1)\n\tif newRef == math.MaxInt32 {\n\t\tpanic(fmt.Sprintf(\"overflow ref: %d\", newRef))\n\t}\n\treturn newRef\n}\n\nfunc (p *pool) decrRef() {\n\tnewRef := atomic.AddInt32(&p.ref, -1)\n\tif newRef < 0 && atomic.LoadInt32(&p.closed) == 0 {\n\t\tpanic(fmt.Sprintf(\"negative ref: %d\", newRef))\n\t}\n\tif newRef == 0 && atomic.LoadInt32(&p.current) > int32(p.opt.MaxIdle) {\n\t\tp.Lock()\n\t\tif atomic.LoadInt32(&p.ref) == 0 {\n\t\t\tlog.Printf(\"shrink pool: %d ---> %d, decrement: %d, maxActive: %d\\n\",\n\t\t\t\tp.current, p.opt.MaxIdle, p.current-int32(p.opt.MaxIdle), p.opt.MaxActive)\n\t\t\tatomic.StoreInt32(&p.current, int32(p.opt.MaxIdle))\n\t\t\tp.deleteFrom(p.opt.MaxIdle)\n\t\t}\n\t\tp.Unlock()\n\t}\n}\n\nfunc (p *pool) reset(index int) {\n\tconn := p.conns[index]\n\tif conn == nil {\n\t\treturn\n\t}\n\tconn.reset()\n\tp.conns[index] = nil\n}\n\nfunc (p *pool) deleteFrom(begin int) {\n\tfor i := begin; i < p.opt.MaxActive; i++ {\n\t\tp.reset(i)\n\t}\n}\n\n// Get see Pool interface.\nfunc (p *pool) Get() (Conn, error) {\n\t// the first selected from the created connections\n\tnextRef := p.incrRef()\n\tp.RLock()\n\tcurrent := atomic.LoadInt32(&p.current)\n\tp.RUnlock()\n\tif current == 0 {\n\t\treturn nil, ErrClosed\n\t}\n\tif nextRef <= current*int32(p.opt.MaxConcurrentStreams) {\n\t\tnext := atomic.AddUint32(&p.index, 1) % uint32(current)\n\t\treturn p.conns[next], nil\n\t}\n\n\t// the number connection of pool is reach to max active\n\tif current == int32(p.opt.MaxActive) {\n\t\t// the second if reuse is true, select from pool's connections\n\t\tif p.opt.Reuse {\n\t\t\tnext := atomic.AddUint32(&p.index, 1) % uint32(current)\n\t\t\treturn p.conns[next], nil\n\t\t}\n\t\t// the third create one-time connection\n\t\tc, err := p.opt.Dial(p.address)\n\t\treturn p.wrapConn(c, true), err\n\t}\n\n\t// the fourth create new connections given back to pool\n\tp.Lock()\n\tcurrent = atomic.LoadInt32(&p.current)\n\tif current < int32(p.opt.MaxActive) && nextRef > current*int32(p.opt.MaxConcurrentStreams) {\n\t\t// 2 times the incremental or the remain incremental\n\t\tincrement := current\n\t\tif current+increment > int32(p.opt.MaxActive) {\n\t\t\tincrement = int32(p.opt.MaxActive) - current\n\t\t}\n\t\tvar i int32\n\t\tvar err error\n\t\tfor i = 0; i < increment; i++ {\n\t\t\tc, er := p.opt.Dial(p.address)\n\t\t\tif er != nil {\n\t\t\t\terr = er\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tp.reset(int(current + i))\n\t\t\tp.conns[current+i] = p.wrapConn(c, false)\n\t\t}\n\t\tcurrent += i\n\t\tlog.Printf(\"grow pool: %d ---> %d, increment: %d, maxActive: %d\\n\",\n\t\t\tp.current, current, increment, p.opt.MaxActive)\n\t\tatomic.StoreInt32(&p.current, current)\n\t\tif err != nil {\n\t\t\tp.Unlock()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tp.Unlock()\n\tnext := atomic.AddUint32(&p.index, 1) % uint32(current)\n\treturn p.conns[next], nil\n}\n\n// Close see Pool interface.\nfunc (p *pool) Close() error {\n\tatomic.StoreInt32(&p.closed, 1)\n\tatomic.StoreUint32(&p.index, 0)\n\tatomic.StoreInt32(&p.current, 0)\n\tatomic.StoreInt32(&p.ref, 0)\n\tp.deleteFrom(0)\n\tlog.Printf(\"close pool success: %v\\n\", p.Status())\n\treturn nil\n}\n\n// Status see Pool interface.\nfunc (p *pool) Status() string {\n\treturn fmt.Sprintf(\"address:%s, index:%d, current:%d, ref:%d. option:%v\",\n\t\tp.address, p.index, p.current, p.ref, p.opt)\n}\n"
  },
  {
    "path": "pool_test.go",
    "content": "// Copyright 2019 shimingyah. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// ee the License for the specific language governing permissions and\n// limitations under the License.\n\npackage pool\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/shimingyah/pool/example/pb\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar endpoint = flag.String(\"endpoint\", \"127.0.0.1:50000\", \"grpc server endpoint\")\n\nfunc newPool(op *Options) (Pool, *pool, Options, error) {\n\topt := DefaultOptions\n\topt.Dial = DialTest\n\tif op != nil {\n\t\topt = *op\n\t}\n\tp, err := New(*endpoint, opt)\n\treturn p, p.(*pool), opt, err\n}\n\nfunc TestNew(t *testing.T) {\n\tp, nativePool, opt, err := newPool(nil)\n\trequire.NoError(t, err)\n\tdefer p.Close()\n\n\trequire.EqualValues(t, 0, nativePool.index)\n\trequire.EqualValues(t, 0, nativePool.ref)\n\trequire.EqualValues(t, opt.MaxIdle, nativePool.current)\n\trequire.EqualValues(t, opt.MaxActive, len(nativePool.conns))\n}\n\nfunc TestNew2(t *testing.T) {\n\topt := DefaultOptions\n\n\t_, err := New(\"\", opt)\n\trequire.Error(t, err)\n\n\topt.Dial = nil\n\t_, err = New(\"127.0.0.1:8080\", opt)\n\trequire.Error(t, err)\n\n\topt = DefaultOptions\n\topt.MaxConcurrentStreams = 0\n\t_, err = New(\"127.0.0.1:8080\", opt)\n\trequire.Error(t, err)\n\n\topt = DefaultOptions\n\topt.MaxIdle = 0\n\t_, err = New(\"127.0.0.1:8080\", opt)\n\trequire.Error(t, err)\n\n\topt = DefaultOptions\n\topt.MaxActive = 0\n\t_, err = New(\"127.0.0.1:8080\", opt)\n\trequire.Error(t, err)\n\n\topt = DefaultOptions\n\topt.MaxIdle = 2\n\topt.MaxActive = 1\n\t_, err = New(\"127.0.0.1:8080\", opt)\n\trequire.Error(t, err)\n}\n\nfunc TestClose(t *testing.T) {\n\tp, nativePool, opt, err := newPool(nil)\n\trequire.NoError(t, err)\n\tp.Close()\n\n\trequire.EqualValues(t, 0, nativePool.index)\n\trequire.EqualValues(t, 0, nativePool.ref)\n\trequire.EqualValues(t, 0, nativePool.current)\n\trequire.EqualValues(t, true, nativePool.conns[0] == nil)\n\trequire.EqualValues(t, true, nativePool.conns[opt.MaxIdle-1] == nil)\n}\n\nfunc TestReset(t *testing.T) {\n\tp, nativePool, opt, err := newPool(nil)\n\trequire.NoError(t, err)\n\tdefer p.Close()\n\n\tnativePool.reset(0)\n\trequire.EqualValues(t, true, nativePool.conns[0] == nil)\n\tnativePool.reset(opt.MaxIdle + 1)\n\trequire.EqualValues(t, true, nativePool.conns[opt.MaxIdle+1] == nil)\n}\n\nfunc TestBasicGet(t *testing.T) {\n\tp, nativePool, _, err := newPool(nil)\n\trequire.NoError(t, err)\n\tdefer p.Close()\n\n\tconn, err := p.Get()\n\trequire.NoError(t, err)\n\trequire.EqualValues(t, true, conn.Value() != nil)\n\n\trequire.EqualValues(t, 1, nativePool.index)\n\trequire.EqualValues(t, 1, nativePool.ref)\n\n\tconn.Close()\n\n\trequire.EqualValues(t, 1, nativePool.index)\n\trequire.EqualValues(t, 0, nativePool.ref)\n}\n\nfunc TestGetAfterClose(t *testing.T) {\n\tp, _, _, err := newPool(nil)\n\trequire.NoError(t, err)\n\tp.Close()\n\n\t_, err = p.Get()\n\trequire.EqualError(t, err, \"pool is closed\")\n}\n\nfunc TestBasicGet2(t *testing.T) {\n\topt := DefaultOptions\n\topt.Dial = DialTest\n\topt.MaxIdle = 1\n\topt.MaxActive = 2\n\topt.MaxConcurrentStreams = 2\n\topt.Reuse = true\n\n\tp, nativePool, _, err := newPool(&opt)\n\trequire.NoError(t, err)\n\tdefer p.Close()\n\n\tconn1, err := p.Get()\n\trequire.NoError(t, err)\n\tdefer conn1.Close()\n\n\tconn2, err := p.Get()\n\trequire.NoError(t, err)\n\tdefer conn2.Close()\n\n\trequire.EqualValues(t, 2, nativePool.index)\n\trequire.EqualValues(t, 2, nativePool.ref)\n\trequire.EqualValues(t, 1, nativePool.current)\n\n\t// create new connections push back to pool\n\tconn3, err := p.Get()\n\trequire.NoError(t, err)\n\tdefer conn3.Close()\n\n\trequire.EqualValues(t, 3, nativePool.index)\n\trequire.EqualValues(t, 3, nativePool.ref)\n\trequire.EqualValues(t, 2, nativePool.current)\n\n\tconn4, err := p.Get()\n\trequire.NoError(t, err)\n\tdefer conn4.Close()\n\n\t// reuse exists connections\n\tconn5, err := p.Get()\n\trequire.NoError(t, err)\n\tdefer conn5.Close()\n\n\tnativeConn := conn5.(*conn)\n\trequire.EqualValues(t, false, nativeConn.once)\n}\n\nfunc TestBasicGet3(t *testing.T) {\n\topt := DefaultOptions\n\topt.Dial = DialTest\n\topt.MaxIdle = 1\n\topt.MaxActive = 1\n\topt.MaxConcurrentStreams = 1\n\topt.Reuse = false\n\n\tp, _, _, err := newPool(&opt)\n\trequire.NoError(t, err)\n\tdefer p.Close()\n\n\tconn1, err := p.Get()\n\trequire.NoError(t, err)\n\tdefer conn1.Close()\n\n\t// create new connections doesn't push back to pool\n\tconn2, err := p.Get()\n\trequire.NoError(t, err)\n\tdefer conn2.Close()\n\n\tnativeConn := conn2.(*conn)\n\trequire.EqualValues(t, true, nativeConn.once)\n}\n\nfunc TestConcurrentGet(t *testing.T) {\n\topt := DefaultOptions\n\topt.Dial = DialTest\n\topt.MaxIdle = 8\n\topt.MaxActive = 64\n\topt.MaxConcurrentStreams = 2\n\topt.Reuse = false\n\n\tp, nativePool, _, err := newPool(&opt)\n\trequire.NoError(t, err)\n\tdefer p.Close()\n\n\tvar wg sync.WaitGroup\n\twg.Add(500)\n\n\tfor i := 0; i < 500; i++ {\n\t\tgo func(i int) {\n\t\t\tconn, err := p.Get()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.EqualValues(t, true, conn != nil)\n\t\t\tconn.Close()\n\t\t\twg.Done()\n\t\t\tt.Logf(\"goroutine: %v, index: %v, ref: %v, current: %v\", i,\n\t\t\t\tatomic.LoadUint32(&nativePool.index),\n\t\t\t\tatomic.LoadInt32(&nativePool.ref),\n\t\t\t\tatomic.LoadInt32(&nativePool.current))\n\t\t}(i)\n\t}\n\twg.Wait()\n\n\trequire.EqualValues(t, 0, nativePool.ref)\n\trequire.EqualValues(t, opt.MaxIdle, nativePool.current)\n\trequire.EqualValues(t, true, nativePool.conns[0] != nil)\n\trequire.EqualValues(t, true, nativePool.conns[opt.MaxIdle] == nil)\n}\n\nvar size = 4 * 1024 * 1024\n\nfunc BenchmarkPoolRPC(b *testing.B) {\n\topt := DefaultOptions\n\tp, err := New(*endpoint, opt)\n\tif err != nil {\n\t\tb.Fatalf(\"failed to new pool: %v\", err)\n\t}\n\tdefer p.Close()\n\n\ttestFunc := func() {\n\t\tconn, err := p.Get()\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"failed to get conn: %v\", err)\n\t\t}\n\t\tdefer conn.Close()\n\n\t\tclient := pb.NewEchoClient(conn.Value())\n\t\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\n\t\tdata := make([]byte, size)\n\t\t_, err = client.Say(ctx, &pb.EchoRequest{Message: data})\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"unexpected error from Say: %v\", err)\n\t\t}\n\t}\n\n\tb.ResetTimer()\n\tb.RunParallel(func(tpb *testing.PB) {\n\t\tfor tpb.Next() {\n\t\t\ttestFunc()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSingleRPC(b *testing.B) {\n\ttestFunc := func() {\n\t\tcc, err := Dial(*endpoint)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"failed to create grpc conn: %v\", err)\n\t\t}\n\n\t\tclient := pb.NewEchoClient(cc)\n\t\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\n\t\tdata := make([]byte, size)\n\t\t_, err = client.Say(ctx, &pb.EchoRequest{Message: data})\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"unexpected error from Say: %v\", err)\n\t\t}\n\t}\n\n\tb.RunParallel(func(tpb *testing.PB) {\n\t\tfor tpb.Next() {\n\t\t\ttestFunc()\n\t\t}\n\t})\n}\n"
  }
]