Skip to content

Commit

Permalink
Redo initialization options
Browse files Browse the repository at this point in the history
  • Loading branch information
bpapillon committed Oct 25, 2024
1 parent 1b1df12 commit 10ee82b
Show file tree
Hide file tree
Showing 10 changed files with 171 additions and 208 deletions.
3 changes: 2 additions & 1 deletion .fernignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
README.md
buffer/buffer.go
cache/cache.go
core/request_option.go
core/custom_options.go
custom_types.go
client/opts.go
client/schematic_client.go
client/schematic_client_test.go
flags/flags.go
Expand Down
5 changes: 5 additions & 0 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import (
"time"
)

type CacheProvider[T any] interface {
Get(ctx context.Context, key string) (T, bool)
Set(ctx context.Context, key string, val T, ttlOverride *time.Duration) error
}

const defaultCacheSize = 1000 // 1000 records
const defaultCacheTTL = 5 * time.Second

Expand Down
127 changes: 0 additions & 127 deletions client/opts.go

This file was deleted.

83 changes: 22 additions & 61 deletions client/schematic_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,71 +9,54 @@ import (
"github.com/schematichq/schematic-go/cache"
core "github.com/schematichq/schematic-go/core"
"github.com/schematichq/schematic-go/flags"
"github.com/schematichq/schematic-go/http"
"github.com/schematichq/schematic-go/logger"
option "github.com/schematichq/schematic-go/option"
)

type SchematicClient struct {
*Client

clientOptions []core.RequestOption
errors chan error
eventBufferPeriod *time.Duration
events chan *schematicgo.CreateEventRequestBody
flagCheckCacheProviders []schematicgo.CacheProvider[bool]
flagCheckCacheProviders []schematicgo.BoolCacheProvider
flagDefaults map[string]bool
isOffline bool
logger schematicgo.Logger
stopWorker chan struct{}
workerInterval time.Duration
}

