-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
62 lines (56 loc) · 1.47 KB
/
client.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
package flagsheet
import (
"context"
"fmt"
"net/http"
"time"
"github.com/Yiling-J/theine-go"
"github.com/bufbuild/connect-go"
flagsheetv1 "github.com/stillmatic/flagsheet/gen/flagsheet/v1"
"github.com/stillmatic/flagsheet/gen/flagsheet/v1/flagsheetv1connect"
)
type flagQuery struct {
Feature string
EntityID string
}
type FlagClient struct {
// flags is the feature flags client
flags flagsheetv1connect.FlagSheetServiceClient
// cache stores key value pairs with their result
cache *theine.Cache[flagQuery, string]
duration time.Duration
}
func NewFlagClient(flagsURL string) *FlagClient {
flagsClient := flagsheetv1connect.NewFlagSheetServiceClient(http.DefaultClient, flagsURL)
cache, err := theine.NewBuilder[flagQuery, string](1024).Build()
if err != nil {
panic(err)
}
return &FlagClient{
flags: flagsClient,
cache: cache,
duration: 10 * time.Second,
}
}
func (f *FlagClient) Evaluate(ctx context.Context, feature string, entityID string) (string, error) {
query := flagQuery{
Feature: feature,
EntityID: entityID,
}
val, ok := f.cache.Get(query)
// cache hit
if ok {
return val, nil
}
// cache miss, call and set cache
req := connect.NewRequest(&flagsheetv1.EvaluateRequest{
Feature: feature,
EntityId: entityID,
})
res, err := f.flags.Evaluate(ctx, req)
if err != nil {
return "", fmt.Errorf("could not evaluate feature: %w", err)
}
f.cache.SetWithTTL(query, res.Msg.Variant, 1, f.duration)
return res.Msg.Variant, nil
}