-
Notifications
You must be signed in to change notification settings - Fork 38
feat(distributed-cache): Add distributed cache support #310
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
Open
avasenin
wants to merge
9
commits into
PostHog:main
Choose a base branch
from
avasenin:feat/flag-definition-cache-provider
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1490ada
Add cache support
avasenin 28c9163
fix(flags): address review of the flag definition cache provider
avasenin e6f1b02
style(flags): keep FlagDefinitionCacheData fields gofmt aligned
avasenin 1b3348f
docs(flags): trim the changeset and link the distributed environments…
avasenin 23c934b
test(flags): cover provider shutdown ordering and the close deadline
avasenin 08e36e0
refactor(flags): rename pollLoopDone to shutdownDone
avasenin 54d88da
refactor(examples): extract the instance count and drop redundant com…
avasenin 4496825
style(flags): use chan bool for shutdownDone like the other poller ch…
avasenin 72cd91d
style(flags): declare shutdownDone next to shutdown
avasenin 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,5 @@ | ||
| --- | ||
| "posthog-go": minor | ||
| --- | ||
|
|
||
| Add the experimental `FlagDefinitionCacheProvider` interface and the `Config.FlagDefinitionCacheProvider` option, for sharing local evaluation flag definitions across SDK instances. See [Distributed environments](https://posthog.com/docs/feature-flags/local-evaluation/distributed-environments). |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,205 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "os" | ||
| "path/filepath" | ||
| "strconv" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/google/uuid" | ||
| "github.com/posthog/posthog-go" | ||
| ) | ||
|
|
||
| // This example implements posthog.FlagDefinitionCacheProvider with a shared directory, | ||
| // so it runs without extra dependencies. A real deployment shares definitions across | ||
| // hosts, so use Redis or something like it there. | ||
|
|
||
| const ( | ||
| // Must be longer than the polling interval. | ||
| flagCacheLockTTL = 30 * time.Second | ||
| flagCachePollInterval = 3 * time.Second | ||
| flagCacheInstances = 2 | ||
| ) | ||
|
|
||
| // FileFlagCache shares flag definitions between processes on one machine through a | ||
| // directory: one file holds the definitions, another is the leader election lock. | ||
| type FileFlagCache struct { | ||
| dir string | ||
| name string | ||
| instanceID string | ||
| } | ||
|
|
||
| // NewFileFlagCache creates a provider for the given cache directory. Instances that | ||
| // share definitions pass the same directory and name. | ||
| func NewFileFlagCache(dir, name string) (*FileFlagCache, error) { | ||
| if err := os.MkdirAll(dir, 0o755); err != nil { | ||
| return nil, err | ||
| } | ||
| return &FileFlagCache{dir: dir, name: name, instanceID: uuid.NewString()}, nil | ||
| } | ||
|
|
||
| func (c *FileFlagCache) cachePath() string { return filepath.Join(c.dir, c.name+".json") } | ||
| func (c *FileFlagCache) lockPath() string { return filepath.Join(c.dir, c.name+".lock") } | ||
|
|
||
| // ShouldFetchFlagDefinitions elects a single instance to poll PostHog by holding a lock | ||
| // that expires. | ||
| // | ||
| // Read-then-write is not atomic on a filesystem, so two instances starting at the same | ||
| // moment can both take the lock. Redis with a Lua script does this atomically. | ||
| func (c *FileFlagCache) ShouldFetchFlagDefinitions(_ context.Context) (bool, error) { | ||
| holder, expiry, err := c.readLock() | ||
| if err != nil { | ||
| return false, err | ||
| } | ||
|
|
||
| heldByAnother := holder != "" && holder != c.instanceID | ||
| if heldByAnother && time.Now().Before(expiry) { | ||
| return false, nil | ||
| } | ||
|
|
||
| return true, c.writeLock() | ||
| } | ||
|
|
||
| func (c *FileFlagCache) GetFlagDefinitions(_ context.Context) (*posthog.FlagDefinitionCacheData, error) { | ||
| contents, err := os.ReadFile(c.cachePath()) | ||
| if errors.Is(err, os.ErrNotExist) { | ||
| return nil, nil | ||
| } else if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| var data posthog.FlagDefinitionCacheData | ||
| if err := json.Unmarshal(contents, &data); err != nil { | ||
| return nil, err | ||
| } | ||
| return &data, nil | ||
| } | ||
|
|
||
| // OnFlagDefinitionsReceived publishes definitions, writing to a temporary file and | ||
| // renaming it so that a reader never observes a half-written payload. | ||
| func (c *FileFlagCache) OnFlagDefinitionsReceived(_ context.Context, data posthog.FlagDefinitionCacheData) error { | ||
| encoded, err := json.Marshal(data) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| tmp, err := os.CreateTemp(c.dir, c.name+".*.tmp") | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer os.Remove(tmp.Name()) | ||
|
|
||
| if _, err := tmp.Write(encoded); err != nil { | ||
| tmp.Close() | ||
| return err | ||
| } | ||
| if err := tmp.Close(); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| fmt.Printf(" [%s] published %d flag definitions to the shared cache\n", c.shortID(), len(data.Flags)) | ||
| return os.Rename(tmp.Name(), c.cachePath()) | ||
| } | ||
|
|
||
| func (c *FileFlagCache) Shutdown(_ context.Context) error { | ||
| holder, _, err := c.readLock() | ||
| if err != nil || holder != c.instanceID { | ||
| return err | ||
| } | ||
| if err := os.Remove(c.lockPath()); err != nil && !errors.Is(err, os.ErrNotExist) { | ||
| return err | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func (c *FileFlagCache) readLock() (holder string, expiry time.Time, err error) { | ||
| contents, err := os.ReadFile(c.lockPath()) | ||
| if errors.Is(err, os.ErrNotExist) { | ||
| return "", time.Time{}, nil | ||
| } else if err != nil { | ||
| return "", time.Time{}, err | ||
| } | ||
|
|
||
| parts := strings.Fields(string(contents)) | ||
| if len(parts) != 2 { | ||
| return "", time.Time{}, nil | ||
| } | ||
| nanos, err := strconv.ParseInt(parts[1], 10, 64) | ||
| if err != nil { | ||
| return "", time.Time{}, nil | ||
| } | ||
| return parts[0], time.Unix(0, nanos), nil | ||
| } | ||
|
|
||
| func (c *FileFlagCache) writeLock() error { | ||
| expiry := time.Now().Add(flagCacheLockTTL).UnixNano() | ||
| return os.WriteFile(c.lockPath(), []byte(fmt.Sprintf("%s %d", c.instanceID, expiry)), 0o644) | ||
| } | ||
|
|
||
| func (c *FileFlagCache) shortID() string { return c.instanceID[:8] } | ||
|
|
||
| // TestFlagDefinitionCache runs several clients that share one flag definition cache. | ||
| func TestFlagDefinitionCache(projectAPIKey, secretKey, endpoint string) { | ||
| dir, err := os.MkdirTemp("", "posthog-flag-cache") | ||
| if err != nil { | ||
| fmt.Printf("❌ Could not create the cache directory: %v\n", err) | ||
| return | ||
| } | ||
| defer os.RemoveAll(dir) | ||
|
|
||
| fmt.Printf("%d instances sharing the cache in %s\n\n", flagCacheInstances, dir) | ||
|
|
||
| clients := make([]posthog.Client, 0, flagCacheInstances) | ||
| caches := make([]*FileFlagCache, 0, flagCacheInstances) | ||
|
|
||
| for i := 0; i < flagCacheInstances; i++ { | ||
| cache, err := NewFileFlagCache(dir, "my-service-production") | ||
| if err != nil { | ||
| fmt.Printf("❌ Could not create the cache provider: %v\n", err) | ||
| return | ||
| } | ||
|
|
||
| client, err := posthog.NewWithConfig(projectAPIKey, posthog.Config{ | ||
| Endpoint: endpoint, | ||
| SecretKey: secretKey, | ||
| DefaultFeatureFlagsPollingInterval: flagCachePollInterval, | ||
| FlagDefinitionCacheProvider: cache, | ||
| }) | ||
| if err != nil { | ||
| fmt.Printf("❌ Could not create the client: %v\n", err) | ||
| return | ||
| } | ||
|
|
||
| clients = append(clients, client) | ||
| caches = append(caches, cache) | ||
| fmt.Printf(" instance %s started\n", cache.shortID()) | ||
| } | ||
|
|
||
| defer func() { | ||
| for i, client := range clients { | ||
| if err := client.Close(); err != nil { | ||
| fmt.Printf(" [%s] close: %v\n", caches[i].shortID(), err) | ||
| } | ||
| } | ||
| }() | ||
|
|
||
| time.Sleep(2 * flagCachePollInterval) | ||
|
|
||
| fmt.Println("\nEvaluating flags on every instance, entirely from the shared definitions:") | ||
| for i, client := range clients { | ||
| flags, err := client.GetAllFlags(posthog.FeatureFlagPayloadNoKey{ | ||
| DistinctId: "distinct-id-of-your-user", | ||
| OnlyEvaluateLocally: true, | ||
| }) | ||
| if err != nil { | ||
| fmt.Printf(" [%s] %v\n", caches[i].shortID(), err) | ||
| continue | ||
| } | ||
| fmt.Printf(" [%s] evaluated %d flags locally\n", caches[i].shortID(), len(flags)) | ||
| } | ||
| } |
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.
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.
Uh oh!
There was an error while loading. Please reload this page.