| 1 | package yarpc |
| 2 | |
| 3 | import ( |
| 4 | "net" |
| 5 | |
| 6 | "context" |
| 7 | |
| 8 | "github.com/influxdata/yamux" |
| 9 | ) |
| 10 | |
| 11 | type dialOptions struct { |
| 12 | codec Codec |
| 13 | } |
| 14 | |
| 15 | type DialOption func(*dialOptions) |
| 16 | |
| 17 | func WithCodec(c Codec) DialOption { |
| 18 | return func(o *dialOptions) { |
| 19 | o.codec = c |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | func Dial(addr string, opt ...DialOption) (*ClientConn, error) { |
| 24 | return DialContext(context.Background(), addr, opt...) |
| 25 | } |
| 26 | |
| 27 | func DialContext(ctx context.Context, addr string, opts ...DialOption) (*ClientConn, error) { |
| 28 | cn, err := net.Dial("tcp", addr) |
| 29 | if err != nil { |
| 30 | return nil, err |
| 31 | } |
| 32 | |
| 33 | s, err := yamux.Client(cn, nil) |
| 34 | if err != nil { |
| 35 | return nil, err |
| 36 | } |
| 37 | cc := &ClientConn{s: s} |
| 38 | cc.ctx, cc.cancel = context.WithCancel(ctx) |
| 39 | |
| 40 | for _, opt := range opts { |
| 41 | opt(&cc.dopts) |
| 42 | } |
| 43 | |
| 44 | if cc.dopts.codec == nil { |
| 45 | cc.dopts.codec = NewCodec() |
| 46 | } |
| 47 | |
| 48 | return cc, nil |
| 49 | } |
| 50 | |
| 51 | type ClientConn struct { |
| 52 | ctx context.Context |
| 53 | cancel context.CancelFunc |
| 54 | s *yamux.Session |
| 55 | dopts dialOptions |
| 56 | } |
| 57 | |
| 58 | func (cc *ClientConn) NewStream() (*yamux.Stream, error) { |
| 59 | return cc.s.OpenStream() |
| 60 | } |
| 61 | |
| 62 | func (cc *ClientConn) Close() error { |
| 63 | cc.cancel() |
| 64 | return cc.s.Close() |
| 65 | } |