chore: import upstream snapshot with attribution
govulncheck / govulncheck (push) Has been cancelled
Lint / golangci-lint (push) Has been cancelled
Run Tests / Unit Tests (push) Has been cancelled
Run Tests / Etcd Integration Tests (push) Has been cancelled
Harness (E2E) / Harnesses (mock LLM) (push) Has been cancelled
Harness (E2E) / Provider harnesses (live LLM conformance) (push) Has been cancelled
govulncheck / govulncheck (push) Has been cancelled
Lint / golangci-lint (push) Has been cancelled
Run Tests / Unit Tests (push) Has been cancelled
Run Tests / Etcd Integration Tests (push) Has been cancelled
Harness (E2E) / Harnesses (mock LLM) (push) Has been cancelled
Harness (E2E) / Provider harnesses (live LLM conformance) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
type netListener struct{}
|
||||
|
||||
// getNetListener Get net.Listener from ListenOptions.
|
||||
func getNetListener(o *ListenOptions) net.Listener {
|
||||
if o.Context == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if l, ok := o.Context.Value(netListener{}).(net.Listener); ok && l != nil {
|
||||
return l
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// Package grpc provides a grpc transport
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
|
||||
"go-micro.dev/v6/cmd"
|
||||
maddr "go-micro.dev/v6/internal/util/addr"
|
||||
mnet "go-micro.dev/v6/internal/util/net"
|
||||
mtls "go-micro.dev/v6/internal/util/tls"
|
||||
"go-micro.dev/v6/transport"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
|
||||
pb "go-micro.dev/v6/transport/grpc/proto"
|
||||
)
|
||||
|
||||
type grpcTransport struct {
|
||||
opts transport.Options
|
||||
}
|
||||
|
||||
type grpcTransportListener struct {
|
||||
listener net.Listener
|
||||
secure bool
|
||||
tls *tls.Config
|
||||
}
|
||||
|
||||
func init() {
|
||||
cmd.DefaultTransports["grpc"] = NewTransport
|
||||
}
|
||||
|
||||
func getTLSConfig(addr string) (*tls.Config, error) {
|
||||
hosts := []string{addr}
|
||||
|
||||
// check if its a valid host:port
|
||||
if host, _, err := net.SplitHostPort(addr); err == nil {
|
||||
if len(host) == 0 {
|
||||
hosts = maddr.IPs()
|
||||
} else {
|
||||
hosts = []string{host}
|
||||
}
|
||||
}
|
||||
|
||||
// generate a certificate
|
||||
cert, err := mtls.Certificate(hosts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &tls.Config{Certificates: []tls.Certificate{cert}}, nil
|
||||
}
|
||||
|
||||
func (t *grpcTransportListener) Addr() string {
|
||||
return t.listener.Addr().String()
|
||||
}
|
||||
|
||||
func (t *grpcTransportListener) Close() error {
|
||||
return t.listener.Close()
|
||||
}
|
||||
|
||||
func (t *grpcTransportListener) Accept(fn func(transport.Socket)) error {
|
||||
var opts []grpc.ServerOption
|
||||
|
||||
// setup tls if specified
|
||||
if t.secure || t.tls != nil {
|
||||
config := t.tls
|
||||
if config == nil {
|
||||
var err error
|
||||
addr := t.listener.Addr().String()
|
||||
config, err = getTLSConfig(addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
creds := credentials.NewTLS(config)
|
||||
opts = append(opts, grpc.Creds(creds))
|
||||
}
|
||||
|
||||
// new service
|
||||
srv := grpc.NewServer(opts...)
|
||||
|
||||
// register service
|
||||
pb.RegisterTransportServer(srv, µTransport{addr: t.listener.Addr().String(), fn: fn})
|
||||
|
||||
// start serving
|
||||
return srv.Serve(t.listener)
|
||||
}
|
||||
|
||||
func (t *grpcTransport) Dial(addr string, opts ...transport.DialOption) (transport.Client, error) {
|
||||
dopts := transport.DialOptions{
|
||||
Timeout: transport.DefaultDialTimeout,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&dopts)
|
||||
}
|
||||
|
||||
options := []grpc.DialOption{
|
||||
grpc.WithTimeout(dopts.Timeout),
|
||||
}
|
||||
|
||||
if t.opts.Secure || t.opts.TLSConfig != nil {
|
||||
config := t.opts.TLSConfig
|
||||
if config == nil {
|
||||
// Use environment-based config - secure by default
|
||||
config = mtls.Config()
|
||||
}
|
||||
creds := credentials.NewTLS(config)
|
||||
options = append(options, grpc.WithTransportCredentials(creds))
|
||||
} else {
|
||||
options = append(options, grpc.WithInsecure())
|
||||
}
|
||||
|
||||
// dial the server
|
||||
conn, err := grpc.Dial(addr, options...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// create stream
|
||||
stream, err := pb.NewTransportClient(conn).Stream(context.Background())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// return a client
|
||||
return &grpcTransportClient{
|
||||
conn: conn,
|
||||
stream: stream,
|
||||
local: "localhost",
|
||||
remote: addr,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *grpcTransport) Listen(addr string, opts ...transport.ListenOption) (transport.Listener, error) {
|
||||
var options transport.ListenOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
ln, err := mnet.Listen(addr, func(addr string) (net.Listener, error) {
|
||||
return net.Listen("tcp", addr)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &grpcTransportListener{
|
||||
listener: ln,
|
||||
tls: t.opts.TLSConfig,
|
||||
secure: t.opts.Secure,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *grpcTransport) Init(opts ...transport.Option) error {
|
||||
for _, o := range opts {
|
||||
o(&t.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *grpcTransport) Options() transport.Options {
|
||||
return t.opts
|
||||
}
|
||||
|
||||
func (t *grpcTransport) String() string {
|
||||
return "grpc"
|
||||
}
|
||||
|
||||
func NewTransport(opts ...transport.Option) transport.Transport {
|
||||
var options transport.Options
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return &grpcTransport{opts: options}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"go-micro.dev/v6/transport"
|
||||
)
|
||||
|
||||
// func TestGRPCTransportPortRange(t *testing.T) {
|
||||
// tp := NewTransport()
|
||||
|
||||
// lsn1, err := tp.Listen(":44454-44458")
|
||||
// if err != nil {
|
||||
// t.Errorf("Did not expect an error, got %s", err)
|
||||
// }
|
||||
// expectedPort(t, "44454", lsn1)
|
||||
|
||||
// lsn2, err := tp.Listen(":44454-44458")
|
||||
// if err != nil {
|
||||
// t.Errorf("Did not expect an error, got %s", err)
|
||||
// }
|
||||
// expectedPort(t, "44455", lsn2)
|
||||
|
||||
// lsn, err := tp.Listen(":0")
|
||||
// if err != nil {
|
||||
// t.Errorf("Did not expect an error, got %s", err)
|
||||
// }
|
||||
|
||||
// lsn.Close()
|
||||
// lsn1.Close()
|
||||
// lsn2.Close()
|
||||
// }
|
||||
|
||||
func TestGRPCTransportCommunication(t *testing.T) {
|
||||
tr := NewTransport()
|
||||
|
||||
l, err := tr.Listen(":0")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected listen err: %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
fn := func(sock transport.Socket) {
|
||||
defer sock.Close()
|
||||
|
||||
for {
|
||||
var m transport.Message
|
||||
if err := sock.Recv(&m); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := sock.Send(&m); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
done := make(chan bool)
|
||||
|
||||
go func() {
|
||||
if err := l.Accept(fn); err != nil {
|
||||
select {
|
||||
case <-done:
|
||||
default:
|
||||
t.Errorf("Unexpected accept err: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := tr.Dial(l.Addr())
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected dial err: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
m := transport.Message{
|
||||
Header: map[string]string{
|
||||
"X-Content-Type": "application/json",
|
||||
},
|
||||
Body: []byte(`{"message": "Hello World"}`),
|
||||
}
|
||||
|
||||
if err := c.Send(&m); err != nil {
|
||||
t.Errorf("Unexpected send err: %v", err)
|
||||
}
|
||||
|
||||
var rm transport.Message
|
||||
|
||||
if err := c.Recv(&rm); err != nil {
|
||||
t.Errorf("Unexpected recv err: %v", err)
|
||||
}
|
||||
|
||||
if string(rm.Body) != string(m.Body) {
|
||||
t.Errorf("Expected %v, got %v", m.Body, rm.Body)
|
||||
}
|
||||
|
||||
close(done)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"runtime/debug"
|
||||
|
||||
"go-micro.dev/v6/errors"
|
||||
"go-micro.dev/v6/logger"
|
||||
"go-micro.dev/v6/transport"
|
||||
pb "go-micro.dev/v6/transport/grpc/proto"
|
||||
"google.golang.org/grpc/peer"
|
||||
)
|
||||
|
||||
// microTransport satisfies the pb.TransportServer inteface.
|
||||
type microTransport struct {
|
||||
addr string
|
||||
fn func(transport.Socket)
|
||||
}
|
||||
|
||||
func (m *microTransport) Stream(ts pb.Transport_StreamServer) (err error) {
|
||||
sock := &grpcTransportSocket{
|
||||
stream: ts,
|
||||
local: m.addr,
|
||||
}
|
||||
|
||||
p, ok := peer.FromContext(ts.Context())
|
||||
if ok {
|
||||
sock.remote = p.Addr.String()
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger.Error(r, string(debug.Stack()))
|
||||
sock.Close()
|
||||
err = errors.InternalServerError("go.micro.transport", "panic recovered: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
// execute socket func
|
||||
m.fn(sock)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.32.0
|
||||
// protoc v4.25.3
|
||||
// source: proto/transport.proto
|
||||
|
||||
package transport
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Header map[string]string `protobuf:"bytes,1,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Body []byte `protobuf:"bytes,2,opt,name=body,proto3" json:"body,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Message) Reset() {
|
||||
*x = Message{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_proto_transport_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Message) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Message) ProtoMessage() {}
|
||||
|
||||
func (x *Message) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proto_transport_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Message.ProtoReflect.Descriptor instead.
|
||||
func (*Message) Descriptor() ([]byte, []int) {
|
||||
return file_proto_transport_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Message) GetHeader() map[string]string {
|
||||
if x != nil {
|
||||
return x.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetBody() []byte {
|
||||
if x != nil {
|
||||
return x.Body
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proto_transport_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_proto_transport_proto_rawDesc = []byte{
|
||||
0x0a, 0x15, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72,
|
||||
0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x17, 0x67, 0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72,
|
||||
0x6f, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x67, 0x72, 0x70, 0x63,
|
||||
0x22, 0x9e, 0x01, 0x0a, 0x07, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x44, 0x0a, 0x06,
|
||||
0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x67,
|
||||
0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72,
|
||||
0x74, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x48,
|
||||
0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64,
|
||||
0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c,
|
||||
0x52, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x1a, 0x39, 0x0a, 0x0b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72,
|
||||
0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
|
||||
0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||
0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38,
|
||||
0x01, 0x32, 0x5f, 0x0a, 0x09, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x52,
|
||||
0x0a, 0x06, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x20, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69,
|
||||
0x63, 0x72, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x67, 0x72,
|
||||
0x70, 0x63, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x20, 0x2e, 0x67, 0x6f, 0x2e,
|
||||
0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e,
|
||||
0x67, 0x72, 0x70, 0x63, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x28, 0x01,
|
||||
0x30, 0x01, 0x42, 0x13, 0x5a, 0x11, 0x2e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x3b, 0x74, 0x72,
|
||||
0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_proto_transport_proto_rawDescOnce sync.Once
|
||||
file_proto_transport_proto_rawDescData = file_proto_transport_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_proto_transport_proto_rawDescGZIP() []byte {
|
||||
file_proto_transport_proto_rawDescOnce.Do(func() {
|
||||
file_proto_transport_proto_rawDescData = protoimpl.X.CompressGZIP(file_proto_transport_proto_rawDescData)
|
||||
})
|
||||
return file_proto_transport_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_proto_transport_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_proto_transport_proto_goTypes = []interface{}{
|
||||
(*Message)(nil), // 0: go.micro.transport.grpc.Message
|
||||
nil, // 1: go.micro.transport.grpc.Message.HeaderEntry
|
||||
}
|
||||
var file_proto_transport_proto_depIdxs = []int32{
|
||||
1, // 0: go.micro.transport.grpc.Message.header:type_name -> go.micro.transport.grpc.Message.HeaderEntry
|
||||
0, // 1: go.micro.transport.grpc.Transport.Stream:input_type -> go.micro.transport.grpc.Message
|
||||
0, // 2: go.micro.transport.grpc.Transport.Stream:output_type -> go.micro.transport.grpc.Message
|
||||
2, // [2:3] is the sub-list for method output_type
|
||||
1, // [1:2] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proto_transport_proto_init() }
|
||||
func file_proto_transport_proto_init() {
|
||||
if File_proto_transport_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_proto_transport_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Message); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_proto_transport_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_proto_transport_proto_goTypes,
|
||||
DependencyIndexes: file_proto_transport_proto_depIdxs,
|
||||
MessageInfos: file_proto_transport_proto_msgTypes,
|
||||
}.Build()
|
||||
File_proto_transport_proto = out.File
|
||||
file_proto_transport_proto_rawDesc = nil
|
||||
file_proto_transport_proto_goTypes = nil
|
||||
file_proto_transport_proto_depIdxs = nil
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
// Code generated by protoc-gen-micro. DO NOT EDIT.
|
||||
// source: proto/transport.proto
|
||||
|
||||
package transport
|
||||
|
||||
import (
|
||||
fmt "fmt"
|
||||
proto "google.golang.org/protobuf/proto"
|
||||
math "math"
|
||||
)
|
||||
|
||||
import (
|
||||
context "context"
|
||||
client "go-micro.dev/v6/client"
|
||||
server "go-micro.dev/v6/server"
|
||||
)
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = fmt.Errorf
|
||||
var _ = math.Inf
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ context.Context
|
||||
var _ client.Option
|
||||
var _ server.Option
|
||||
|
||||
// Client API for Transport service
|
||||
|
||||
type TransportService interface {
|
||||
Stream(ctx context.Context, opts ...client.CallOption) (Transport_StreamService, error)
|
||||
}
|
||||
|
||||
type transportService struct {
|
||||
c client.Client
|
||||
name string
|
||||
}
|
||||
|
||||
func NewTransportService(name string, c client.Client) TransportService {
|
||||
return &transportService{
|
||||
c: c,
|
||||
name: name,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *transportService) Stream(ctx context.Context, opts ...client.CallOption) (Transport_StreamService, error) {
|
||||
req := c.c.NewRequest(c.name, "Transport.Stream", &Message{})
|
||||
stream, err := c.c.Stream(ctx, req, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &transportServiceStream{stream}, nil
|
||||
}
|
||||
|
||||
type Transport_StreamService interface {
|
||||
Context() context.Context
|
||||
SendMsg(interface{}) error
|
||||
RecvMsg(interface{}) error
|
||||
CloseSend() error
|
||||
Close() error
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
}
|
||||
|
||||
type transportServiceStream struct {
|
||||
stream client.Stream
|
||||
}
|
||||
|
||||
func (x *transportServiceStream) CloseSend() error {
|
||||
return x.stream.CloseSend()
|
||||
}
|
||||
|
||||
func (x *transportServiceStream) Close() error {
|
||||
return x.stream.Close()
|
||||
}
|
||||
|
||||
func (x *transportServiceStream) Context() context.Context {
|
||||
return x.stream.Context()
|
||||
}
|
||||
|
||||
func (x *transportServiceStream) SendMsg(m interface{}) error {
|
||||
return x.stream.Send(m)
|
||||
}
|
||||
|
||||
func (x *transportServiceStream) RecvMsg(m interface{}) error {
|
||||
return x.stream.Recv(m)
|
||||
}
|
||||
|
||||
func (x *transportServiceStream) Send(m *Message) error {
|
||||
return x.stream.Send(m)
|
||||
}
|
||||
|
||||
func (x *transportServiceStream) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
err := x.stream.Recv(m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Server API for Transport service
|
||||
|
||||
type TransportHandler interface {
|
||||
Stream(context.Context, Transport_StreamStream) error
|
||||
}
|
||||
|
||||
func RegisterTransportHandler(s server.Server, hdlr TransportHandler, opts ...server.HandlerOption) error {
|
||||
type transport interface {
|
||||
Stream(ctx context.Context, stream server.Stream) error
|
||||
}
|
||||
type Transport struct {
|
||||
transport
|
||||
}
|
||||
h := &transportHandler{hdlr}
|
||||
return s.Handle(s.NewHandler(&Transport{h}, opts...))
|
||||
}
|
||||
|
||||
type transportHandler struct {
|
||||
TransportHandler
|
||||
}
|
||||
|
||||
func (h *transportHandler) Stream(ctx context.Context, stream server.Stream) error {
|
||||
return h.TransportHandler.Stream(ctx, &transportStreamStream{stream})
|
||||
}
|
||||
|
||||
type Transport_StreamStream interface {
|
||||
Context() context.Context
|
||||
SendMsg(interface{}) error
|
||||
RecvMsg(interface{}) error
|
||||
Close() error
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
}
|
||||
|
||||
type transportStreamStream struct {
|
||||
stream server.Stream
|
||||
}
|
||||
|
||||
func (x *transportStreamStream) Close() error {
|
||||
return x.stream.Close()
|
||||
}
|
||||
|
||||
func (x *transportStreamStream) Context() context.Context {
|
||||
return x.stream.Context()
|
||||
}
|
||||
|
||||
func (x *transportStreamStream) SendMsg(m interface{}) error {
|
||||
return x.stream.Send(m)
|
||||
}
|
||||
|
||||
func (x *transportStreamStream) RecvMsg(m interface{}) error {
|
||||
return x.stream.Recv(m)
|
||||
}
|
||||
|
||||
func (x *transportStreamStream) Send(m *Message) error {
|
||||
return x.stream.Send(m)
|
||||
}
|
||||
|
||||
func (x *transportStreamStream) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
if err := x.stream.Recv(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option go_package = "./proto;transport";
|
||||
|
||||
package go.micro.transport.grpc;
|
||||
|
||||
service Transport {
|
||||
rpc Stream(stream Message) returns (stream Message) {}
|
||||
}
|
||||
|
||||
message Message {
|
||||
map<string, string> header = 1;
|
||||
bytes body = 2;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.3.0
|
||||
// - protoc v4.25.3
|
||||
// source: proto/transport.proto
|
||||
|
||||
package transport
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.32.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion7
|
||||
|
||||
const (
|
||||
Transport_Stream_FullMethodName = "/go.micro.transport.grpc.Transport/Stream"
|
||||
)
|
||||
|
||||
// TransportClient is the client API for Transport service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type TransportClient interface {
|
||||
Stream(ctx context.Context, opts ...grpc.CallOption) (Transport_StreamClient, error)
|
||||
}
|
||||
|
||||
type transportClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewTransportClient(cc grpc.ClientConnInterface) TransportClient {
|
||||
return &transportClient{cc}
|
||||
}
|
||||
|
||||
func (c *transportClient) Stream(ctx context.Context, opts ...grpc.CallOption) (Transport_StreamClient, error) {
|
||||
stream, err := c.cc.NewStream(ctx, &Transport_ServiceDesc.Streams[0], Transport_Stream_FullMethodName, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &transportStreamClient{stream}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
type Transport_StreamClient interface {
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
type transportStreamClient struct {
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
func (x *transportStreamClient) Send(m *Message) error {
|
||||
return x.ClientStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *transportStreamClient) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
if err := x.ClientStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// TransportServer is the server API for Transport service.
|
||||
// All implementations should embed UnimplementedTransportServer
|
||||
// for forward compatibility
|
||||
type TransportServer interface {
|
||||
Stream(Transport_StreamServer) error
|
||||
}
|
||||
|
||||
// UnimplementedTransportServer should be embedded to have forward compatible implementations.
|
||||
type UnimplementedTransportServer struct {
|
||||
}
|
||||
|
||||
func (UnimplementedTransportServer) Stream(Transport_StreamServer) error {
|
||||
return status.Errorf(codes.Unimplemented, "method Stream not implemented")
|
||||
}
|
||||
|
||||
// UnsafeTransportServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to TransportServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeTransportServer interface {
|
||||
mustEmbedUnimplementedTransportServer()
|
||||
}
|
||||
|
||||
func RegisterTransportServer(s grpc.ServiceRegistrar, srv TransportServer) {
|
||||
s.RegisterService(&Transport_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _Transport_Stream_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
return srv.(TransportServer).Stream(&transportStreamServer{stream})
|
||||
}
|
||||
|
||||
type Transport_StreamServer interface {
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
type transportStreamServer struct {
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
func (x *transportStreamServer) Send(m *Message) error {
|
||||
return x.ServerStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *transportStreamServer) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
if err := x.ServerStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Transport_ServiceDesc is the grpc.ServiceDesc for Transport service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var Transport_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "go.micro.transport.grpc.Transport",
|
||||
HandlerType: (*TransportServer)(nil),
|
||||
Methods: []grpc.MethodDesc{},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
StreamName: "Stream",
|
||||
Handler: _Transport_Stream_Handler,
|
||||
ServerStreams: true,
|
||||
ClientStreams: true,
|
||||
},
|
||||
},
|
||||
Metadata: "proto/transport.proto",
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"go-micro.dev/v6/transport"
|
||||
pb "go-micro.dev/v6/transport/grpc/proto"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type grpcTransportClient struct {
|
||||
conn *grpc.ClientConn
|
||||
stream pb.Transport_StreamClient
|
||||
|
||||
local string
|
||||
remote string
|
||||
}
|
||||
|
||||
type grpcTransportSocket struct {
|
||||
stream pb.Transport_StreamServer
|
||||
local string
|
||||
remote string
|
||||
}
|
||||
|
||||
func (g *grpcTransportClient) Local() string {
|
||||
return g.local
|
||||
}
|
||||
|
||||
func (g *grpcTransportClient) Remote() string {
|
||||
return g.remote
|
||||
}
|
||||
|
||||
func (g *grpcTransportClient) Recv(m *transport.Message) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
msg, err := g.stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.Header = msg.Header
|
||||
m.Body = msg.Body
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *grpcTransportClient) Send(m *transport.Message) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return g.stream.Send(&pb.Message{
|
||||
Header: m.Header,
|
||||
Body: m.Body,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *grpcTransportClient) Close() error {
|
||||
return g.conn.Close()
|
||||
}
|
||||
|
||||
func (g *grpcTransportSocket) Local() string {
|
||||
return g.local
|
||||
}
|
||||
|
||||
func (g *grpcTransportSocket) Remote() string {
|
||||
return g.remote
|
||||
}
|
||||
|
||||
func (g *grpcTransportSocket) Recv(m *transport.Message) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
msg, err := g.stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.Header = msg.Header
|
||||
m.Body = msg.Body
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *grpcTransportSocket) Send(m *transport.Message) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return g.stream.Send(&pb.Message{
|
||||
Header: m.Header,
|
||||
Body: m.Body,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *grpcTransportSocket) Close() error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// headers is a package for internal micro global constants
|
||||
package headers
|
||||
|
||||
const (
|
||||
// Message header is a header for internal message communication.
|
||||
Message = "Micro-Topic"
|
||||
// Request header is a message header for internal request communication.
|
||||
Request = "Micro-Service"
|
||||
// Error header contains an error message.
|
||||
Error = "Micro-Error"
|
||||
// Endpoint header.
|
||||
Endpoint = "Micro-Endpoint"
|
||||
// Method header.
|
||||
Method = "Micro-Method"
|
||||
// ID header.
|
||||
ID = "Micro-ID"
|
||||
// Prefix used to prefix headers.
|
||||
Prefix = "Micro-"
|
||||
// Namespace header.
|
||||
Namespace = "Micro-Namespace"
|
||||
// Protocol header.
|
||||
Protocol = "Micro-Protocol"
|
||||
// Target header.
|
||||
Target = "Micro-Target"
|
||||
// ContentType header.
|
||||
ContentType = "Content-Type"
|
||||
// SpanID header.
|
||||
SpanID = "Micro-Span-ID"
|
||||
// TraceIDKey header.
|
||||
TraceIDKey = "Micro-Trace-ID"
|
||||
// Stream header.
|
||||
Stream = "Micro-Stream"
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
package transport
|
||||
|
||||
import "sync"
|
||||
|
||||
var http2BufPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
buf := make([]byte, DefaultBufSizeH2)
|
||||
return &buf
|
||||
},
|
||||
}
|
||||
|
||||
func getHTTP2BufPool() *sync.Pool {
|
||||
return &http2BufPool
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"go-micro.dev/v6/internal/util/buf"
|
||||
log "go-micro.dev/v6/logger"
|
||||
)
|
||||
|
||||
type httpTransportClient struct {
|
||||
dialOpts DialOptions
|
||||
conn net.Conn
|
||||
ht *httpTransport
|
||||
|
||||
// request must be stored for response processing
|
||||
req chan *http.Request
|
||||
buff *bufio.Reader
|
||||
addr string
|
||||
|
||||
// local/remote ip
|
||||
local string
|
||||
remote string
|
||||
reqList []*http.Request
|
||||
|
||||
sync.RWMutex
|
||||
|
||||
once sync.Once
|
||||
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (h *httpTransportClient) Local() string {
|
||||
return h.local
|
||||
}
|
||||
|
||||
func (h *httpTransportClient) Remote() string {
|
||||
return h.remote
|
||||
}
|
||||
|
||||
func (h *httpTransportClient) Send(m *Message) error {
|
||||
logger := h.ht.Options().Logger
|
||||
|
||||
header := make(http.Header)
|
||||
for k, v := range m.Header {
|
||||
header.Set(k, v)
|
||||
}
|
||||
|
||||
b := buf.New(bytes.NewBuffer(m.Body))
|
||||
defer func() {
|
||||
if err := b.Close(); err != nil {
|
||||
logger.Logf(log.ErrorLevel, "failed to close buffer: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
req := &http.Request{
|
||||
Method: http.MethodPost,
|
||||
URL: &url.URL{
|
||||
Scheme: "http",
|
||||
Host: h.addr,
|
||||
},
|
||||
Header: header,
|
||||
Body: b,
|
||||
ContentLength: int64(b.Len()),
|
||||
Host: h.addr,
|
||||
Close: h.dialOpts.ConnClose,
|
||||
}
|
||||
|
||||
if !h.dialOpts.Stream {
|
||||
h.Lock()
|
||||
if h.closed {
|
||||
h.Unlock()
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
h.reqList = append(h.reqList, req)
|
||||
|
||||
select {
|
||||
case h.req <- h.reqList[0]:
|
||||
h.reqList = h.reqList[1:]
|
||||
default:
|
||||
}
|
||||
h.Unlock()
|
||||
}
|
||||
|
||||
// set timeout if its greater than 0
|
||||
if h.ht.opts.Timeout > time.Duration(0) {
|
||||
if err := h.conn.SetDeadline(time.Now().Add(h.ht.opts.Timeout)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return req.Write(h.conn)
|
||||
|
||||
}
|
||||
|
||||
// Recv receives a message.
|
||||
func (h *httpTransportClient) Recv(msg *Message) (err error) {
|
||||
if msg == nil {
|
||||
return errors.New("message passed in is nil")
|
||||
}
|
||||
|
||||
var req *http.Request
|
||||
|
||||
if !h.dialOpts.Stream {
|
||||
|
||||
var rc *http.Request
|
||||
var ok bool
|
||||
|
||||
h.Lock()
|
||||
select {
|
||||
case rc, ok = <-h.req:
|
||||
default:
|
||||
}
|
||||
|
||||
if !ok {
|
||||
if len(h.reqList) == 0 {
|
||||
h.Unlock()
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
rc = h.reqList[0]
|
||||
h.reqList = h.reqList[1:]
|
||||
}
|
||||
h.Unlock()
|
||||
|
||||
req = rc
|
||||
}
|
||||
|
||||
// set timeout if its greater than 0
|
||||
if h.ht.opts.Timeout > time.Duration(0) {
|
||||
if err = h.conn.SetDeadline(time.Now().Add(h.ht.opts.Timeout)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
h.Lock()
|
||||
defer h.Unlock()
|
||||
|
||||
if h.closed {
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
rsp, err := http.ReadResponse(h.buff, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err2 := rsp.Body.Close(); err2 != nil {
|
||||
err = errors.Wrap(err2, "failed to close body")
|
||||
}
|
||||
}()
|
||||
|
||||
b, err := io.ReadAll(rsp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if rsp.StatusCode != http.StatusOK {
|
||||
return errors.New(rsp.Status + ": " + string(b))
|
||||
}
|
||||
|
||||
msg.Body = b
|
||||
|
||||
if msg.Header == nil {
|
||||
msg.Header = make(map[string]string, len(rsp.Header))
|
||||
}
|
||||
|
||||
for k, v := range rsp.Header {
|
||||
if len(v) > 0 {
|
||||
msg.Header[k] = v[0]
|
||||
} else {
|
||||
msg.Header[k] = ""
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportClient) Close() error {
|
||||
if !h.dialOpts.Stream {
|
||||
h.once.Do(
|
||||
func() {
|
||||
h.Lock()
|
||||
h.buff.Reset(nil)
|
||||
h.closed = true
|
||||
h.Unlock()
|
||||
close(h.req)
|
||||
},
|
||||
)
|
||||
|
||||
return h.conn.Close()
|
||||
}
|
||||
|
||||
err := h.conn.Close()
|
||||
h.once.Do(
|
||||
func() {
|
||||
h.Lock()
|
||||
h.buff.Reset(nil)
|
||||
h.closed = true
|
||||
h.Unlock()
|
||||
close(h.req)
|
||||
},
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func TestHttpTransportClient(t *testing.T) {
|
||||
// arrange
|
||||
l, c, err := echoHttpTransportClient("127.0.0.1:")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer l.Close()
|
||||
defer c.Close()
|
||||
|
||||
// act + assert
|
||||
N := cap(c.req)
|
||||
// Send N+1 messages to overflow the buffered channel and place the extra message in the internal buffer
|
||||
for i := 0; i < N+1; i++ {
|
||||
body := fmt.Sprintf("msg-%d", i)
|
||||
if err := c.Send(&Message{Body: []byte(body)}); err != nil {
|
||||
t.Errorf("Unexpected send err: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// consume all requests from the buffered channel
|
||||
for i := 0; i < N; i++ {
|
||||
msg := Message{}
|
||||
if err := c.Recv(&msg); err != nil {
|
||||
t.Errorf("Unexpected recv err: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(c.reqList) != 1 {
|
||||
t.Error("Unexpected reqList")
|
||||
}
|
||||
|
||||
msg := Message{}
|
||||
if err := c.Recv(&msg); err != nil {
|
||||
t.Errorf("Unexpected recv err: %v", err)
|
||||
}
|
||||
want := fmt.Sprintf("msg-%d", N)
|
||||
got := string(msg.Body)
|
||||
if want != got {
|
||||
t.Errorf("Unexpected message: got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func echoHttpTransportClient(addr string) (*httpTransportListener, *httpTransportClient, error) {
|
||||
tr := NewHTTPTransport()
|
||||
l, err := tr.Listen(addr)
|
||||
if err != nil {
|
||||
return nil, nil, errors.Errorf("Unexpected listen err: %v", err)
|
||||
}
|
||||
c, err := tr.Dial(l.Addr())
|
||||
if err != nil {
|
||||
return nil, nil, errors.Errorf("Unexpected dial err: %v", err)
|
||||
}
|
||||
go l.Accept(echoHandler)
|
||||
return l.(*httpTransportListener), c.(*httpTransportClient), nil
|
||||
}
|
||||
|
||||
func echoHandler(sock Socket) {
|
||||
defer sock.Close()
|
||||
for {
|
||||
var msg Message
|
||||
if err := sock.Recv(&msg); err != nil {
|
||||
return
|
||||
}
|
||||
if err := sock.Send(&msg); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
log "go-micro.dev/v6/logger"
|
||||
|
||||
"golang.org/x/net/http2"
|
||||
"golang.org/x/net/http2/h2c"
|
||||
)
|
||||
|
||||
type httpTransportListener struct {
|
||||
ht *httpTransport
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
func (h *httpTransportListener) Addr() string {
|
||||
return h.listener.Addr().String()
|
||||
}
|
||||
|
||||
func (h *httpTransportListener) Close() error {
|
||||
return h.listener.Close()
|
||||
}
|
||||
|
||||
func (h *httpTransportListener) Accept(fn func(Socket)) error {
|
||||
// Create handler mux
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Register our transport handler
|
||||
mux.HandleFunc("/", h.newHandler(fn))
|
||||
|
||||
// Get optional handlers from context.
|
||||
// See examples/web-service for usage.
|
||||
if h.ht.opts.Context != nil {
|
||||
handlers, ok := h.ht.opts.Context.Value("http_handlers").(map[string]http.Handler)
|
||||
if ok {
|
||||
for pattern, handler := range handlers {
|
||||
mux.Handle(pattern, handler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Server ONLY supports HTTP1 + H2C
|
||||
srv := &http.Server{
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: time.Second * 5,
|
||||
}
|
||||
|
||||
// insecure connection use h2c
|
||||
if !h.ht.opts.Secure && h.ht.opts.TLSConfig == nil {
|
||||
srv.Handler = h2c.NewHandler(mux, &http2.Server{})
|
||||
}
|
||||
|
||||
return srv.Serve(h.listener)
|
||||
}
|
||||
|
||||
// newHandler creates a new HTTP transport handler passed to the mux.
|
||||
func (h *httpTransportListener) newHandler(serveConn func(Socket)) func(rsp http.ResponseWriter, req *http.Request) {
|
||||
logger := h.ht.opts.Logger
|
||||
|
||||
return func(rsp http.ResponseWriter, req *http.Request) {
|
||||
var (
|
||||
buf *bufio.ReadWriter
|
||||
con net.Conn
|
||||
)
|
||||
|
||||
// HTTP1: read a regular request
|
||||
if req.ProtoMajor == 1 {
|
||||
b, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
http.Error(rsp, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
|
||||
// Hijack the conn
|
||||
// We also don't close the connection here, as it will be closed by
|
||||
// the httpTransportSocket
|
||||
hj, ok := rsp.(http.Hijacker)
|
||||
if !ok {
|
||||
// We're screwed
|
||||
http.Error(rsp, "cannot serve conn", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
conn, bufrw, err := hj.Hijack()
|
||||
if err != nil {
|
||||
http.Error(rsp, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := conn.Close(); err != nil {
|
||||
logger.Logf(log.ErrorLevel, "Failed to close TCP connection: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
buf = bufrw
|
||||
con = conn
|
||||
}
|
||||
|
||||
// Buffered reader
|
||||
bufr := bufio.NewReader(req.Body)
|
||||
|
||||
// Save the request
|
||||
ch := make(chan *http.Request, 1)
|
||||
ch <- req
|
||||
|
||||
// Create a new transport socket
|
||||
sock := &httpTransportSocket{
|
||||
ht: h.ht,
|
||||
w: rsp,
|
||||
r: req,
|
||||
rw: buf,
|
||||
buf: bufr,
|
||||
ch: ch,
|
||||
conn: con,
|
||||
local: h.Addr(),
|
||||
remote: req.RemoteAddr,
|
||||
closed: make(chan bool),
|
||||
}
|
||||
|
||||
// Execute the socket
|
||||
serveConn(sock)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const (
|
||||
proxyAuthHeader = "Proxy-Authorization"
|
||||
)
|
||||
|
||||
func getURL(addr string) (*url.URL, error) {
|
||||
r := &http.Request{
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: addr,
|
||||
},
|
||||
}
|
||||
|
||||
return http.ProxyFromEnvironment(r)
|
||||
}
|
||||
|
||||
type pbuffer struct {
|
||||
net.Conn
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
func (p *pbuffer) Read(b []byte) (int, error) {
|
||||
return p.r.Read(b)
|
||||
}
|
||||
|
||||
func proxyDial(conn net.Conn, addr string, proxyURL *url.URL) (_ net.Conn, err error) {
|
||||
defer func() {
|
||||
if err != nil {
|
||||
// trunk-ignore(golangci-lint/errcheck)
|
||||
conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
r := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{Host: addr},
|
||||
Header: map[string][]string{"User-Agent": {"micro/latest"}},
|
||||
}
|
||||
|
||||
if user := proxyURL.User; user != nil {
|
||||
u := user.Username()
|
||||
p, _ := user.Password()
|
||||
auth := []byte(u + ":" + p)
|
||||
basicAuth := base64.StdEncoding.EncodeToString(auth)
|
||||
r.Header.Add(proxyAuthHeader, "Basic "+basicAuth)
|
||||
}
|
||||
|
||||
if err := r.Write(conn); err != nil {
|
||||
return nil, fmt.Errorf("failed to write the HTTP request: %w", err)
|
||||
}
|
||||
|
||||
br := bufio.NewReader(conn)
|
||||
|
||||
rsp, err := http.ReadResponse(br, r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading server HTTP response: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err = rsp.Body.Close()
|
||||
}()
|
||||
|
||||
if rsp.StatusCode != http.StatusOK {
|
||||
dump, err := httputil.DumpResponse(rsp, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to do connect handshake, status code: %s", rsp.Status)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump)
|
||||
}
|
||||
|
||||
return &pbuffer{Conn: conn, r: br}, nil
|
||||
}
|
||||
|
||||
// Creates a new connection.
|
||||
func newConn(dial func(string) (net.Conn, error)) func(string) (net.Conn, error) {
|
||||
return func(addr string) (net.Conn, error) {
|
||||
// get the proxy url
|
||||
proxyURL, err := getURL(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// set to addr
|
||||
callAddr := addr
|
||||
|
||||
// got proxy
|
||||
if proxyURL != nil {
|
||||
callAddr = proxyURL.Host
|
||||
}
|
||||
|
||||
// dial the addr
|
||||
c, err := dial(callAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// do proxy connect if we have proxy url
|
||||
if proxyURL != nil {
|
||||
c, err = proxyDial(c, addr, proxyURL)
|
||||
}
|
||||
|
||||
return c, err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type httpTransportSocket struct {
|
||||
w http.ResponseWriter
|
||||
|
||||
// the hijacked when using http 1
|
||||
conn net.Conn
|
||||
ht *httpTransport
|
||||
r *http.Request
|
||||
rw *bufio.ReadWriter
|
||||
|
||||
// for the first request
|
||||
ch chan *http.Request
|
||||
|
||||
// h2 things
|
||||
buf *bufio.Reader
|
||||
// indicate if socket is closed
|
||||
closed chan bool
|
||||
|
||||
// local/remote ip
|
||||
local string
|
||||
remote string
|
||||
|
||||
mtx sync.RWMutex
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Local() string {
|
||||
return h.local
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Remote() string {
|
||||
return h.remote
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Recv(msg *Message) error {
|
||||
if msg == nil {
|
||||
return errors.New("message passed in is nil")
|
||||
}
|
||||
|
||||
if msg.Header == nil {
|
||||
msg.Header = make(map[string]string, len(h.r.Header))
|
||||
}
|
||||
|
||||
if h.r.ProtoMajor == 1 {
|
||||
return h.recvHTTP1(msg)
|
||||
}
|
||||
|
||||
return h.recvHTTP2(msg)
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Send(msg *Message) error {
|
||||
// we need to lock to protect the write
|
||||
h.mtx.RLock()
|
||||
defer h.mtx.RUnlock()
|
||||
|
||||
if h.r.ProtoMajor == 1 {
|
||||
return h.sendHTTP1(msg)
|
||||
}
|
||||
|
||||
return h.sendHTTP2(msg)
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Close() error {
|
||||
h.mtx.Lock()
|
||||
defer h.mtx.Unlock()
|
||||
|
||||
select {
|
||||
case <-h.closed:
|
||||
return nil
|
||||
default:
|
||||
// Close the channel
|
||||
close(h.closed)
|
||||
|
||||
// Close the buffer
|
||||
if err := h.r.Body.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) error(m *Message) error {
|
||||
if h.r.ProtoMajor == 1 {
|
||||
rsp := &http.Response{
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(bytes.NewReader(m.Body)),
|
||||
Status: "500 Internal Server Error",
|
||||
StatusCode: http.StatusInternalServerError,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
ContentLength: int64(len(m.Body)),
|
||||
}
|
||||
|
||||
for k, v := range m.Header {
|
||||
rsp.Header.Set(k, v)
|
||||
}
|
||||
|
||||
return rsp.Write(h.conn)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) recvHTTP1(msg *Message) error {
|
||||
// set timeout if its greater than 0
|
||||
if h.ht.opts.Timeout > time.Duration(0) {
|
||||
if err := h.conn.SetDeadline(time.Now().Add(h.ht.opts.Timeout)); err != nil {
|
||||
return errors.Wrap(err, "failed to set deadline")
|
||||
}
|
||||
}
|
||||
|
||||
var req *http.Request
|
||||
|
||||
select {
|
||||
// get first request
|
||||
case req = <-h.ch:
|
||||
// read next request
|
||||
default:
|
||||
rr, err := http.ReadRequest(h.rw.Reader)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read request")
|
||||
}
|
||||
|
||||
req = rr
|
||||
}
|
||||
|
||||
// read body
|
||||
b, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read body")
|
||||
}
|
||||
|
||||
// set body
|
||||
if err := req.Body.Close(); err != nil {
|
||||
return errors.Wrap(err, "failed to close body")
|
||||
}
|
||||
|
||||
msg.Body = b
|
||||
|
||||
// set headers
|
||||
for k, v := range req.Header {
|
||||
if len(v) > 0 {
|
||||
msg.Header[k] = v[0]
|
||||
} else {
|
||||
msg.Header[k] = ""
|
||||
}
|
||||
}
|
||||
|
||||
// return early early
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) recvHTTP2(msg *Message) error {
|
||||
// only process if the socket is open
|
||||
select {
|
||||
case <-h.closed:
|
||||
return io.EOF
|
||||
default:
|
||||
}
|
||||
|
||||
// buffer pool for reuse
|
||||
var bufPool = getHTTP2BufPool()
|
||||
|
||||
// set max buffer size
|
||||
s := h.ht.opts.BuffSizeH2
|
||||
if s == 0 {
|
||||
s = DefaultBufSizeH2
|
||||
}
|
||||
|
||||
bufp := bufPool.Get().(*[]byte)
|
||||
buf := *bufp
|
||||
if cap(buf) < s {
|
||||
buf = make([]byte, s)
|
||||
*bufp = buf
|
||||
}
|
||||
buf = buf[:s]
|
||||
|
||||
n, err := h.buf.Read(buf)
|
||||
if err != nil {
|
||||
bufPool.Put(bufp)
|
||||
return err
|
||||
}
|
||||
|
||||
if n > 0 {
|
||||
msg.Body = make([]byte, n)
|
||||
copy(msg.Body, buf[:n])
|
||||
}
|
||||
bufPool.Put(bufp)
|
||||
|
||||
for k, v := range h.r.Header {
|
||||
if len(v) > 0 {
|
||||
msg.Header[k] = v[0]
|
||||
} else {
|
||||
msg.Header[k] = ""
|
||||
}
|
||||
}
|
||||
|
||||
msg.Header[":path"] = h.r.URL.Path
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) sendHTTP1(msg *Message) error {
|
||||
// make copy of header
|
||||
hdr := make(http.Header)
|
||||
for k, v := range h.r.Header {
|
||||
hdr[k] = v
|
||||
}
|
||||
|
||||
rsp := &http.Response{
|
||||
Header: hdr,
|
||||
Body: io.NopCloser(bytes.NewReader(msg.Body)),
|
||||
Status: "200 OK",
|
||||
StatusCode: http.StatusOK,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
ContentLength: int64(len(msg.Body)),
|
||||
}
|
||||
|
||||
for k, v := range msg.Header {
|
||||
rsp.Header.Set(k, v)
|
||||
}
|
||||
|
||||
// set timeout if its greater than 0
|
||||
if h.ht.opts.Timeout > time.Duration(0) {
|
||||
if err := h.conn.SetDeadline(time.Now().Add(h.ht.opts.Timeout)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return rsp.Write(h.conn)
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) sendHTTP2(msg *Message) error {
|
||||
// only process if the socket is open
|
||||
select {
|
||||
case <-h.closed:
|
||||
return io.EOF
|
||||
default:
|
||||
}
|
||||
|
||||
// set headers
|
||||
for k, v := range msg.Header {
|
||||
h.w.Header().Set(k, v)
|
||||
}
|
||||
|
||||
// write request
|
||||
_, err := h.w.Write(msg.Body)
|
||||
|
||||
// flush the trailers
|
||||
h.w.(http.Flusher).Flush()
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
maddr "go-micro.dev/v6/internal/util/addr"
|
||||
mnet "go-micro.dev/v6/internal/util/net"
|
||||
mls "go-micro.dev/v6/internal/util/tls"
|
||||
"go-micro.dev/v6/logger"
|
||||
)
|
||||
|
||||
type httpTransport struct {
|
||||
opts Options
|
||||
}
|
||||
|
||||
func NewHTTPTransport(opts ...Option) *httpTransport {
|
||||
options := Options{
|
||||
BuffSizeH2: DefaultBufSizeH2,
|
||||
Logger: logger.DefaultLogger,
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return &httpTransport{opts: options}
|
||||
}
|
||||
|
||||
func (h *httpTransport) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&h.opts)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransport) Dial(addr string, opts ...DialOption) (Client, error) {
|
||||
dopts := DialOptions{
|
||||
Timeout: DefaultDialTimeout,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&dopts)
|
||||
}
|
||||
|
||||
var (
|
||||
conn net.Conn
|
||||
err error
|
||||
)
|
||||
|
||||
if h.opts.Secure || h.opts.TLSConfig != nil {
|
||||
config := h.opts.TLSConfig
|
||||
if config == nil {
|
||||
config = &tls.Config{
|
||||
InsecureSkipVerify: dopts.InsecureSkipVerify,
|
||||
}
|
||||
}
|
||||
|
||||
config.NextProtos = []string{"http/1.1"}
|
||||
|
||||
conn, err = newConn(func(addr string) (net.Conn, error) {
|
||||
return tls.DialWithDialer(&net.Dialer{Timeout: dopts.Timeout}, "tcp", addr, config)
|
||||
})(addr)
|
||||
} else {
|
||||
conn, err = newConn(func(addr string) (net.Conn, error) {
|
||||
return net.DialTimeout("tcp", addr, dopts.Timeout)
|
||||
})(addr)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &httpTransportClient{
|
||||
ht: h,
|
||||
addr: addr,
|
||||
conn: conn,
|
||||
buff: bufio.NewReader(conn),
|
||||
dialOpts: dopts,
|
||||
req: make(chan *http.Request, 100),
|
||||
local: conn.LocalAddr().String(),
|
||||
remote: conn.RemoteAddr().String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *httpTransport) Listen(addr string, opts ...ListenOption) (Listener, error) {
|
||||
var options ListenOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
var (
|
||||
list net.Listener
|
||||
err error
|
||||
)
|
||||
|
||||
switch listener := getNetListener(&options); {
|
||||
// Extracted listener from context
|
||||
case listener != nil:
|
||||
getList := func(addr string) (net.Listener, error) {
|
||||
return listener, nil
|
||||
}
|
||||
|
||||
list, err = mnet.Listen(addr, getList)
|
||||
|
||||
// Needs to create self signed certificate
|
||||
case h.opts.Secure || h.opts.TLSConfig != nil:
|
||||
config := h.opts.TLSConfig
|
||||
|
||||
getList := func(addr string) (net.Listener, error) {
|
||||
if config != nil {
|
||||
return tls.Listen("tcp", addr, config)
|
||||
}
|
||||
|
||||
hosts := []string{addr}
|
||||
|
||||
// check if its a valid host:port
|
||||
if host, _, err := net.SplitHostPort(addr); err == nil {
|
||||
if len(host) == 0 {
|
||||
hosts = maddr.IPs()
|
||||
} else {
|
||||
hosts = []string{host}
|
||||
}
|
||||
}
|
||||
|
||||
// generate a certificate
|
||||
cert, err := mls.Certificate(hosts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
config = &tls.Config{
|
||||
Certificates: []tls.Certificate{cert},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
|
||||
return tls.Listen("tcp", addr, config)
|
||||
}
|
||||
|
||||
list, err = mnet.Listen(addr, getList)
|
||||
|
||||
// Create new basic net listener
|
||||
default:
|
||||
getList := func(addr string) (net.Listener, error) {
|
||||
return net.Listen("tcp", addr)
|
||||
}
|
||||
|
||||
list, err = mnet.Listen(addr, getList)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &httpTransportListener{
|
||||
ht: h,
|
||||
listener: list,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *httpTransport) Options() Options {
|
||||
return h.opts
|
||||
}
|
||||
|
||||
func (h *httpTransport) String() string {
|
||||
return "http"
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHTTPTransportCommunication(t *testing.T) {
|
||||
tr := NewHTTPTransport()
|
||||
|
||||
l, err := tr.Listen("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected listen err: %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
fn := func(sock Socket) {
|
||||
defer sock.Close()
|
||||
|
||||
for {
|
||||
var m Message
|
||||
if err := sock.Recv(&m); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := sock.Send(&m); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
done := make(chan bool)
|
||||
|
||||
go func() {
|
||||
if err := l.Accept(fn); err != nil {
|
||||
select {
|
||||
case <-done:
|
||||
default:
|
||||
t.Errorf("Unexpected accept err: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := tr.Dial(l.Addr())
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected dial err: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
m := Message{
|
||||
Header: map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
Body: []byte(`{"message": "Hello World"}`),
|
||||
}
|
||||
|
||||
if err := c.Send(&m); err != nil {
|
||||
t.Errorf("Unexpected send err: %v", err)
|
||||
}
|
||||
|
||||
var rm Message
|
||||
|
||||
if err := c.Recv(&rm); err != nil {
|
||||
t.Errorf("Unexpected recv err: %v", err)
|
||||
}
|
||||
|
||||
if string(rm.Body) != string(m.Body) {
|
||||
t.Errorf("Expected %v, got %v", m.Body, rm.Body)
|
||||
}
|
||||
|
||||
close(done)
|
||||
}
|
||||
|
||||
func TestHTTPTransportError(t *testing.T) {
|
||||
tr := NewHTTPTransport()
|
||||
|
||||
l, err := tr.Listen("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected listen err: %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
fn := func(sock Socket) {
|
||||
defer sock.Close()
|
||||
|
||||
for {
|
||||
var m Message
|
||||
if err := sock.Recv(&m); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
sock.(*httpTransportSocket).error(&Message{
|
||||
Body: []byte(`an error occurred`),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
done := make(chan bool)
|
||||
|
||||
go func() {
|
||||
if err := l.Accept(fn); err != nil {
|
||||
select {
|
||||
case <-done:
|
||||
default:
|
||||
t.Errorf("Unexpected accept err: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := tr.Dial(l.Addr())
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected dial err: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
m := Message{
|
||||
Header: map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
Body: []byte(`{"message": "Hello World"}`),
|
||||
}
|
||||
|
||||
if err := c.Send(&m); err != nil {
|
||||
t.Errorf("Unexpected send err: %v", err)
|
||||
}
|
||||
|
||||
var rm Message
|
||||
|
||||
err = c.Recv(&rm)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error but got nil")
|
||||
}
|
||||
|
||||
if err.Error() != "500 Internal Server Error: an error occurred" {
|
||||
t.Fatalf("Did not receive expected error, got: %v", err)
|
||||
}
|
||||
|
||||
close(done)
|
||||
}
|
||||
|
||||
func TestHTTPTransportTimeout(t *testing.T) {
|
||||
tr := NewHTTPTransport(Timeout(time.Millisecond * 100))
|
||||
|
||||
l, err := tr.Listen("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected listen err: %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
done := make(chan bool)
|
||||
|
||||
fn := func(sock Socket) {
|
||||
defer func() {
|
||||
sock.Close()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
t.Errorf("deadline not executed")
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
var m Message
|
||||
|
||||
if err := sock.Recv(&m); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
if err := l.Accept(fn); err != nil {
|
||||
select {
|
||||
case <-done:
|
||||
default:
|
||||
t.Errorf("Unexpected accept err: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := tr.Dial(l.Addr())
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected dial err: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
m := Message{
|
||||
Header: map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
Body: []byte(`{"message": "Hello World"}`),
|
||||
}
|
||||
|
||||
if err := c.Send(&m); err != nil {
|
||||
t.Errorf("Unexpected send err: %v", err)
|
||||
}
|
||||
|
||||
<-done
|
||||
}
|
||||
|
||||
func TestHTTPTransportCloseWhenRecv(t *testing.T) {
|
||||
tr := NewHTTPTransport()
|
||||
|
||||
l, err := tr.Listen("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected listen err: %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
fn := func(sock Socket) {
|
||||
defer sock.Close()
|
||||
|
||||
for {
|
||||
var m Message
|
||||
if err := sock.Recv(&m); err != nil {
|
||||
return
|
||||
}
|
||||
if err := sock.Send(&m); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
done := make(chan bool)
|
||||
|
||||
go func() {
|
||||
if err := l.Accept(fn); err != nil {
|
||||
select {
|
||||
case <-done:
|
||||
default:
|
||||
t.Errorf("Unexpected accept err: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := tr.Dial(l.Addr())
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected dial err: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
m := Message{
|
||||
Header: map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
Body: []byte(`{"message": "Hello World"}`),
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
var rm Message
|
||||
|
||||
if err := c.Recv(&rm); err != nil {
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
for i := 1; i < 3; i++ {
|
||||
if err := c.Send(&m); err != nil {
|
||||
t.Errorf("Unexpected send err: %v", err)
|
||||
}
|
||||
}
|
||||
close(done)
|
||||
|
||||
c.Close()
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestHTTPTransportMultipleSendWhenRecv(t *testing.T) {
|
||||
tr := NewHTTPTransport()
|
||||
|
||||
l, err := tr.Listen("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected listen err: %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
readyToSend := make(chan struct{})
|
||||
m := Message{
|
||||
Header: map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
Body: []byte(`{"message": "Hello World"}`),
|
||||
}
|
||||
|
||||
var wgSend sync.WaitGroup
|
||||
fn := func(sock Socket) {
|
||||
defer sock.Close()
|
||||
|
||||
for {
|
||||
var mr Message
|
||||
if err := sock.Recv(&mr); err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer wgSend.Done()
|
||||
<-readyToSend
|
||||
if err := sock.Send(&m); err != nil {
|
||||
return
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
done := make(chan bool)
|
||||
|
||||
go func() {
|
||||
if err := l.Accept(fn); err != nil {
|
||||
select {
|
||||
case <-done:
|
||||
default:
|
||||
t.Errorf("Unexpected accept err: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := tr.Dial(l.Addr(), WithStream())
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected dial err: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
readyForRecv := make(chan struct{})
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
close(readyForRecv)
|
||||
for {
|
||||
var rm Message
|
||||
if err := c.Recv(&rm); err != nil {
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
wgSend.Add(3)
|
||||
<-readyForRecv
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := c.Send(&m); err != nil {
|
||||
t.Errorf("Unexpected send err: %v", err)
|
||||
}
|
||||
}
|
||||
close(readyToSend)
|
||||
wgSend.Wait()
|
||||
close(done)
|
||||
|
||||
c.Close()
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestHttpTransportListenerNetListener(t *testing.T) {
|
||||
address := "127.0.0.1:0"
|
||||
|
||||
customListener, err := net.Listen("tcp", address)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
tr := NewHTTPTransport(Timeout(time.Millisecond * 100))
|
||||
|
||||
// injection
|
||||
l, err := tr.Listen(address, NetListener(customListener))
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected listen err: %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
done := make(chan bool)
|
||||
|
||||
fn := func(sock Socket) {
|
||||
defer func() {
|
||||
sock.Close()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
t.Errorf("deadline not executed")
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
var m Message
|
||||
|
||||
if err := sock.Recv(&m); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
if err := l.Accept(fn); err != nil {
|
||||
select {
|
||||
case <-done:
|
||||
default:
|
||||
t.Errorf("Unexpected accept err: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := tr.Dial(l.Addr())
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected dial err: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
m := Message{
|
||||
Header: map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
Body: []byte(`{"message": "Hello World"}`),
|
||||
}
|
||||
|
||||
if err := c.Send(&m); err != nil {
|
||||
t.Errorf("Unexpected send err: %v", err)
|
||||
}
|
||||
|
||||
<-done
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
maddr "go-micro.dev/v6/internal/util/addr"
|
||||
mnet "go-micro.dev/v6/internal/util/net"
|
||||
)
|
||||
|
||||
type memorySocket struct {
|
||||
ctx context.Context
|
||||
// Client receiver of io.Pipe with gob
|
||||
crecv *gob.Decoder
|
||||
// Client sender of the io.Pipe with gob
|
||||
csend *gob.Encoder
|
||||
// Server receiver of the io.Pip with gob
|
||||
srecv *gob.Decoder
|
||||
// Server sender of the io.Pip with gob
|
||||
ssend *gob.Encoder
|
||||
// sock exit
|
||||
exit chan bool
|
||||
// listener exit
|
||||
lexit chan bool
|
||||
|
||||
local string
|
||||
remote string
|
||||
|
||||
// for send/recv Timeout
|
||||
timeout time.Duration
|
||||
// True server mode, False client mode
|
||||
server bool
|
||||
}
|
||||
|
||||
type memoryClient struct {
|
||||
*memorySocket
|
||||
opts DialOptions
|
||||
}
|
||||
|
||||
type memoryListener struct {
|
||||
lopts ListenOptions
|
||||
ctx context.Context
|
||||
exit chan bool
|
||||
conn chan *memorySocket
|
||||
topts Options
|
||||
addr string
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type memoryTransport struct {
|
||||
listeners map[string]*memoryListener
|
||||
opts Options
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Recv(m *Message) error {
|
||||
ctx := ms.ctx
|
||||
if ms.timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ms.ctx, ms.timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ms.exit:
|
||||
// connection closed
|
||||
return io.EOF
|
||||
case <-ms.lexit:
|
||||
// Server connection closed
|
||||
return io.EOF
|
||||
default:
|
||||
if ms.server {
|
||||
if err := ms.srecv.Decode(m); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := ms.crecv.Decode(m); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Local() string {
|
||||
return ms.local
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Remote() string {
|
||||
return ms.remote
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Send(m *Message) error {
|
||||
ctx := ms.ctx
|
||||
if ms.timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ms.ctx, ms.timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ms.exit:
|
||||
// connection closed
|
||||
return io.EOF
|
||||
case <-ms.lexit:
|
||||
// Server connection closed
|
||||
return io.EOF
|
||||
default:
|
||||
if ms.server {
|
||||
if err := ms.ssend.Encode(m); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := ms.csend.Encode(m); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Close() error {
|
||||
select {
|
||||
case <-ms.exit:
|
||||
return nil
|
||||
default:
|
||||
close(ms.exit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryListener) Addr() string {
|
||||
return m.addr
|
||||
}
|
||||
|
||||
func (m *memoryListener) Close() error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
select {
|
||||
case <-m.exit:
|
||||
return nil
|
||||
default:
|
||||
close(m.exit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryListener) Accept(fn func(Socket)) error {
|
||||
for {
|
||||
select {
|
||||
case <-m.exit:
|
||||
return nil
|
||||
case c := <-m.conn:
|
||||
go fn(&memorySocket{
|
||||
server: true,
|
||||
lexit: c.lexit,
|
||||
exit: c.exit,
|
||||
ssend: c.ssend,
|
||||
srecv: c.srecv,
|
||||
local: c.Remote(),
|
||||
remote: c.Local(),
|
||||
timeout: m.topts.Timeout,
|
||||
ctx: m.topts.Context,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Dial(addr string, opts ...DialOption) (Client, error) {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
listener, ok := m.listeners[addr]
|
||||
if !ok {
|
||||
return nil, errors.New("could not dial " + addr)
|
||||
}
|
||||
|
||||
var options DialOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
creader, swriter := io.Pipe()
|
||||
sreader, cwriter := io.Pipe()
|
||||
|
||||
client := &memoryClient{
|
||||
&memorySocket{
|
||||
server: false,
|
||||
csend: gob.NewEncoder(cwriter),
|
||||
crecv: gob.NewDecoder(creader),
|
||||
ssend: gob.NewEncoder(swriter),
|
||||
srecv: gob.NewDecoder(sreader), exit: make(chan bool),
|
||||
lexit: listener.exit,
|
||||
local: addr,
|
||||
remote: addr,
|
||||
timeout: m.opts.Timeout,
|
||||
ctx: m.opts.Context,
|
||||
},
|
||||
options,
|
||||
}
|
||||
|
||||
// pseudo connect
|
||||
select {
|
||||
case <-listener.exit:
|
||||
return nil, errors.New("connection error")
|
||||
case listener.conn <- client.memorySocket:
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Listen(addr string, opts ...ListenOption) (Listener, error) {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
var options ListenOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
addr, err = maddr.Extract(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// if zero port then randomly assign one
|
||||
if len(port) > 0 && port == "0" {
|
||||
i := rand.Intn(20000)
|
||||
port = fmt.Sprintf("%d", 10000+i)
|
||||
}
|
||||
|
||||
// set addr with port
|
||||
addr = mnet.HostPort(addr, port)
|
||||
|
||||
if _, ok := m.listeners[addr]; ok {
|
||||
return nil, errors.New("already listening on " + addr)
|
||||
}
|
||||
|
||||
listener := &memoryListener{
|
||||
lopts: options,
|
||||
topts: m.opts,
|
||||
addr: addr,
|
||||
conn: make(chan *memorySocket),
|
||||
exit: make(chan bool),
|
||||
ctx: m.opts.Context,
|
||||
}
|
||||
|
||||
m.listeners[addr] = listener
|
||||
|
||||
return listener, nil
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&m.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Options() Options {
|
||||
return m.opts
|
||||
}
|
||||
|
||||
func (m *memoryTransport) String() string {
|
||||
return "memory"
|
||||
}
|
||||
|
||||
func NewMemoryTransport(opts ...Option) Transport {
|
||||
var options Options
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
if options.Context == nil {
|
||||
options.Context = context.Background()
|
||||
}
|
||||
|
||||
return &memoryTransport{
|
||||
opts: options,
|
||||
listeners: make(map[string]*memoryListener),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMemoryTransport(t *testing.T) {
|
||||
tr := NewMemoryTransport()
|
||||
|
||||
// bind / listen
|
||||
l, err := tr.Listen("127.0.0.1:8080")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error listening %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
// accept
|
||||
go func() {
|
||||
if err := l.Accept(func(sock Socket) {
|
||||
for {
|
||||
var m Message
|
||||
if err := sock.Recv(&m); err != nil {
|
||||
return
|
||||
}
|
||||
if len(os.Getenv("IN_TRAVIS_CI")) == 0 {
|
||||
t.Logf("Server Received %s", string(m.Body))
|
||||
}
|
||||
if err := sock.Send(&Message{
|
||||
Body: []byte(`pong`),
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
t.Errorf("Unexpected error accepting %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// dial
|
||||
c, err := tr.Dial("127.0.0.1:8080")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error dialing %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
// send <=> receive
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := c.Send(&Message{
|
||||
Body: []byte(`ping`),
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
var m Message
|
||||
if err := c.Recv(&m); err != nil {
|
||||
return
|
||||
}
|
||||
if len(os.Getenv("IN_TRAVIS_CI")) == 0 {
|
||||
t.Logf("Client Received %s", string(m.Body))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListener(t *testing.T) {
|
||||
tr := NewMemoryTransport()
|
||||
|
||||
// bind / listen on random port
|
||||
l, err := tr.Listen(":0")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error listening %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
// try again
|
||||
l2, err := tr.Listen(":0")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error listening %v", err)
|
||||
}
|
||||
defer l2.Close()
|
||||
|
||||
// now make sure it still fails
|
||||
l3, err := tr.Listen(":8080")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error listening %v", err)
|
||||
}
|
||||
defer l3.Close()
|
||||
|
||||
if _, err := tr.Listen(":8080"); err == nil {
|
||||
t.Fatal("Expected error binding to :8080 got nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
// Package nats provides a NATS transport
|
||||
package nats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
"go-micro.dev/v6/codec/json"
|
||||
"go-micro.dev/v6/server"
|
||||
"go-micro.dev/v6/transport"
|
||||
)
|
||||
|
||||
type ntport struct {
|
||||
addrs []string
|
||||
opts transport.Options
|
||||
nopts nats.Options
|
||||
pool *connectionPool // connection pool for clients
|
||||
poolSize int
|
||||
poolIdleTimeout time.Duration
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
type ntportClient struct {
|
||||
conn *nats.Conn
|
||||
pooledConn *pooledConnection // reference to pooled connection if using pool
|
||||
pool *connectionPool // reference to pool to return connection on close
|
||||
addr string
|
||||
id string
|
||||
local string
|
||||
remote string
|
||||
sub *nats.Subscription
|
||||
opts transport.Options
|
||||
}
|
||||
|
||||
type ntportSocket struct {
|
||||
conn *nats.Conn
|
||||
m *nats.Msg
|
||||
r chan *nats.Msg
|
||||
|
||||
close chan bool
|
||||
|
||||
sync.Mutex
|
||||
bl []*nats.Msg
|
||||
|
||||
opts transport.Options
|
||||
local string
|
||||
remote string
|
||||
}
|
||||
|
||||
type ntportListener struct {
|
||||
conn *nats.Conn
|
||||
addr string
|
||||
exit chan bool
|
||||
|
||||
sync.RWMutex
|
||||
so map[string]*ntportSocket
|
||||
|
||||
opts transport.Options
|
||||
}
|
||||
|
||||
var (
|
||||
DefaultTimeout = time.Minute
|
||||
)
|
||||
|
||||
func configure(n *ntport, opts ...transport.Option) {
|
||||
for _, o := range opts {
|
||||
o(&n.opts)
|
||||
}
|
||||
|
||||
natsOptions := nats.GetDefaultOptions()
|
||||
if no, ok := n.opts.Context.Value(optionsKey{}).(nats.Options); ok {
|
||||
natsOptions = no
|
||||
}
|
||||
|
||||
// Set pool size (default is 1 - no pooling)
|
||||
n.poolSize = 1
|
||||
if poolSize, ok := n.opts.Context.Value(poolSizeKey{}).(int); ok && poolSize > 0 {
|
||||
n.poolSize = poolSize
|
||||
}
|
||||
|
||||
// Set pool idle timeout (default is 5 minutes)
|
||||
n.poolIdleTimeout = 5 * time.Minute
|
||||
if idleTimeout, ok := n.opts.Context.Value(poolIdleTimeoutKey{}).(time.Duration); ok {
|
||||
n.poolIdleTimeout = idleTimeout
|
||||
}
|
||||
|
||||
// transport.Options have higher priority than nats.Options
|
||||
// only if Addrs, Secure or TLSConfig were not set through a transport.Option
|
||||
// we read them from nats.Option
|
||||
if len(n.opts.Addrs) == 0 {
|
||||
n.opts.Addrs = natsOptions.Servers
|
||||
}
|
||||
|
||||
if !n.opts.Secure {
|
||||
n.opts.Secure = natsOptions.Secure
|
||||
}
|
||||
|
||||
if n.opts.TLSConfig == nil {
|
||||
n.opts.TLSConfig = natsOptions.TLSConfig
|
||||
}
|
||||
|
||||
// check & add nats:// prefix (this makes also sure that the addresses
|
||||
// stored in natsRegistry.addrs and options.Addrs are identical)
|
||||
n.opts.Addrs = setAddrs(n.opts.Addrs)
|
||||
n.nopts = natsOptions
|
||||
n.addrs = n.opts.Addrs
|
||||
|
||||
// Initialize connection pool if size > 1
|
||||
if n.poolSize > 1 && n.pool == nil {
|
||||
factory := func() (*nats.Conn, error) {
|
||||
opts := n.nopts
|
||||
opts.Servers = n.addrs
|
||||
opts.Secure = n.opts.Secure
|
||||
opts.TLSConfig = n.opts.TLSConfig
|
||||
|
||||
// secure might not be set
|
||||
if n.opts.TLSConfig != nil {
|
||||
opts.Secure = true
|
||||
}
|
||||
|
||||
return opts.Connect()
|
||||
}
|
||||
|
||||
pool, err := newConnectionPool(n.poolSize, factory)
|
||||
if err == nil {
|
||||
if n.poolIdleTimeout > 0 {
|
||||
pool.idleTimeout = n.poolIdleTimeout
|
||||
}
|
||||
n.pool = pool
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setAddrs(addrs []string) []string {
|
||||
cAddrs := make([]string, 0, len(addrs))
|
||||
for _, addr := range addrs {
|
||||
if len(addr) == 0 {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(addr, "nats://") {
|
||||
addr = "nats://" + addr
|
||||
}
|
||||
cAddrs = append(cAddrs, addr)
|
||||
}
|
||||
if len(cAddrs) == 0 {
|
||||
cAddrs = []string{nats.DefaultURL}
|
||||
}
|
||||
return cAddrs
|
||||
}
|
||||
|
||||
func (n *ntportClient) Local() string {
|
||||
return n.local
|
||||
}
|
||||
|
||||
func (n *ntportClient) Remote() string {
|
||||
return n.remote
|
||||
}
|
||||
|
||||
func (n *ntportClient) Send(m *transport.Message) error {
|
||||
b, err := n.opts.Codec.Marshal(m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// no deadline
|
||||
if n.opts.Timeout == time.Duration(0) {
|
||||
return n.conn.PublishRequest(n.addr, n.id, b)
|
||||
}
|
||||
|
||||
// use the deadline
|
||||
ch := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
ch <- n.conn.PublishRequest(n.addr, n.id, b)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-ch:
|
||||
return err
|
||||
case <-time.After(n.opts.Timeout):
|
||||
return errors.New("deadline exceeded")
|
||||
}
|
||||
}
|
||||
|
||||
func (n *ntportClient) Recv(m *transport.Message) error {
|
||||
timeout := time.Second * 10
|
||||
if n.opts.Timeout > time.Duration(0) {
|
||||
timeout = n.opts.Timeout
|
||||
}
|
||||
|
||||
rsp, err := n.sub.NextMsg(timeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var mr transport.Message
|
||||
if err := n.opts.Codec.Unmarshal(rsp.Data, &mr); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*m = mr
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *ntportClient) Close() error {
|
||||
_ = n.sub.Unsubscribe()
|
||||
|
||||
// If using a pooled connection, return it to the pool
|
||||
if n.pool != nil && n.pooledConn != nil {
|
||||
return n.pool.Put(n.pooledConn)
|
||||
}
|
||||
|
||||
// Otherwise, close the connection directly
|
||||
n.conn.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *ntportSocket) Local() string {
|
||||
return n.local
|
||||
}
|
||||
|
||||
func (n *ntportSocket) Remote() string {
|
||||
return n.remote
|
||||
}
|
||||
|
||||
func (n *ntportSocket) Recv(m *transport.Message) error {
|
||||
if m == nil {
|
||||
return errors.New("message passed in is nil")
|
||||
}
|
||||
|
||||
var r *nats.Msg
|
||||
var ok bool
|
||||
|
||||
// if there's a deadline we use it
|
||||
if n.opts.Timeout > time.Duration(0) {
|
||||
select {
|
||||
case r, ok = <-n.r:
|
||||
case <-time.After(n.opts.Timeout):
|
||||
return errors.New("deadline exceeded")
|
||||
}
|
||||
} else {
|
||||
r, ok = <-n.r
|
||||
}
|
||||
|
||||
if !ok {
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
n.Lock()
|
||||
if len(n.bl) > 0 {
|
||||
select {
|
||||
case n.r <- n.bl[0]:
|
||||
n.bl = n.bl[1:]
|
||||
default:
|
||||
}
|
||||
}
|
||||
n.Unlock()
|
||||
|
||||
if err := n.opts.Codec.Unmarshal(r.Data, m); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *ntportSocket) Send(m *transport.Message) error {
|
||||
b, err := n.opts.Codec.Marshal(m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// no deadline
|
||||
if n.opts.Timeout == time.Duration(0) {
|
||||
return n.conn.Publish(n.m.Reply, b)
|
||||
}
|
||||
|
||||
// use the deadline
|
||||
ch := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
ch <- n.conn.Publish(n.m.Reply, b)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-ch:
|
||||
return err
|
||||
case <-time.After(n.opts.Timeout):
|
||||
return errors.New("deadline exceeded")
|
||||
}
|
||||
}
|
||||
|
||||
func (n *ntportSocket) Close() error {
|
||||
select {
|
||||
case <-n.close:
|
||||
return nil
|
||||
default:
|
||||
close(n.close)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *ntportListener) Addr() string {
|
||||
return n.addr
|
||||
}
|
||||
|
||||
func (n *ntportListener) Close() error {
|
||||
n.exit <- true
|
||||
n.conn.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *ntportListener) Accept(fn func(transport.Socket)) error {
|
||||
s, err := n.conn.SubscribeSync(n.addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
go func() {
|
||||
<-n.exit
|
||||
_ = s.Unsubscribe()
|
||||
}()
|
||||
|
||||
for {
|
||||
m, err := s.NextMsg(time.Minute)
|
||||
if err != nil && err == nats.ErrTimeout {
|
||||
continue
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
n.RLock()
|
||||
sock, ok := n.so[m.Reply]
|
||||
n.RUnlock()
|
||||
|
||||
if !ok {
|
||||
sock = &ntportSocket{
|
||||
conn: n.conn,
|
||||
m: m,
|
||||
r: make(chan *nats.Msg, 1),
|
||||
close: make(chan bool),
|
||||
opts: n.opts,
|
||||
local: n.Addr(),
|
||||
remote: m.Reply,
|
||||
}
|
||||
n.Lock()
|
||||
n.so[m.Reply] = sock
|
||||
n.Unlock()
|
||||
|
||||
go func() {
|
||||
// TODO: think of a better error response strategy
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
sock.Close()
|
||||
}
|
||||
}()
|
||||
fn(sock)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
<-sock.close
|
||||
n.Lock()
|
||||
delete(n.so, sock.m.Reply)
|
||||
n.Unlock()
|
||||
}()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-sock.close:
|
||||
continue
|
||||
default:
|
||||
}
|
||||
|
||||
sock.Lock()
|
||||
sock.bl = append(sock.bl, m)
|
||||
select {
|
||||
case sock.r <- sock.bl[0]:
|
||||
sock.bl = sock.bl[1:]
|
||||
default:
|
||||
}
|
||||
sock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (n *ntport) Dial(addr string, dialOpts ...transport.DialOption) (transport.Client, error) {
|
||||
dopts := transport.DialOptions{
|
||||
Timeout: transport.DefaultDialTimeout,
|
||||
}
|
||||
|
||||
for _, o := range dialOpts {
|
||||
o(&dopts)
|
||||
}
|
||||
|
||||
var c *nats.Conn
|
||||
var pooledConn *pooledConnection
|
||||
var err error
|
||||
|
||||
// Use connection pool if available
|
||||
n.mu.RLock()
|
||||
hasPool := n.pool != nil
|
||||
n.mu.RUnlock()
|
||||
|
||||
if hasPool {
|
||||
pooledConn, err = n.pool.Get()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c = pooledConn.Conn()
|
||||
if c == nil {
|
||||
_ = n.pool.Put(pooledConn)
|
||||
return nil, errors.New("invalid connection from pool")
|
||||
}
|
||||
} else {
|
||||
// Create a new connection (original behavior)
|
||||
opts := n.nopts
|
||||
opts.Servers = n.addrs
|
||||
opts.Secure = n.opts.Secure
|
||||
opts.TLSConfig = n.opts.TLSConfig
|
||||
opts.Timeout = dopts.Timeout
|
||||
|
||||
// secure might not be set
|
||||
if n.opts.TLSConfig != nil {
|
||||
opts.Secure = true
|
||||
}
|
||||
|
||||
c, err = opts.Connect()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
id := nats.NewInbox()
|
||||
sub, err := c.SubscribeSync(id)
|
||||
if err != nil {
|
||||
if pooledConn != nil {
|
||||
_ = n.pool.Put(pooledConn)
|
||||
} else {
|
||||
c.Close()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client := &ntportClient{
|
||||
conn: c,
|
||||
pooledConn: pooledConn,
|
||||
pool: n.pool,
|
||||
addr: addr,
|
||||
id: id,
|
||||
sub: sub,
|
||||
opts: n.opts,
|
||||
local: id,
|
||||
remote: addr,
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (n *ntport) Listen(addr string, listenOpts ...transport.ListenOption) (transport.Listener, error) {
|
||||
opts := n.nopts
|
||||
opts.Servers = n.addrs
|
||||
opts.Secure = n.opts.Secure
|
||||
opts.TLSConfig = n.opts.TLSConfig
|
||||
|
||||
// secure might not be set
|
||||
if n.opts.TLSConfig != nil {
|
||||
opts.Secure = true
|
||||
}
|
||||
|
||||
c, err := opts.Connect()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// in case address has not been specifically set, create a new nats.Inbox()
|
||||
if addr == server.DefaultAddress {
|
||||
addr = nats.NewInbox()
|
||||
}
|
||||
|
||||
// make sure addr subject is not empty
|
||||
if len(addr) == 0 {
|
||||
return nil, errors.New("addr (nats subject) must not be empty")
|
||||
}
|
||||
|
||||
// since NATS implements a text based protocol, no space characters are
|
||||
// admitted in the addr (subject name)
|
||||
if strings.Contains(addr, " ") {
|
||||
return nil, errors.New("addr (nats subject) must not contain space characters")
|
||||
}
|
||||
|
||||
return &ntportListener{
|
||||
addr: addr,
|
||||
conn: c,
|
||||
exit: make(chan bool, 1),
|
||||
so: make(map[string]*ntportSocket),
|
||||
opts: n.opts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (n *ntport) Init(opts ...transport.Option) error {
|
||||
configure(n, opts...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *ntport) Options() transport.Options {
|
||||
return n.opts
|
||||
}
|
||||
|
||||
func (n *ntport) String() string {
|
||||
return "nats"
|
||||
}
|
||||
|
||||
func NewTransport(opts ...transport.Option) transport.Transport {
|
||||
options := transport.Options{
|
||||
// Default codec
|
||||
Codec: json.Marshaler{},
|
||||
Timeout: DefaultTimeout,
|
||||
Context: context.Background(),
|
||||
}
|
||||
|
||||
nt := &ntport{
|
||||
opts: options,
|
||||
}
|
||||
configure(nt, opts...)
|
||||
return nt
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"log"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
"go-micro.dev/v6/server"
|
||||
"go-micro.dev/v6/transport"
|
||||
)
|
||||
|
||||
var addrTestCases = []struct {
|
||||
name string
|
||||
description string
|
||||
addrs map[string]string // expected address : set address
|
||||
}{
|
||||
{
|
||||
"transportOption",
|
||||
"set broker addresses through a transport.Option",
|
||||
map[string]string{
|
||||
"nats://192.168.10.1:5222": "192.168.10.1:5222",
|
||||
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
|
||||
},
|
||||
{
|
||||
"natsOption",
|
||||
"set broker addresses through the nats.Option",
|
||||
map[string]string{
|
||||
"nats://192.168.10.1:5222": "192.168.10.1:5222",
|
||||
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
|
||||
},
|
||||
{
|
||||
"default",
|
||||
"check if default Address is set correctly",
|
||||
map[string]string{
|
||||
"nats://127.0.0.1:4222": ""},
|
||||
},
|
||||
}
|
||||
|
||||
// This test will check if options (here nats addresses) set through either
|
||||
// transport.Option or via nats.Option are successfully set.
|
||||
func TestInitAddrs(t *testing.T) {
|
||||
for _, tc := range addrTestCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var tr transport.Transport
|
||||
var addrs []string
|
||||
|
||||
for _, addr := range tc.addrs {
|
||||
addrs = append(addrs, addr)
|
||||
}
|
||||
|
||||
switch tc.name {
|
||||
case "transportOption":
|
||||
// we know that there are just two addrs in the dict
|
||||
tr = NewTransport(transport.Addrs(addrs[0], addrs[1]))
|
||||
case "natsOption":
|
||||
nopts := nats.GetDefaultOptions()
|
||||
nopts.Servers = addrs
|
||||
tr = NewTransport(Options(nopts))
|
||||
case "default":
|
||||
tr = NewTransport()
|
||||
}
|
||||
|
||||
ntport, ok := tr.(*ntport)
|
||||
if !ok {
|
||||
t.Fatal("Expected broker to be of types *nbroker")
|
||||
}
|
||||
// check if the same amount of addrs we set has actually been set
|
||||
if len(ntport.addrs) != len(tc.addrs) {
|
||||
t.Errorf("Expected Addr count = %d, Actual Addr count = %d",
|
||||
len(ntport.addrs), len(tc.addrs))
|
||||
}
|
||||
|
||||
for _, addr := range ntport.addrs {
|
||||
_, ok := tc.addrs[addr]
|
||||
if !ok {
|
||||
t.Errorf("Expected '%s' has not been set", addr)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var listenAddrTestCases = []struct {
|
||||
name string
|
||||
address string
|
||||
mustPass bool
|
||||
}{
|
||||
{"default address", server.DefaultAddress, true},
|
||||
{"nats.NewInbox", nats.NewInbox(), true},
|
||||
{"correct service name", "micro.test.myservice", true},
|
||||
{"several space chars", "micro.test.my new service", false},
|
||||
{"one space char", "micro.test.my oldservice", false},
|
||||
{"empty", "", false},
|
||||
}
|
||||
|
||||
func TestListenAddr(t *testing.T) {
|
||||
natsURL := os.Getenv("NATS_URL")
|
||||
if natsURL == "" {
|
||||
log.Println("NATS_URL is undefined - skipping tests")
|
||||
return
|
||||
}
|
||||
|
||||
for _, tc := range listenAddrTestCases {
|
||||
t.Run(tc.address, func(t *testing.T) {
|
||||
nOpts := nats.GetDefaultOptions()
|
||||
nOpts.Servers = []string{natsURL}
|
||||
nTport := ntport{
|
||||
nopts: nOpts,
|
||||
}
|
||||
trListener, err := nTport.Listen(tc.address)
|
||||
if err != nil {
|
||||
if tc.mustPass {
|
||||
t.Fatalf("%s (%s) is not allowed", tc.name, tc.address)
|
||||
}
|
||||
// correctly failed
|
||||
return
|
||||
}
|
||||
if trListener.Addr() != tc.address {
|
||||
// special case - since an always string will be returned
|
||||
if tc.name == "default address" {
|
||||
if strings.Contains(trListener.Addr(), "_INBOX.") {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Errorf("expected address %s but got %s", tc.address, trListener.Addr())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
"go-micro.dev/v6/transport"
|
||||
)
|
||||
|
||||
type optionsKey struct{}
|
||||
type poolSizeKey struct{}
|
||||
type poolIdleTimeoutKey struct{}
|
||||
|
||||
// Options allow to inject a nats.Options struct for configuring
|
||||
// the nats connection.
|
||||
func Options(nopts nats.Options) transport.Option {
|
||||
return func(o *transport.Options) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
o.Context = context.WithValue(o.Context, optionsKey{}, nopts)
|
||||
}
|
||||
}
|
||||
|
||||
// PoolSize sets the size of the connection pool.
|
||||
// If set to a value > 1, the transport will use a connection pool.
|
||||
// Default is 1 (no pooling).
|
||||
func PoolSize(size int) transport.Option {
|
||||
return func(o *transport.Options) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
o.Context = context.WithValue(o.Context, poolSizeKey{}, size)
|
||||
}
|
||||
}
|
||||
|
||||
// PoolIdleTimeout sets the timeout for idle connections in the pool.
|
||||
// Connections idle for longer than this duration will be closed.
|
||||
// Default is 5 minutes. Set to 0 to disable idle timeout.
|
||||
func PoolIdleTimeout(timeout time.Duration) transport.Option {
|
||||
return func(o *transport.Options) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
o.Context = context.WithValue(o.Context, poolIdleTimeoutKey{}, timeout)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
natsp "github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrPoolExhausted is returned when no connections are available in the pool
|
||||
ErrPoolExhausted = errors.New("connection pool exhausted")
|
||||
// ErrPoolClosed is returned when trying to use a closed pool
|
||||
ErrPoolClosed = errors.New("connection pool is closed")
|
||||
)
|
||||
|
||||
// connectionPool manages a pool of NATS connections
|
||||
type connectionPool struct {
|
||||
mu sync.RWMutex
|
||||
connections chan *pooledConnection
|
||||
factory func() (*natsp.Conn, error)
|
||||
size int
|
||||
idleTimeout time.Duration
|
||||
closed bool
|
||||
}
|
||||
|
||||
// pooledConnection wraps a NATS connection with metadata
|
||||
type pooledConnection struct {
|
||||
conn *natsp.Conn
|
||||
createdAt time.Time
|
||||
lastUsed time.Time
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// newConnectionPool creates a new connection pool
|
||||
func newConnectionPool(size int, factory func() (*natsp.Conn, error)) (*connectionPool, error) {
|
||||
if size <= 0 {
|
||||
size = 1
|
||||
}
|
||||
|
||||
pool := &connectionPool{
|
||||
connections: make(chan *pooledConnection, size),
|
||||
factory: factory,
|
||||
size: size,
|
||||
idleTimeout: 5 * time.Minute,
|
||||
closed: false,
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// Get retrieves a connection from the pool or creates a new one
|
||||
func (p *connectionPool) Get() (*pooledConnection, error) {
|
||||
p.mu.RLock()
|
||||
if p.closed {
|
||||
p.mu.RUnlock()
|
||||
return nil, ErrPoolClosed
|
||||
}
|
||||
p.mu.RUnlock()
|
||||
|
||||
// Try to get an existing connection from the pool
|
||||
select {
|
||||
case conn := <-p.connections:
|
||||
// Check if connection is still valid and not idle for too long
|
||||
if conn.isValid() && !conn.isExpired(p.idleTimeout) {
|
||||
conn.updateLastUsed()
|
||||
return conn, nil
|
||||
}
|
||||
// Connection is invalid or expired, close it and create a new one
|
||||
conn.close()
|
||||
return p.createConnection()
|
||||
default:
|
||||
// No connection available, create a new one
|
||||
return p.createConnection()
|
||||
}
|
||||
}
|
||||
|
||||
// Put returns a connection to the pool
|
||||
func (p *connectionPool) Put(conn *pooledConnection) error {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
|
||||
if p.closed {
|
||||
return conn.close()
|
||||
}
|
||||
|
||||
// Check if connection is still valid
|
||||
if !conn.isValid() {
|
||||
return conn.close()
|
||||
}
|
||||
|
||||
conn.updateLastUsed()
|
||||
|
||||
// Try to return connection to pool
|
||||
select {
|
||||
case p.connections <- conn:
|
||||
return nil
|
||||
default:
|
||||
// Pool is full, close the connection
|
||||
return conn.close()
|
||||
}
|
||||
}
|
||||
|
||||
// Close closes all connections in the pool
|
||||
func (p *connectionPool) Close() error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
p.closed = true
|
||||
close(p.connections)
|
||||
|
||||
// Close all connections in the pool
|
||||
for conn := range p.connections {
|
||||
conn.close()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createConnection creates a new pooled connection
|
||||
func (p *connectionPool) createConnection() (*pooledConnection, error) {
|
||||
conn, err := p.factory()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pooledConnection{
|
||||
conn: conn,
|
||||
createdAt: time.Now(),
|
||||
lastUsed: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// isValid checks if the underlying NATS connection is valid
|
||||
func (pc *pooledConnection) isValid() bool {
|
||||
pc.mu.Lock()
|
||||
defer pc.mu.Unlock()
|
||||
|
||||
if pc.conn == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
status := pc.conn.Status()
|
||||
return status == natsp.CONNECTED || status == natsp.RECONNECTING
|
||||
}
|
||||
|
||||
// isExpired checks if the connection has been idle for too long
|
||||
func (pc *pooledConnection) isExpired(timeout time.Duration) bool {
|
||||
pc.mu.Lock()
|
||||
defer pc.mu.Unlock()
|
||||
|
||||
if timeout <= 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
return time.Since(pc.lastUsed) > timeout
|
||||
}
|
||||
|
||||
// close closes the underlying NATS connection
|
||||
func (pc *pooledConnection) close() error {
|
||||
pc.mu.Lock()
|
||||
defer pc.mu.Unlock()
|
||||
|
||||
if pc.conn != nil {
|
||||
pc.conn.Close()
|
||||
pc.conn = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Conn returns the underlying NATS connection
|
||||
func (pc *pooledConnection) Conn() *natsp.Conn {
|
||||
pc.mu.Lock()
|
||||
defer pc.mu.Unlock()
|
||||
return pc.conn
|
||||
}
|
||||
|
||||
// updateLastUsed updates the last used timestamp in a thread-safe manner
|
||||
func (pc *pooledConnection) updateLastUsed() {
|
||||
pc.mu.Lock()
|
||||
defer pc.mu.Unlock()
|
||||
pc.lastUsed = time.Now()
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
natsp "github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
func TestTransportConnectionPool_GetPut(t *testing.T) {
|
||||
// Mock factory that creates connections
|
||||
connCount := 0
|
||||
factory := func() (*natsp.Conn, error) {
|
||||
connCount++
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
pool, err := newConnectionPool(3, factory)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create pool: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
// Get a connection (should create one)
|
||||
conn1, err := pool.Get()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get connection: %v", err)
|
||||
}
|
||||
if conn1 == nil {
|
||||
t.Fatal("Expected connection, got nil")
|
||||
}
|
||||
|
||||
// Put it back
|
||||
if err := pool.Put(conn1); err != nil {
|
||||
t.Fatalf("Failed to put connection: %v", err)
|
||||
}
|
||||
|
||||
// Get it again (should reuse the same one)
|
||||
conn2, err := pool.Get()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get connection: %v", err)
|
||||
}
|
||||
|
||||
if conn2 == nil {
|
||||
t.Fatal("Expected connection, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportConnectionPool_Concurrent(t *testing.T) {
|
||||
connCount := 0
|
||||
mu := sync.Mutex{}
|
||||
factory := func() (*natsp.Conn, error) {
|
||||
mu.Lock()
|
||||
connCount++
|
||||
mu.Unlock()
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
pool, err := newConnectionPool(5, factory)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create pool: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
// Simulate concurrent access
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 10; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
conn, err := pool.Get()
|
||||
if err != nil {
|
||||
t.Errorf("Failed to get connection: %v", err)
|
||||
return
|
||||
}
|
||||
// Simulate some work
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if err := pool.Put(conn); err != nil {
|
||||
t.Errorf("Failed to put connection: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// We should have created some connections
|
||||
mu.Lock()
|
||||
if connCount == 0 {
|
||||
t.Error("Expected at least one connection to be created")
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
func TestTransportConnectionPool_Close(t *testing.T) {
|
||||
factory := func() (*natsp.Conn, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
pool, err := newConnectionPool(3, factory)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create pool: %v", err)
|
||||
}
|
||||
|
||||
// Get a connection
|
||||
conn, err := pool.Get()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get connection: %v", err)
|
||||
}
|
||||
|
||||
// Close the pool
|
||||
if err := pool.Close(); err != nil {
|
||||
t.Fatalf("Failed to close pool: %v", err)
|
||||
}
|
||||
|
||||
// Put connection back to closed pool should not panic
|
||||
_ = pool.Put(conn)
|
||||
|
||||
// Try to get from closed pool
|
||||
_, err = pool.Get()
|
||||
if err != ErrPoolClosed {
|
||||
t.Errorf("Expected ErrPoolClosed, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportPoolConfiguration(t *testing.T) {
|
||||
// Test with pool size 5
|
||||
tr := NewTransport(PoolSize(5))
|
||||
nt, ok := tr.(*ntport)
|
||||
if !ok {
|
||||
t.Fatal("Expected transport to be of type *ntport")
|
||||
}
|
||||
|
||||
if nt.poolSize != 5 {
|
||||
t.Errorf("Expected pool size 5, got %d", nt.poolSize)
|
||||
}
|
||||
|
||||
// Test with custom idle timeout
|
||||
tr2 := NewTransport(PoolSize(3), PoolIdleTimeout(10*time.Minute))
|
||||
nt2, ok := tr2.(*ntport)
|
||||
if !ok {
|
||||
t.Fatal("Expected transport to be of type *ntport")
|
||||
}
|
||||
|
||||
if nt2.poolSize != 3 {
|
||||
t.Errorf("Expected pool size 3, got %d", nt2.poolSize)
|
||||
}
|
||||
|
||||
if nt2.poolIdleTimeout != 10*time.Minute {
|
||||
t.Errorf("Expected idle timeout 10m, got %v", nt2.poolIdleTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportDefaultSingleConnection(t *testing.T) {
|
||||
// Test that default behavior is single connection (pool size 1)
|
||||
tr := NewTransport()
|
||||
nt, ok := tr.(*ntport)
|
||||
if !ok {
|
||||
t.Fatal("Expected transport to be of type *ntport")
|
||||
}
|
||||
|
||||
if nt.poolSize != 1 {
|
||||
t.Errorf("Expected default pool size 1, got %d", nt.poolSize)
|
||||
}
|
||||
|
||||
// With size 1, pool should not be created
|
||||
if nt.pool != nil {
|
||||
t.Error("Expected no pool with size 1")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/codec"
|
||||
"go-micro.dev/v6/logger"
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultBufSizeH2 = 4 * 1024 * 1024
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
// Codec is the codec interface to use where headers are not supported
|
||||
// by the transport and the entire payload must be encoded
|
||||
Codec codec.Marshaler
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
Context context.Context
|
||||
// Logger is the underline logger
|
||||
Logger logger.Logger
|
||||
// TLSConfig to secure the connection. The assumption is that this
|
||||
// is mTLS keypair
|
||||
TLSConfig *tls.Config
|
||||
// Addrs is the list of intermediary addresses to connect to
|
||||
Addrs []string
|
||||
// Timeout sets the timeout for Send/Recv
|
||||
Timeout time.Duration
|
||||
// BuffSizeH2 is the HTTP2 buffer size
|
||||
BuffSizeH2 int
|
||||
// Secure tells the transport to secure the connection.
|
||||
// In the case TLSConfig is not specified best effort self-signed
|
||||
// certs should be used
|
||||
Secure bool
|
||||
}
|
||||
|
||||
type DialOptions struct {
|
||||
// TLS options can be set via global transport options or Context.
|
||||
// See SECURITY.md for TLS configuration best practices.
|
||||
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
Context context.Context
|
||||
// Timeout for dialing
|
||||
Timeout time.Duration
|
||||
// Tells the transport this is a streaming connection with
|
||||
// multiple calls to send/recv and that send may not even be called
|
||||
Stream bool
|
||||
// ConnClose sets the Connection header to close
|
||||
ConnClose bool
|
||||
// InsecureSkipVerify skip TLS verification.
|
||||
InsecureSkipVerify bool
|
||||
}
|
||||
|
||||
type ListenOptions struct {
|
||||
// TLS options can be set via global transport options or Context.
|
||||
// See SECURITY.md for TLS configuration best practices.
|
||||
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
// Addrs to use for transport.
|
||||
func Addrs(addrs ...string) Option {
|
||||
return func(o *Options) {
|
||||
o.Addrs = addrs
|
||||
}
|
||||
}
|
||||
|
||||
// Codec sets the codec used for encoding where the transport
|
||||
// does not support message headers.
|
||||
func Codec(c codec.Marshaler) Option {
|
||||
return func(o *Options) {
|
||||
o.Codec = c
|
||||
}
|
||||
}
|
||||
|
||||
// Timeout sets the timeout for Send/Recv execution.
|
||||
func Timeout(t time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
o.Timeout = t
|
||||
}
|
||||
}
|
||||
|
||||
// Use secure communication. If TLSConfig is not specified we
|
||||
// use InsecureSkipVerify and generate a self signed cert.
|
||||
func Secure(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.Secure = b
|
||||
}
|
||||
}
|
||||
|
||||
// TLSConfig to be used for the transport.
|
||||
func TLSConfig(t *tls.Config) Option {
|
||||
return func(o *Options) {
|
||||
o.TLSConfig = t
|
||||
}
|
||||
}
|
||||
|
||||
// Indicates whether this is a streaming connection.
|
||||
func WithStream() DialOption {
|
||||
return func(o *DialOptions) {
|
||||
o.Stream = true
|
||||
}
|
||||
}
|
||||
|
||||
func WithTimeout(d time.Duration) DialOption {
|
||||
return func(o *DialOptions) {
|
||||
o.Timeout = d
|
||||
}
|
||||
}
|
||||
|
||||
// WithConnClose sets the Connection header to close.
|
||||
func WithConnClose() DialOption {
|
||||
return func(o *DialOptions) {
|
||||
o.ConnClose = true
|
||||
}
|
||||
}
|
||||
|
||||
func WithInsecureSkipVerify(b bool) DialOption {
|
||||
return func(o *DialOptions) {
|
||||
o.InsecureSkipVerify = b
|
||||
}
|
||||
}
|
||||
|
||||
// Logger sets the underline logger.
|
||||
func Logger(l logger.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// BuffSizeH2 sets the HTTP2 buffer size.
|
||||
// Default is 4 * 1024 * 1024.
|
||||
func BuffSizeH2(size int) Option {
|
||||
return func(o *Options) {
|
||||
o.BuffSizeH2 = size
|
||||
}
|
||||
}
|
||||
|
||||
// InsecureSkipVerify sets the TLS options to skip verification.
|
||||
// NetListener Set net.Listener for httpTransport.
|
||||
func NetListener(customListener net.Listener) ListenOption {
|
||||
return func(o *ListenOptions) {
|
||||
if customListener == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if o.Context == nil {
|
||||
o.Context = context.TODO()
|
||||
}
|
||||
|
||||
o.Context = context.WithValue(o.Context, netListener{}, customListener)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Package transport is an interface for synchronous connection based communication
|
||||
package transport
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Transport is an interface which is used for communication between
|
||||
// services. It uses connection based socket send/recv semantics and
|
||||
// has various implementations; http, grpc, quic.
|
||||
type Transport interface {
|
||||
Init(...Option) error
|
||||
Options() Options
|
||||
Dial(addr string, opts ...DialOption) (Client, error)
|
||||
Listen(addr string, opts ...ListenOption) (Listener, error)
|
||||
String() string
|
||||
}
|
||||
|
||||
// Message is a broker message.
|
||||
type Message struct {
|
||||
Header map[string]string
|
||||
Body []byte
|
||||
}
|
||||
|
||||
type Socket interface {
|
||||
Recv(*Message) error
|
||||
Send(*Message) error
|
||||
Close() error
|
||||
Local() string
|
||||
Remote() string
|
||||
}
|
||||
|
||||
type Client interface {
|
||||
Socket
|
||||
}
|
||||
|
||||
type Listener interface {
|
||||
Addr() string
|
||||
Close() error
|
||||
Accept(func(Socket)) error
|
||||
}
|
||||
|
||||
type Option func(*Options)
|
||||
|
||||
type DialOption func(*DialOptions)
|
||||
|
||||
type ListenOption func(*ListenOptions)
|
||||
|
||||
var (
|
||||
DefaultTransport Transport = NewHTTPTransport()
|
||||
|
||||
DefaultDialTimeout = time.Second * 5
|
||||
)
|
||||
Reference in New Issue
Block a user