-
Notifications
You must be signed in to change notification settings - Fork 17
feat: Realtime improvements #154
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
Merged
Merged
Changes from 3 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9210899
Add WithPolling
rolodato 113f600
Realtime/polling improvements
rolodato 26d4459
add HTTP logging middleware
rolodato 2fb64a3
feedback
rolodato 0729ae5
Merge branch 'main' into feat/realtime-poll
rolodato e983df6
add pollThenStartRealtime
rolodato 25ddb91
unused
rolodato 1b2698d
lint
rolodato 077e0ef
only log if new env. fix poll timeout
rolodato File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package flagsmith | ||
|
|
||
| import "time" | ||
|
|
||
| const ( | ||
| initialBackoff = 200 * time.Millisecond | ||
| maxBackoff = 30 * time.Second | ||
| ) | ||
|
|
||
| // backoff handles exponential backoff with jitter | ||
| type backoff struct { | ||
| current time.Duration | ||
| } | ||
|
|
||
| // newBackoff creates a new backoff instance | ||
| func newBackoff() *backoff { | ||
| return &backoff{ | ||
| current: initialBackoff, | ||
| } | ||
| } | ||
|
|
||
| // next returns the next backoff duration and updates the current backoff | ||
| func (b *backoff) next() time.Duration { | ||
| // Add jitter between 0-1s | ||
| backoff := b.current + time.Duration(time.Now().UnixNano()%1e9) | ||
|
|
||
| // Double the backoff time, but cap it | ||
| if b.current < maxBackoff { | ||
| b.current *= 2 | ||
| } | ||
|
|
||
| return backoff | ||
| } | ||
|
|
||
| // reset resets the backoff to initial value | ||
| func (b *backoff) reset() { | ||
| b.current = initialBackoff | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package flagsmith | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| ) | ||
|
|
||
| func TestBackoff(t *testing.T) { | ||
| // Given | ||
| b := newBackoff() | ||
|
|
||
| // When | ||
| first := b.next() | ||
| second := b.next() | ||
| third := b.next() | ||
|
|
||
| // Then | ||
| assert.LessOrEqual(t, third, maxBackoff, "Backoff should not exceed max") | ||
|
|
||
| // Backoff increases across attempts | ||
| assert.Greater(t, second, first, "Second backoff should be greater than the first") | ||
| assert.Greater(t, third, second, "Third backoff should be greater than the second") | ||
| } | ||
|
|
||
| func TestBackoffReset(t *testing.T) { | ||
| b := newBackoff() | ||
| assert.Greater(t, b.next(), initialBackoff) | ||
| b.reset() | ||
| assert.Equal(t, initialBackoff, b.current, "Reset should return to initial backoff") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,7 @@ import ( | |
| "fmt" | ||
| "log/slog" | ||
| "strings" | ||
| "sync" | ||
| "sync/atomic" | ||
| "time" | ||
|
|
||
|
|
@@ -30,6 +31,7 @@ type Client struct { | |
| identitiesWithOverrides atomic.Value | ||
|
|
||
| analyticsProcessor *AnalyticsProcessor | ||
| realtime *realtime | ||
| defaultFlagHandler func(string) (Flag, error) | ||
|
|
||
| client *resty.Client | ||
|
|
@@ -38,6 +40,8 @@ type Client struct { | |
| log *slog.Logger | ||
| offlineHandler OfflineHandler | ||
| errorHandler func(handler *FlagsmithAPIError) | ||
|
|
||
| once sync.Once | ||
| } | ||
|
|
||
| // Returns context with provided EvaluationContext instance set. | ||
|
|
@@ -71,9 +75,12 @@ func NewClient(apiKey string, options ...Option) *Client { | |
| opt(c) | ||
| } | ||
| } | ||
| c.client.SetLogger(newSlogToRestyAdapter(c.log)) | ||
| c.client = c.client. | ||
| SetLogger(newSlogToRestyAdapter(c.log)). | ||
| OnBeforeRequest(newRestyLogRequestMiddleware(c.log)). | ||
| OnAfterResponse(newRestyLogResponseMiddleware(c.log)) | ||
|
|
||
| c.log.Debug("initialising Flagsmith client", | ||
| c.log.Info("initialising Flagsmith client", | ||
| "base_url", c.config.baseURL, | ||
| "local_evaluation", c.config.localEvaluation, | ||
| "offline", c.config.offlineMode, | ||
|
|
@@ -101,11 +108,15 @@ func NewClient(apiKey string, options ...Option) *Client { | |
| if !strings.HasPrefix(apiKey, "ser.") { | ||
| panic("In order to use local evaluation, please generate a server key in the environment settings page.") | ||
| } | ||
| if c.config.polling || !c.config.useRealtime { | ||
| // Poll indefinitely | ||
| go c.pollEnvironment(c.ctxLocalEval, true) | ||
| } | ||
| if c.config.useRealtime { | ||
| go c.startRealtimeUpdates(c.ctxLocalEval) | ||
| } else { | ||
| go c.pollEnvironment(c.ctxLocalEval) | ||
| // Poll until we get the environment once | ||
| go c.pollEnvironment(c.ctxLocalEval, false) | ||
| } | ||
|
|
||
| } | ||
| // Initialise analytics processor | ||
| if c.config.enableAnalytics { | ||
|
|
@@ -333,26 +344,42 @@ func (c *Client) getEnvironmentFlagsFromEnvironment() (Flags, error) { | |
| ), nil | ||
| } | ||
|
|
||
| func (c *Client) pollEnvironment(ctx context.Context) { | ||
| func (c *Client) pollEnvironment(ctx context.Context, pollForever bool) { | ||
| log := c.log.With(slog.String("worker", "poll")) | ||
| update := func() { | ||
| log.Debug("polling environment") | ||
| ctx, cancel := context.WithTimeout(ctx, c.config.envRefreshInterval) | ||
| defer cancel() | ||
| err := c.UpdateEnvironment(ctx) | ||
| if err != nil { | ||
| c.log.Error("failed to update environment", "error", err) | ||
| log.Error("failed to update environment", "error", err) | ||
| } | ||
| } | ||
| update() | ||
| ticker := time.NewTicker(c.config.envRefreshInterval) | ||
| defer func() { | ||
| ticker.Stop() | ||
| log.Info("polling stopped") | ||
| }() | ||
| for { | ||
| select { | ||
| case <-ticker.C: | ||
| if !pollForever { | ||
| // Check if environment was successfully fetched | ||
| if _, ok := c.environment.Load().(*environments.EnvironmentModel); ok { | ||
| if !pollForever { | ||
| c.log.Debug("environment initialised") | ||
| return | ||
| } | ||
| } | ||
| } | ||
| update() | ||
| case <-ctx.Done(): | ||
| return | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func (c *Client) UpdateEnvironment(ctx context.Context) error { | ||
| var env environments.EnvironmentModel | ||
| resp, err := c.client.NewRequest(). | ||
|
|
@@ -385,6 +412,14 @@ func (c *Client) UpdateEnvironment(ctx context.Context) error { | |
| c.identitiesWithOverrides.Store(identitiesWithOverrides) | ||
|
|
||
| c.log.Info("environment updated", "environment", env.APIKey) | ||
| c.once.Do(func() { | ||
| if c.config.useRealtime && c.realtime == nil { | ||
|
||
| streamURL := c.config.realtimeBaseUrl + "sse/environments/" + env.APIKey + "/stream" | ||
| c.realtime = newRealtime(c, c.ctxLocalEval, streamURL, env.UpdatedAt) | ||
| c.log.Debug("environment initialised, starting realtime updates") | ||
| go c.realtime.start() | ||
| } | ||
| }) | ||
| return nil | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be moved to
real-timemodule/package; pollEnvironment should not be responsible for this