connector.go raw
1 package transport
2
3 import (
4 "context"
5
6 "google.golang.org/grpc"
7 "google.golang.org/protobuf/reflect/protoreflect"
8
9 "github.com/yandex-cloud/go-sdk/v2/pkg/endpoints"
10 transportgrpc "github.com/yandex-cloud/go-sdk/v2/pkg/transport/grpc"
11 )
12
13 // Connector is an interface for retrieving gRPC client connections to specified methods with context and options.
14 type Connector interface {
15 GetConnection(ctx context.Context, method protoreflect.FullName, opts ...grpc.CallOption) (grpc.ClientConnInterface, error)
16 }
17
18 var _ Connector = &ConnectorImpl{}
19
20 // ConnectorImpl is an implementation of the Connector interface, managing gRPC connections using endpoints resolution and pooling.
21 type ConnectorImpl struct {
22 endpointsResolver endpoints.EndpointsResolver
23 connectionPool *transportgrpc.ConnPool
24 }
25
26 // NewConnector initializes and returns a ConnectorImpl instance with the provided endpoints resolver and connection pool.
27 func NewConnector(endpoints endpoints.EndpointsResolver, connectionPool *transportgrpc.ConnPool) *ConnectorImpl {
28 return &ConnectorImpl{
29 endpointsResolver: endpoints,
30 connectionPool: connectionPool,
31 }
32 }
33
34 // GetConnection retrieves a gRPC client connection for the given method, resolving the endpoint via the endpointsResolver.
35 func (c *ConnectorImpl) GetConnection(ctx context.Context, method protoreflect.FullName, opts ...grpc.CallOption) (grpc.ClientConnInterface, error) {
36 ep, err := c.endpointsResolver.Endpoint(ctx, method, opts...)
37 if err != nil {
38 return nil, err
39 }
40
41 return c.connectionPool.GetConn(ctx, ep)
42 }
43
44 // SingleConnector provides a gRPC connection handler using a single predefined endpoint resolver.
45 type SingleConnector struct {
46 endpointsResolver endpoints.EndpointsResolver
47 }
48
49 // NewSingleConnector creates a SingleConnector that utilizes a single gRPC endpoint with the specified address and options.
50 func NewSingleConnector(add string, opts ...grpc.DialOption) *SingleConnector {
51 return &SingleConnector{
52 endpointsResolver: endpoints.NewSingleEndpointResolver(add, opts...),
53 }
54 }
55
56 // GetConnection retrieves a gRPC client connection for the specified method and options, resolving the appropriate endpoint.
57 func (s *SingleConnector) GetConnection(ctx context.Context, method protoreflect.FullName, opts ...grpc.CallOption) (grpc.ClientConnInterface, error) {
58 ep, err := s.endpointsResolver.Endpoint(ctx, method, opts...)
59 if err != nil {
60 return nil, err
61 }
62
63 return grpc.NewClient(ep.Addr, ep.DialOptions...)
64 }
65