-
Notifications
You must be signed in to change notification settings - Fork 68
feat: Support async flag definition cache providers #626
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
dustinbyrne
wants to merge
3
commits into
main
Choose a base branch
from
feat/async-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
3 commits
Select commit
Hold shift + click to select a range
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 @@ | ||
| --- | ||
| pypi/posthog: minor | ||
| --- | ||
|
|
||
| Add async flag definition cache providers |
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,149 @@ | ||
| """ | ||
| Async Redis-based distributed cache for PostHog feature flag definitions. | ||
|
|
||
| This example demonstrates how to implement a FlagDefinitionCacheProvider with | ||
| redis.asyncio for async-first applications. The PostHog SDK accepts async cache | ||
| provider methods and runs their awaitables to completion before continuing. | ||
|
|
||
| Usage: | ||
| import redis.asyncio as redis | ||
| from posthog import Posthog | ||
|
|
||
| # Use a Redis client dedicated to this cache provider. The SDK runs async | ||
| # provider methods on its own background event loop. | ||
| redis_client = redis.Redis(host="localhost", port=6379, decode_responses=True) | ||
| cache = AsyncRedisFlagCache(redis_client, service_key="my-service") | ||
|
|
||
| posthog = Posthog( | ||
| "<project_api_key>", | ||
| personal_api_key="<personal_api_key>", | ||
| flag_definition_cache_provider=cache, | ||
| ) | ||
|
|
||
| Requirements: | ||
| pip install redis | ||
| """ | ||
|
|
||
| import json | ||
| import uuid | ||
| from typing import Optional | ||
|
|
||
| from posthog import FlagDefinitionCacheData, FlagDefinitionCacheProvider | ||
| from redis.asyncio import Redis | ||
|
|
||
|
|
||
| class AsyncRedisFlagCache(FlagDefinitionCacheProvider): | ||
| """ | ||
| A distributed cache for PostHog feature flag definitions using redis.asyncio. | ||
|
|
||
| In a multi-instance deployment, only one instance should poll PostHog for | ||
| flag updates while all instances share the cached results. This prevents N | ||
| instances from making N redundant API calls. | ||
|
|
||
| The implementation uses leader election: | ||
| - One instance "wins" and becomes responsible for fetching | ||
| - Other instances read from the shared cache | ||
| - If the leader dies, the lock expires and another instance takes over | ||
|
|
||
| Uses Lua scripts for atomic operations, following Redis distributed lock best | ||
| practices: https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/ | ||
| """ | ||
|
|
||
| LOCK_TTL_MS = 60 * 1000 # 60 seconds, should be longer than the flags poll interval | ||
| CACHE_TTL_SECONDS = 60 * 60 * 24 # 24 hours | ||
|
|
||
| # Lua script: acquire lock if free, or extend if we own it | ||
| _LUA_TRY_LEAD = """ | ||
| local current = redis.call('GET', KEYS[1]) | ||
| if current == false then | ||
| redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2]) | ||
| return 1 | ||
| elseif current == ARGV[1] then | ||
| redis.call('PEXPIRE', KEYS[1], ARGV[2]) | ||
| return 1 | ||
| end | ||
| return 0 | ||
| """ | ||
|
|
||
| # Lua script: release lock only if we own it | ||
| _LUA_STOP_LEAD = """ | ||
| if redis.call('GET', KEYS[1]) == ARGV[1] then | ||
| return redis.call('DEL', KEYS[1]) | ||
| end | ||
| return 0 | ||
| """ | ||
|
|
||
| def __init__(self, redis: Redis, service_key: str): | ||
| """ | ||
| Initialize the async Redis flag cache. | ||
|
|
||
| Args: | ||
| redis: A redis.asyncio client instance dedicated to this cache provider. | ||
| The SDK runs async provider methods on its own background event | ||
| loop, so avoid sharing the same asyncio Redis client with a | ||
| different application event loop. Configure decode_responses=True | ||
| for string responses, or bytes responses will be decoded here. | ||
| service_key: A unique identifier for this service/environment. | ||
| Used to scope Redis keys, allowing multiple services | ||
| or environments to share the same Redis instance. | ||
| """ | ||
| self._redis = redis | ||
| self._cache_key = f"posthog:flags:{service_key}" | ||
| self._lock_key = f"posthog:flags:{service_key}:lock" | ||
| self._instance_id = str(uuid.uuid4()) | ||
|
|
||
| async def get_flag_definitions(self) -> Optional[FlagDefinitionCacheData]: | ||
| """ | ||
| Retrieve cached flag definitions from Redis. | ||
|
|
||
| Returns: | ||
| Cached flag definitions if available, None otherwise. | ||
| """ | ||
| cached = await self._redis.get(self._cache_key) | ||
| if not cached: | ||
| return None | ||
| if isinstance(cached, bytes): | ||
| cached = cached.decode("utf-8") | ||
| return json.loads(cached) | ||
|
|
||
| async def should_fetch_flag_definitions(self) -> bool: | ||
| """ | ||
| Determines if this instance should fetch flag definitions from PostHog. | ||
|
|
||
| Atomically either: | ||
| - Acquires the lock if no one holds it, OR | ||
| - Extends the lock TTL if we already hold it | ||
|
|
||
| Returns: | ||
| True if this instance is the leader and should fetch, False otherwise. | ||
| """ | ||
| result = await self._redis.eval( | ||
| self._LUA_TRY_LEAD, | ||
| 1, | ||
| self._lock_key, | ||
| self._instance_id, | ||
| self.LOCK_TTL_MS, | ||
| ) | ||
| return result == 1 | ||
|
|
||
| async def on_flag_definitions_received(self, data: FlagDefinitionCacheData) -> None: | ||
| """ | ||
| Store fetched flag definitions in Redis. | ||
|
|
||
| Args: | ||
| data: The flag definitions to cache. | ||
| """ | ||
| await self._redis.set( | ||
| self._cache_key, json.dumps(data), ex=self.CACHE_TTL_SECONDS | ||
| ) | ||
|
|
||
| async def shutdown(self) -> None: | ||
| """ | ||
| Release leadership if we hold it. Safe to call even if not the leader. | ||
| """ | ||
| await self._redis.eval( | ||
| self._LUA_STOP_LEAD, | ||
| 1, | ||
| self._lock_key, | ||
| self._instance_id, | ||
| ) |
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,85 @@ | ||
| import asyncio | ||
| import threading | ||
| from collections.abc import Awaitable | ||
| from typing import Any | ||
|
|
||
|
|
||
| class _BackgroundEventLoopRunner: | ||
| """Run awaitables to completion on a reusable background event loop.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self._loop: asyncio.AbstractEventLoop | None = None | ||
| self._thread: threading.Thread | None = None | ||
| self._started = threading.Event() | ||
| self._lock = threading.Lock() | ||
|
|
||
| def run(self, awaitable: Awaitable[Any]) -> Any: | ||
| loop = self._ensure_loop() | ||
| future = asyncio.run_coroutine_threadsafe(self._await_result(awaitable), loop) | ||
| return future.result() | ||
|
|
||
| def close(self) -> None: | ||
| with self._lock: | ||
| loop = self._loop | ||
| thread = self._thread | ||
| self._loop = None | ||
| self._thread = None | ||
|
|
||
| if loop is None or thread is None or loop.is_closed(): | ||
| return | ||
|
|
||
| if thread is threading.current_thread(): | ||
| loop.call_soon(loop.stop) | ||
| return | ||
|
|
||
| loop.call_soon_threadsafe(loop.stop) | ||
| thread.join() | ||
|
|
||
| @staticmethod | ||
| async def _await_result(awaitable: Awaitable[Any]) -> Any: | ||
| return await awaitable | ||
|
|
||
| def _ensure_loop(self) -> asyncio.AbstractEventLoop: | ||
| with self._lock: | ||
| if ( | ||
| self._loop is not None | ||
| and self._thread is not None | ||
| and self._thread.is_alive() | ||
| and not self._loop.is_closed() | ||
| ): | ||
| return self._loop | ||
|
|
||
| self._started.clear() | ||
| self._thread = threading.Thread( | ||
| target=self._run_loop, | ||
| name="PostHogBackgroundEventLoopRunner", | ||
| daemon=True, | ||
| ) | ||
| self._thread.start() | ||
|
|
||
| self._started.wait() | ||
| with self._lock: | ||
| assert self._loop is not None | ||
| return self._loop | ||
|
|
||
| def _run_loop(self) -> None: | ||
| loop = asyncio.new_event_loop() | ||
| asyncio.set_event_loop(loop) | ||
| with self._lock: | ||
| self._loop = loop | ||
| self._started.set() | ||
|
|
||
| try: | ||
| loop.run_forever() | ||
| finally: | ||
| pending = asyncio.all_tasks(loop) | ||
| for task in pending: | ||
| task.cancel() | ||
| if pending: | ||
| loop.run_until_complete( | ||
| asyncio.gather(*pending, return_exceptions=True) | ||
| ) | ||
| loop.run_until_complete(loop.shutdown_asyncgens()) | ||
| loop.run_until_complete(loop.shutdown_default_executor()) | ||
| asyncio.set_event_loop(None) | ||
| loop.close() |
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.