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