Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(flags): Add configurable flag timeouts #37

Merged
merged 5 commits into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,13 @@ type Config struct {
// timer triggers.
Interval time.Duration

// Interval at which to fetch new feature flags, 5min by default
// Interval at which to fetch new feature flag definitions, 5min by default
DefaultFeatureFlagsPollingInterval time.Duration

// Calculate when feature flags should be polled next. Setting this property
// Timeout for fetching feature flags, 3 seconds by default
FeatureFlagRequestTimeout time.Duration

// Calculate when feature flag definitions should be polled next. Setting this property
// will override DefaultFeatureFlagsPollingInterval.
NextFeatureFlagsPollingTick func() time.Duration

Expand Down Expand Up @@ -98,6 +101,9 @@ const DefaultInterval = 5 * time.Second
// Specifies the default interval at which to fetch new feature flags
const DefaultFeatureFlagsPollingInterval = 5 * time.Minute

// Specifies the default timeout for fetching feature flags
const DefaultFeatureFlagRequestTimeout = 3 * time.Second

// This constant sets the default batch size used by client instances if none
// was explicitly set.
const DefaultBatchSize = 250
Expand Down Expand Up @@ -139,6 +145,10 @@ func makeConfig(c Config) Config {
c.DefaultFeatureFlagsPollingInterval = DefaultFeatureFlagsPollingInterval
}

if c.FeatureFlagRequestTimeout == 0 {
c.FeatureFlagRequestTimeout = DefaultFeatureFlagRequestTimeout
}

if c.Transport == nil {
c.Transport = http.DefaultTransport
}
Expand Down
26 changes: 17 additions & 9 deletions examples/featureflags.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ import (
)

func TestIsFeatureEnabled() {
client, _ := posthog.NewWithConfig("phc_X8B6bhR1QgQKP1WdpFLN82LxLxgZ7WPXDgJyRyvIpib", posthog.Config{
Interval: 30 * time.Second,
BatchSize: 100,
Verbose: true,
PersonalApiKey: "phx_vXZ7AOnFjDrCxfWLyo9V6P0SWLLfXT2d5euy3U0nRGk",
client, _ := posthog.NewWithConfig("phc_36WfBWNJEQcYotMZ7Ui7EWzqKLbIo2LWJFG5fIg1EER", posthog.Config{
Interval: 30 * time.Second,
BatchSize: 100,
Verbose: true,
PersonalApiKey: "phx_n79cT52OfsxAWDhZs9j3w67aRoBCZ7l5ksRRKmAi5nr",
Endpoint: "http://localhost:8000",
FeatureFlagRequestTimeout: 3 * time.Second,
})
defer client.Close()

Expand All @@ -22,38 +24,44 @@ func TestIsFeatureEnabled() {
DistinctId: "hello",
})

fmt.Println("boolResult:", boolResult)

if boolErr != nil || boolResult == nil {
fmt.Println("error:", boolErr)
return
// return
}

// Simple flag
simpleResult, simpleErr := client.GetFeatureFlag(posthog.FeatureFlagPayload{
Key: "simple-test",
DistinctId: "hello",
})

fmt.Println("simpleResult:", simpleResult)
if simpleErr != nil || simpleResult == false {
fmt.Println("error:", simpleErr)
return
// return
}

// Multivariate flag
variantResult, variantErr := client.GetFeatureFlag(posthog.FeatureFlagPayload{
Key: "multivariate-test",
DistinctId: "hello",
})
fmt.Println("variantResult:", variantResult)
if variantErr != nil || variantResult != "variant-value" {
fmt.Println("error:", variantErr)
return
// return
}

// Multivariate + simple flag
variantResult, variantErr = client.GetFeatureFlag(posthog.FeatureFlagPayload{
Key: "multivariate-simple-test",
DistinctId: "hello",
})
fmt.Println("variantResult:", variantResult)
if variantErr != nil || variantResult == true {
fmt.Println("error:", variantErr)
return
// return
}
}
4 changes: 2 additions & 2 deletions examples/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

func main() {
TestCapture()
TestCaptureWithSendFeatureFlagOption()
// TestCapture()
// TestCaptureWithSendFeatureFlagOption()
TestIsFeatureEnabled()
}
36 changes: 21 additions & 15 deletions featureflags.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package posthog

import (
"bytes"
"context"
"crypto/sha1"
"encoding/json"
"errors"
Expand Down Expand Up @@ -34,6 +35,7 @@ type FeatureFlagsPoller struct {
mutex sync.RWMutex
fetchedFlagsSuccessfullyOnce bool
nextPollTick func() time.Duration
flagTimeout time.Duration
}

type FeatureFlag struct {
Expand Down Expand Up @@ -121,6 +123,7 @@ func newFeatureFlagsPoller(
httpClient http.Client,
pollingInterval time.Duration,
nextPollTick func() time.Duration,
flagTimeout time.Duration,
) *FeatureFlagsPoller {

if nextPollTick == nil {
Expand All @@ -139,6 +142,7 @@ func newFeatureFlagsPoller(
mutex: sync.RWMutex{},
fetchedFlagsSuccessfullyOnce: false,
nextPollTick: nextPollTick,
flagTimeout: flagTimeout,
}

go poller.run()
Expand Down Expand Up @@ -169,7 +173,8 @@ func (poller *FeatureFlagsPoller) run() {
func (poller *FeatureFlagsPoller) fetchNewFeatureFlags() {
personalApiKey := poller.personalApiKey
headers := [][2]string{{"Authorization", "Bearer " + personalApiKey + ""}}
res, err := poller.localEvaluationFlags(headers)
res, err, cancel := poller.localEvaluationFlags(headers)
defer cancel()
if err != nil || res.StatusCode != http.StatusOK {
poller.loaded <- false
poller.Errorf("Unable to fetch feature flags", err)
Expand All @@ -193,9 +198,7 @@ func (poller *FeatureFlagsPoller) fetchNewFeatureFlags() {
poller.loaded <- true
}
newFlags := []FeatureFlag{}
for _, flag := range featureFlagsResponse.Flags {
newFlags = append(newFlags, flag)
}
newFlags = append(newFlags, featureFlagsResponse.Flags...)
poller.mutex.Lock()
poller.featureFlags = newFlags
poller.cohorts = featureFlagsResponse.Cohorts
Expand Down Expand Up @@ -746,7 +749,7 @@ func interfaceToFloat(val interface{}) (float64, error) {
case uint64:
i = float64(t)
default:
errMessage := "Argument not orderable"
errMessage := "argument not orderable"
return 0.0, errors.New(errMessage)
}

Expand Down Expand Up @@ -815,18 +818,18 @@ func (poller *FeatureFlagsPoller) GetFeatureFlags() []FeatureFlag {
return poller.featureFlags
}

func (poller *FeatureFlagsPoller) decide(requestData []byte, headers [][2]string) (*http.Response, error) {
localEvaluationEndpoint := "decide/?v=2"
func (poller *FeatureFlagsPoller) decide(requestData []byte, headers [][2]string) (*http.Response, error, context.CancelFunc) {
decideEndpoint := "decide/?v=2"

url, err := url.Parse(poller.Endpoint + "/" + localEvaluationEndpoint + "")
url, err := url.Parse(poller.Endpoint + "/" + decideEndpoint + "")
if err != nil {
poller.Errorf("creating url - %s", err)
}

return poller.request("POST", url, requestData, headers)
return poller.request("POST", url, requestData, headers, poller.flagTimeout)
}

func (poller *FeatureFlagsPoller) localEvaluationFlags(headers [][2]string) (*http.Response, error) {
func (poller *FeatureFlagsPoller) localEvaluationFlags(headers [][2]string) (*http.Response, error, context.CancelFunc) {
localEvaluationEndpoint := "api/feature_flag/local_evaluation"

url, err := url.Parse(poller.Endpoint + "/" + localEvaluationEndpoint + "")
Expand All @@ -838,11 +841,13 @@ func (poller *FeatureFlagsPoller) localEvaluationFlags(headers [][2]string) (*ht
searchParams.Add("send_cohorts", "true")
url.RawQuery = searchParams.Encode()

return poller.request("GET", url, []byte{}, headers)
return poller.request("GET", url, []byte{}, headers, time.Duration(10)*time.Second)
}

func (poller *FeatureFlagsPoller) request(method string, url *url.URL, requestData []byte, headers [][2]string) (*http.Response, error) {
req, err := http.NewRequest(method, url.String(), bytes.NewReader(requestData))
func (poller *FeatureFlagsPoller) request(method string, url *url.URL, requestData []byte, headers [][2]string, timeout time.Duration) (*http.Response, error, context.CancelFunc) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)

req, err := http.NewRequestWithContext(ctx, method, url.String(), bytes.NewReader(requestData))
if err != nil {
poller.Errorf("creating request - %s", err)
}
Expand All @@ -862,7 +867,7 @@ func (poller *FeatureFlagsPoller) request(method string, url *url.URL, requestDa
poller.Errorf("sending request - %s", err)
}

return res, err
return res, err, cancel
}

func (poller *FeatureFlagsPoller) ForceReload() {
Expand All @@ -888,7 +893,8 @@ func (poller *FeatureFlagsPoller) getFeatureFlagVariants(distinctId string, grou
poller.Errorf(errorMessage)
return nil, errors.New(errorMessage)
}
res, err := poller.decide(requestDataBytes, headers)
res, err, cancel := poller.decide(requestDataBytes, headers)
defer cancel()
if err != nil || res.StatusCode != http.StatusOK {
errorMessage = "Error calling /decide/"
poller.Errorf(errorMessage)
Expand Down
1 change: 1 addition & 0 deletions posthog.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ func NewWithConfig(apiKey string, config Config) (cli Client, err error) {
c.http,
c.DefaultFeatureFlagsPollingInterval,
c.NextFeatureFlagsPollingTick,
c.FeatureFlagRequestTimeout,
)
}

Expand Down
Loading