-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathservice.go
More file actions
310 lines (254 loc) · 7.74 KB
/
Copy pathservice.go
File metadata and controls
310 lines (254 loc) · 7.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package transport
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"sync"
offlipt "github.com/open-feature/go-sdk-contrib/providers/flipt/pkg/service"
of "github.com/open-feature/go-sdk/openfeature"
flipt "go.flipt.io/flipt/rpc/flipt"
"go.flipt.io/flipt/rpc/flipt/evaluation"
sdk "go.flipt.io/flipt/sdk/go"
sdkgrpc "go.flipt.io/flipt/sdk/go/grpc"
sdkhttp "go.flipt.io/flipt/sdk/go/http"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
const (
requestID = "requestID"
defaultAddr = "http://localhost:8080"
)
// Service is a Transport service.
type Service struct {
client offlipt.Client
address string
certificatePath string
unaryInterceptors []grpc.UnaryClientInterceptor
once sync.Once
tokenProvider sdk.ClientTokenProvider
grpcDialOptions []grpc.DialOption
httpClient *http.Client
}
// Option is a service option.
type Option func(*Service)
// WithHTTPClient returns an [Option] that specifies the HTTP client to use as the basis of communications.
func WithHTTPClient(client *http.Client) Option {
return func(s *Service) {
s.httpClient = client
}
}
// WithAddress sets the address for the remote Flipt gRPC API.
func WithAddress(address string) Option {
return func(s *Service) {
s.address = address
}
}
// WithCertificatePath sets the certificate path for the service.
func WithCertificatePath(certificatePath string) Option {
return func(s *Service) {
s.certificatePath = certificatePath
}
}
// WithUnaryClientInterceptor sets the provided unary client interceptors
// to be applied to the established gRPC client connection.
func WithUnaryClientInterceptor(unaryInterceptors ...grpc.UnaryClientInterceptor) Option {
return func(s *Service) {
s.unaryInterceptors = unaryInterceptors
}
}
// WithClientTokenProvider sets the token provider for auth to support client
// auth needs.
func WithClientTokenProvider(tokenProvider sdk.ClientTokenProvider) Option {
return func(s *Service) {
s.tokenProvider = tokenProvider
}
}
// WithGRPCDialOptions sets the provided DialOption
// to be applied when establishing gRPC client connection.
func WithGRPCDialOptions(dialOptions ...grpc.DialOption) Option {
return func(s *Service) {
s.grpcDialOptions = append(s.grpcDialOptions, dialOptions...)
}
}
// New creates a new Transport service.
func New(opts ...Option) *Service {
s := &Service{
address: defaultAddr,
unaryInterceptors: []grpc.UnaryClientInterceptor{},
grpcDialOptions: []grpc.DialOption{
grpc.WithStatsHandler(otelgrpc.NewClientHandler()),
},
httpClient: http.DefaultClient,
}
for _, opt := range opts {
opt(s)
}
return s
}
func (s *Service) connect() (*grpc.ClientConn, error) {
var (
err error
credentials = insecure.NewCredentials()
)
if s.certificatePath != "" {
credentials, err = loadTLSCredentials(s.certificatePath)
if err != nil {
// TODO: log error?
credentials = insecure.NewCredentials()
}
}
address := s.address
if strings.HasPrefix(s.address, "unix://") {
address = "passthrough:///" + s.address
}
dialOptions := []grpc.DialOption{
grpc.WithTransportCredentials(credentials),
grpc.WithChainUnaryInterceptor(s.unaryInterceptors...),
}
dialOptions = append(dialOptions, s.grpcDialOptions...)
conn, err := grpc.NewClient(address, dialOptions...)
if err != nil {
return nil, fmt.Errorf("dialing %w", err)
}
return conn, nil
}
func (s *Service) instance() (offlipt.Client, error) {
type fclient struct {
*sdk.Flipt
*sdk.Evaluation
}
if s.client != nil {
return s.client, nil
}
var err error
s.once.Do(func() {
u, uerr := url.Parse(s.address)
if uerr != nil {
err = fmt.Errorf("connecting %w", uerr)
}
opts := []sdk.Option{}
if s.tokenProvider != nil {
opts = append(opts, sdk.WithClientTokenProvider(s.tokenProvider))
}
hclient := sdk.New(sdkhttp.NewTransport(s.address, sdkhttp.WithHTTPClient(s.httpClient)), opts...)
if u.Scheme == "https" || u.Scheme == "http" {
s.client = &fclient{
hclient.Flipt(),
hclient.Evaluation(),
}
return
}
conn, cerr := s.connect()
if cerr != nil {
err = fmt.Errorf("connecting %w", cerr)
}
gclient := sdk.New(sdkgrpc.NewTransport(conn), opts...)
s.client = &fclient{
gclient.Flipt(),
gclient.Evaluation(),
}
})
return s.client, err
}
// GetFlag returns a flag if it exists for the given namespace/flag key pair.
func (s *Service) GetFlag(ctx context.Context, namespaceKey, flagKey string) (*flipt.Flag, error) {
conn, err := s.instance()
if err != nil {
return nil, err
}
flag, err := conn.GetFlag(ctx, &flipt.GetFlagRequest{
Key: flagKey,
NamespaceKey: namespaceKey,
})
if err != nil {
return nil, gRPCToOpenFeatureError(err)
}
return flag, nil
}
// Boolean evaluates a boolean type flag with the given context and namespace/flag key pair.
func (s *Service) Boolean(ctx context.Context, namespaceKey, flagKey string, evalCtx map[string]any) (*evaluation.BooleanEvaluationResponse, error) {
if evalCtx == nil {
return nil, of.NewInvalidContextResolutionError("evalCtx is nil")
}
ec := convertMapInterface(evalCtx)
targetingKey := ec[of.TargetingKey]
if targetingKey == "" {
return nil, of.NewTargetingKeyMissingResolutionError("targetingKey is missing")
}
conn, err := s.instance()
if err != nil {
return nil, err
}
ber, err := conn.Boolean(ctx, &evaluation.EvaluationRequest{FlagKey: flagKey, NamespaceKey: namespaceKey, EntityId: targetingKey, RequestId: ec[requestID], Context: ec})
if err != nil {
return nil, gRPCToOpenFeatureError(err)
}
return ber, nil
}
// Evaluate evaluates a variant type flag with the given context and namespace/flag key pair.
func (s *Service) Evaluate(ctx context.Context, namespaceKey, flagKey string, evalCtx map[string]any) (*evaluation.VariantEvaluationResponse, error) {
if evalCtx == nil {
return nil, of.NewInvalidContextResolutionError("evalCtx is nil")
}
ec := convertMapInterface(evalCtx)
targetingKey := ec[of.TargetingKey]
if targetingKey == "" {
return nil, of.NewTargetingKeyMissingResolutionError("targetingKey is missing")
}
conn, err := s.instance()
if err != nil {
return nil, err
}
resp, err := conn.Variant(ctx, &evaluation.EvaluationRequest{FlagKey: flagKey, NamespaceKey: namespaceKey, EntityId: targetingKey, RequestId: ec[requestID], Context: ec})
if err != nil {
return nil, gRPCToOpenFeatureError(err)
}
return resp, nil
}
func convertMapInterface(m map[string]any) map[string]string {
ee := make(map[string]string)
for k, v := range m {
ee[k] = fmt.Sprintf("%v", v)
}
return ee
}
func loadTLSCredentials(serverCertPath string) (credentials.TransportCredentials, error) {
pemServerCA, err := os.ReadFile(serverCertPath)
if err != nil {
return nil, fmt.Errorf("failed to load certificate: %w", err)
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(pemServerCA) {
return nil, errors.New("failed to add server CA's certificate")
}
config := &tls.Config{
RootCAs: certPool,
MinVersion: tls.VersionTLS12,
}
return credentials.NewTLS(config), nil
}
func gRPCToOpenFeatureError(err error) of.ResolutionError {
s, ok := status.FromError(err)
if !ok {
return of.NewGeneralResolutionError("internal error: " + err.Error())
}
switch s.Code() {
case codes.NotFound:
return of.NewFlagNotFoundResolutionError(s.Message())
case codes.InvalidArgument:
return of.NewInvalidContextResolutionError(s.Message())
case codes.Unavailable:
return of.NewProviderNotReadyResolutionError(s.Message())
}
return of.NewGeneralResolutionError(s.Message())
}