-
Notifications
You must be signed in to change notification settings - Fork 45
/
service.go
307 lines (276 loc) · 8.9 KB
/
service.go
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
package process
import (
"context"
"fmt"
"github.com/open-feature/flagd/core/pkg/evaluator"
"github.com/open-feature/flagd/core/pkg/logger"
"github.com/open-feature/flagd/core/pkg/model"
"github.com/open-feature/flagd/core/pkg/store"
"github.com/open-feature/flagd/core/pkg/sync"
"github.com/open-feature/flagd/core/pkg/sync/file"
"github.com/open-feature/flagd/core/pkg/sync/grpc"
"github.com/open-feature/flagd/core/pkg/sync/grpc/credentials"
of "github.com/open-feature/go-sdk/openfeature"
"golang.org/x/exp/maps"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
parallel "sync"
)
// InProcess service implements flagd flag evaluation in-process.
// Flag configurations are obtained from supported sources.
type InProcess struct {
evaluator evaluator.IEvaluator
events chan of.Event
listenerShutdown chan interface{}
logger *logger.Logger
serviceMetadata map[string]interface{}
sync sync.ISync
syncEnd context.CancelFunc
}
type Configuration struct {
Host any
Port any
Selector string
TLSEnabled bool
OfflineFlagSource string
}
func NewInProcessService(cfg Configuration) *InProcess {
log := logger.NewLogger(zap.NewRaw(), false)
iSync, uri := makeSyncProvider(cfg, log)
// service specific metadata
var svcMetadata map[string]interface{}
if cfg.Selector != "" {
svcMetadata = make(map[string]interface{}, 1)
svcMetadata["scope"] = cfg.Selector
}
flagStore := store.NewFlags()
flagStore.FlagSources = append(flagStore.FlagSources, uri)
return &InProcess{
evaluator: evaluator.NewJSON(log, flagStore),
events: make(chan of.Event, 5),
logger: log,
listenerShutdown: make(chan interface{}),
serviceMetadata: svcMetadata,
sync: iSync,
}
}
func (i *InProcess) Init() error {
var ctx context.Context
ctx, i.syncEnd = context.WithCancel(context.Background())
err := i.sync.Init(ctx)
if err != nil {
return err
}
initOnce := parallel.Once{}
syncInitSuccess := make(chan interface{})
syncInitErr := make(chan error)
syncChan := make(chan sync.DataSync, 1)
// start data sync
go func() {
err := i.sync.Sync(ctx, syncChan)
if err != nil {
syncInitErr <- err
}
}()
// start data sync listener and listen to listener shutdown hook
go func() {
for {
select {
case data := <-syncChan:
// re-syncs are ignored as we only support single flag sync source
changes, _, err := i.evaluator.SetState(data)
if err != nil {
i.events <- of.Event{
ProviderName: "flagd", EventType: of.ProviderError,
ProviderEventDetails: of.ProviderEventDetails{Message: "Error from flag sync " + err.Error()}}
}
initOnce.Do(func() {
i.events <- of.Event{ProviderName: "flagd", EventType: of.ProviderReady}
syncInitSuccess <- nil
})
i.events <- of.Event{
ProviderName: "flagd", EventType: of.ProviderConfigChange,
ProviderEventDetails: of.ProviderEventDetails{Message: "New flag sync", FlagChanges: maps.Keys(changes)}}
case <-i.listenerShutdown:
i.logger.Info("Shutting down data sync listener")
return
}
}
}()
// wait for initialization or error
select {
case <-syncInitSuccess:
return nil
case err := <-syncInitErr:
return err
}
}
func (i *InProcess) Shutdown() {
i.syncEnd()
close(i.listenerShutdown)
}
func (i *InProcess) ResolveBoolean(ctx context.Context, key string, defaultValue bool,
evalCtx map[string]interface{}) of.BoolResolutionDetail {
value, variant, reason, metadata, err := i.evaluator.ResolveBooleanValue(ctx, "", key, evalCtx)
i.appendMetadata(metadata)
if err != nil {
return of.BoolResolutionDetail{
Value: defaultValue,
ProviderResolutionDetail: of.ProviderResolutionDetail{
ResolutionError: mapError(key, err),
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
return of.BoolResolutionDetail{
Value: value,
ProviderResolutionDetail: of.ProviderResolutionDetail{
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
func (i *InProcess) ResolveString(ctx context.Context, key string, defaultValue string,
evalCtx map[string]interface{}) of.StringResolutionDetail {
value, variant, reason, metadata, err := i.evaluator.ResolveStringValue(ctx, "", key, evalCtx)
i.appendMetadata(metadata)
if err != nil {
return of.StringResolutionDetail{
Value: defaultValue,
ProviderResolutionDetail: of.ProviderResolutionDetail{
ResolutionError: mapError(key, err),
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
return of.StringResolutionDetail{
Value: value,
ProviderResolutionDetail: of.ProviderResolutionDetail{
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
func (i *InProcess) ResolveFloat(ctx context.Context, key string, defaultValue float64,
evalCtx map[string]interface{}) of.FloatResolutionDetail {
value, variant, reason, metadata, err := i.evaluator.ResolveFloatValue(ctx, "", key, evalCtx)
i.appendMetadata(metadata)
if err != nil {
return of.FloatResolutionDetail{
Value: defaultValue,
ProviderResolutionDetail: of.ProviderResolutionDetail{
ResolutionError: mapError(key, err),
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
return of.FloatResolutionDetail{
Value: value,
ProviderResolutionDetail: of.ProviderResolutionDetail{
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
func (i *InProcess) ResolveInt(ctx context.Context, key string, defaultValue int64,
evalCtx map[string]interface{}) of.IntResolutionDetail {
value, variant, reason, metadata, err := i.evaluator.ResolveIntValue(ctx, "", key, evalCtx)
i.appendMetadata(metadata)
if err != nil {
return of.IntResolutionDetail{
Value: defaultValue,
ProviderResolutionDetail: of.ProviderResolutionDetail{
ResolutionError: mapError(key, err),
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
return of.IntResolutionDetail{
Value: value,
ProviderResolutionDetail: of.ProviderResolutionDetail{
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
func (i *InProcess) ResolveObject(ctx context.Context, key string, defaultValue interface{},
evalCtx map[string]interface{}) of.InterfaceResolutionDetail {
value, variant, reason, metadata, err := i.evaluator.ResolveObjectValue(ctx, "", key, evalCtx)
i.appendMetadata(metadata)
if err != nil {
return of.InterfaceResolutionDetail{
Value: defaultValue,
ProviderResolutionDetail: of.ProviderResolutionDetail{
ResolutionError: mapError(key, err),
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
return of.InterfaceResolutionDetail{
Value: value,
ProviderResolutionDetail: of.ProviderResolutionDetail{
Reason: of.Reason(reason),
Variant: variant,
FlagMetadata: metadata,
},
}
}
func (i *InProcess) EventChannel() <-chan of.Event {
return i.events
}
func (i *InProcess) appendMetadata(evalMetadata map[string]interface{}) {
// For a nil slice, the number of iterations is 0
for k, v := range i.serviceMetadata {
evalMetadata[k] = v
}
}
// makeSyncProvider is a helper to create sync.ISync and return the underlying uri used by it to the caller
func makeSyncProvider(cfg Configuration, log *logger.Logger) (sync.ISync, string) {
if cfg.OfflineFlagSource != "" {
// file sync provider
log.Info("operating in in-process mode with offline flags sourced from " + cfg.OfflineFlagSource)
return &file.Sync{
URI: cfg.OfflineFlagSource,
Logger: log,
Mux: ¶llel.RWMutex{},
}, cfg.OfflineFlagSource
}
// grpc sync provider
uri := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
log.Info("operating in in-process mode with flags sourced from " + uri)
return &grpc.Sync{
CredentialBuilder: &credentials.CredentialBuilder{},
Logger: log,
Secure: cfg.TLSEnabled,
Selector: cfg.Selector,
URI: uri,
}, uri
}
// mapError is a helper to map evaluation errors to OF errors
func mapError(flagKey string, err error) of.ResolutionError {
switch err.Error() {
case model.FlagNotFoundErrorCode:
return of.NewFlagNotFoundResolutionError(fmt.Sprintf("flag: " + flagKey + " not found"))
case model.FlagDisabledErrorCode:
return of.NewFlagNotFoundResolutionError(fmt.Sprintf("flag: " + flagKey + " is disabled"))
case model.TypeMismatchErrorCode:
return of.NewTypeMismatchResolutionError(fmt.Sprintf("flag: " + flagKey + " evaluated type not valid"))
case model.ParseErrorCode:
return of.NewParseErrorResolutionError(fmt.Sprintf("flag: " + flagKey + " parsing error"))
default:
return of.NewGeneralResolutionError(fmt.Sprintf("flag: " + flagKey + " unable to evaluate"))
}
}