func NewSchematicClient(apiKey string, opts ...ClientOpt) *SchematicClient {
var apiConfig []core.RequestOption
func NewSchematicClient(opts ...option.RequestOption) *SchematicClient {
options := core.NewRequestOptions(opts...)
if options.APIKey == "" {
// If no API key provideed, assume offline mode if no API key provided
opts = append(opts, core.WithOfflineMode())
}

if apiKey != "" {
apiConfig = append(apiConfig, &core.APIKeyOption{APIKey: apiKey})
} else {
opts = append(opts, WithOfflineMode())
// If no caching behavior is specified, assume a default behavior
if len(options.FlagCheckCacheProviders) == 0 {
opts = append(opts, core.WithFlagCheckCacheProvider(cache.NewDefaultCache[bool]()))
}

client := &SchematicClient{
clientOptions: apiConfig,
flagCheckCacheProviders: make([]schematicgo.CacheProvider[bool], 0),
Client: NewClient(opts...),
errors: make(chan error, 100),
eventBufferPeriod: options.EventBufferPeriod,
events: make(chan *schematicgo.CreateEventRequestBody, 100),
flagDefaults: make(map[string]bool),
flagCheckCacheProviders: options.FlagCheckCacheProviders,
flagDefaults: options.FlagDefaults,
logger: logger.NewDefaultLogger(),
stopWorker: make(chan struct{}),
workerInterval: 5 * time.Second,
}

// Apply initialization options
ctx := context.Background()
for _, opt := range opts {
if err := opt.Apply(ctx, client); err != nil {
client.errors <- err
}
}

// Once initialization options are applied, we can create the API client
client.Client = NewClient(client.clientOptions...)

// If no caching behavior is specified, assume a default behavior
if len(client.flagCheckCacheProviders) == 0 {
client.flagCheckCacheProviders = append(client.flagCheckCacheProviders, cache.NewDefaultCache[bool]())
}

// Start background worker which handles async error logging and event buffering
go client.worker()

return client
}

func (c *SchematicClient) AddFlagCheckCacheProvider(ctx context.Context, provider schematicgo.CacheProvider[bool]) {
c.flagCheckCacheProviders = append(c.flagCheckCacheProviders, provider)
}

func (c *SchematicClient) CheckFlag(ctx context.Context, evalCtx *schematicgo.CheckFlagRequestBody, flagKey string) bool {
defer func() {
if r := recover(); r != nil {
Expand Down Expand Up @@ -144,25 +127,13 @@ func (c *SchematicClient) Identify(
}
}

func (c *SchematicClient) SetAPIClient(apiClient *Client) {
c.Client = apiClient
}

func (c *SchematicClient) SetAPIHost(ctx context.Context, host string) {
c.clientOptions = append(c.clientOptions, &core.BaseURLOption{BaseURL: host})

// In case this is called after initialization, recreate the API client
c.Client = NewClient(c.clientOptions...)
}

func (c *SchematicClient) SetEventBufferPeriod(period time.Duration) {
c.eventBufferPeriod = &period
}

func (c *SchematicClient) SetFlagDefault(
flag string,
value bool,
) {
if c.flagDefaults == nil {
c.flagDefaults = make(map[string]bool)
}
c.flagDefaults[flag] = value
}

Expand All @@ -174,20 +145,6 @@ func (c *SchematicClient) SetFlagDefaults(
}
}

func (c *SchematicClient) SetOfflineMode() {
c.isOffline = true

c.clientOptions = append(c.clientOptions, &core.HTTPClientOption{
HTTPClient: http.NoopClient{},
})
}

func (c *SchematicClient) SetHTTPClient(httpClient core.HTTPClient) {
c.clientOptions = append(c.clientOptions, &core.HTTPClientOption{
HTTPClient: httpClient,
})
}

func (c *SchematicClient) Track(
ctx context.Context,
body *schematicgo.EventBodyTrack,
Expand Down Expand Up @@ -231,6 +188,10 @@ func (c *SchematicClient) enqueueEvent(
func (c *SchematicClient) getFlagDefault(
flag string,
) bool {
if c.flagDefaults == nil {
return false
}

if value, ok := c.flagDefaults[flag]; ok {
return value
}
Expand Down
18 changes: 10 additions & 8 deletions client/schematic_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,24 @@ import (
"github.com/golang/mock/gomock"
schematicgo "github.com/schematichq/schematic-go"
schematicclient "github.com/schematichq/schematic-go/client"
core "github.com/schematichq/schematic-go/core"
"github.com/schematichq/schematic-go/mocks"
option "github.com/schematichq/schematic-go/option"

"github.com/stretchr/testify/assert"
)

func TestNewSchematicClient(t *testing.T) {
client := schematicclient.NewSchematicClient("test-api-key")
client := schematicclient.NewSchematicClient(option.WithAPIKey("test-api-key"))
defer client.Close()

assert.NotNil(t, client)
}

func TestCheckFlagWithCacheHit(t *testing.T) {
ctrl := gomock.NewController(t)
mockHTTPClient := mocks.NewMockHTTPClient(ctrl)
client := schematicclient.NewSchematicClient("test-api-key", schematicclient.WithHTTPClient(mockHTTPClient))

client := schematicclient.NewSchematicClient(option.WithAPIKey("test-api-key"), option.WithHTTPClient(mockHTTPClient))
defer client.Close()

assert.NotNil(t, client)
Expand Down Expand Up @@ -61,7 +63,7 @@ func TestCheckFlagWithCacheHit(t *testing.T) {
func TestCheckFlagWithNoCache(t *testing.T) {
ctrl := gomock.NewController(t)
mockHTTPClient := mocks.NewMockHTTPClient(ctrl)
client := schematicclient.NewSchematicClient("test-api-key", schematicclient.WithDisableFlagCheckCache(), schematicclient.WithHTTPClient(mockHTTPClient))
client := schematicclient.NewSchematicClient(option.WithAPIKey("test-api-key"), core.WithDisableFlagCheckCache(), option.WithHTTPClient(mockHTTPClient))
defer client.Close()

assert.NotNil(t, client)
Expand Down Expand Up @@ -94,7 +96,7 @@ func TestCheckFlagWithCacheOptions(t *testing.T) {
cacheMaxSize := 1000
ctrl := gomock.NewController(t)
mockHTTPClient := mocks.NewMockHTTPClient(ctrl)
client := schematicclient.NewSchematicClient("test-api-key", schematicclient.WithLocalFlagCheckCache(cacheMaxSize, cacheTTL), schematicclient.WithHTTPClient(mockHTTPClient))
client := schematicclient.NewSchematicClient(option.WithAPIKey("test-api-key"), core.WithLocalFlagCheckCache(cacheMaxSize, cacheTTL), option.WithHTTPClient(mockHTTPClient))
defer client.Close()

assert.NotNil(t, client)
Expand Down Expand Up @@ -130,7 +132,7 @@ func TestCheckFlagWithCacheOptions(t *testing.T) {
func TestTrackEventBatch(t *testing.T) {
//ctrl := gomock.NewController(t)
//mockHTTPClient := mocks.NewMockHTTPClient(ctrl)
client := schematicclient.NewSchematicClient("test-api-key", schematicclient.WithEventBufferPeriod(10*time.Millisecond))
client := schematicclient.NewSchematicClient(option.WithAPIKey("test-api-key"), core.WithEventBufferPeriod(10*time.Millisecond))
defer client.Close()

assert.NotNil(t, client)
Expand All @@ -144,7 +146,7 @@ func TestTrackEventBatch(t *testing.T) {
func TestMultipleEventBatches(t *testing.T) {
ctrl := gomock.NewController(t)
mockHTTPClient := mocks.NewMockHTTPClient(ctrl)
client := schematicclient.NewSchematicClient("test-api-key", schematicclient.WithEventBufferPeriod(10*time.Millisecond), schematicclient.WithHTTPClient(mockHTTPClient))
client := schematicclient.NewSchematicClient(option.WithAPIKey("test-api-key"), core.WithEventBufferPeriod(10*time.Millisecond), option.WithHTTPClient(mockHTTPClient))
defer client.Close()

assert.NotNil(t, client)
Expand Down Expand Up @@ -177,7 +179,7 @@ func TestMultipleEventBatches(t *testing.T) {
}

func TestCheckFlagOfflineMode(t *testing.T) {
client := schematicclient.NewSchematicClient("")
client := schematicclient.NewSchematicClient()
client.SetFlagDefault("test-flag", true)
defer client.Close()

Expand Down
Loading

0 comments on commit 10ee82b

Please sign in to comment.