:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(integrations): cache resolved slack channels for name search (#104110)
Daniel Marchuk419bfbe4e9c0
diff --git a/docs/internal/slack-local-setup-guide.md b/docs/internal/slack-local-setup-guide.mdindex 0d99afc13298..c4232078734a 100644--- a/docs/internal/slack-local-setup-guide.md+++ b/docs/internal/slack-local-setup-guide.md@@ -307,6 +307,15 @@ Tokens from the development app cannot be transferred to the production app.lines, and Slack's app **Event Deliveries** page shows delivery failures — neither was needed inour run, but they're there if you get stuck.+### Channel search cache++Channel name search uses the cached channel list.+If name search does not find a channel, paste its ID to look it up directly in Slack.+A successful ID lookup also adds the channel to an existing search cache with the same access scope.+Concurrent ID lookups keep both channels in the cache.+The update keeps the cache refresh time and expiry.+It does not load other missing channels or create a channel list from a single lookup.+## Troubleshooting### Channel selectiondiff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 0176de84f98a..fce891e2ec6b 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -7,7 +7,7 @@ from typing import Any, NoReturn, Protocol, castfrom urllib.parse import urlencodefrom django.conf import settings-from django.core.cache import cache+from django.core.cache import cache, cachesfrom django.db import transactionfrom django.db.models import Q, QuerySetfrom django.http import HttpResponse@@ -17,8 +17,11 @@ from django.utils.dateparse import parse_datetimeimport structlogfrom django_filters.rest_framework import DjangoFilterBackend+from django_redis.cache import RedisCache+from django_redis.exceptions import ConnectionInterruptedfrom drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_serializerfrom prometheus_client import Counter+from redis.exceptions import RedisErrorfrom rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.exceptions import APIException, PermissionDenied, Throttled, ValidationErrorfrom rest_framework.permissions import BasePermission, IsAuthenticated@@ -1495,6 +1498,42 @@ class IntegrationViewSet("is_private_without_access": channel.get("is_private_without_access", False),}+ @staticmethod+ def _cache_slack_channel(key: str, channel: dict) -> None:+ backend = caches["default"]+ if not isinstance(backend, RedisCache):+ return+ try:+ client = backend.client+ redis_client = client.get_client(write=True)+ redis_key = client.make_key(key)+ for _ in range(5):+ previous = redis_client.get(redis_key)+ if previous is None or redis_client.pttl(redis_key) <= 0:+ return+ data = client.decode(previous)+ channels_by_id = {item["id"]: item for item in data["channels"]}+ channels_by_id[channel["id"]] = channel+ updated = client.encode({**data, "channels": list(channels_by_id.values())})+ # Compare the encoded value so concurrent lookups and list refreshes cannot lose writes.+ if redis_client.eval(+ """+ if redis.call('GET', KEYS[1]) == ARGV[1] and redis.call('PTTL', KEYS[1]) > 0 then+ return redis.call('SET', KEYS[1], ARGV[2], 'XX', 'KEEPTTL')+ end+ return false+ """,+ 1,+ redis_key,+ previous,+ updated,+ ):+ return+ except (ConnectionInterrupted, RedisError, OSError):+ # The caller already resolved the channel, so a Redis failure here must not turn a+ # successful lookup into a 500. The next list refresh rebuilds the cache.+ logger.warning("slack_channel_cache_update_failed", cache_key=key, exc_info=True)+@staticmethoddef _filter_slack_channels_for_search(channels: list[dict], search: str) -> list[dict]:visible = [channel for channel in channels if not channel.get("is_private_without_access")]@@ -1545,7 +1584,9 @@ class IntegrationViewSet(except SlackApiError as e:_reraise_slack_api_error(e)if channel:- return Response({"channels": [self._serialize_slack_channel(channel)]})+ serialized_channel = self._serialize_slack_channel(channel)+ self._cache_slack_channel(key, serialized_channel)+ return Response({"channels": [serialized_channel]})return Response({"channels": []})query_serializer = SlackChannelsQuerySerializer(data=request.query_params)diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex c8d74d91ca1a..8aa6beb10f03 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -3,12 +3,14 @@ import jsonimport timeimport hashlibfrom datetime import timedelta+from typing import Any, castfrom urllib.parse import quote, urlencodeimport pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import ANY, MagicMock, patch+from django.conf import settingsfrom django.core.cache import cachefrom django.db import connectionfrom django.test import override_settings@@ -17,8 +19,10 @@ from django.test.utils import CaptureQueriesContextfrom django.utils import timezoneimport requests+from fakeredis import FakeConnectionfrom parameterized import parameterizedfrom prometheus_client import REGISTRY+from redis.exceptions import RedisErrorfrom rest_framework import statusfrom rest_framework.exceptions import ValidationErrorfrom slack_sdk.errors import SlackApiError@@ -2282,6 +2286,113 @@ class TestIntegrationAPIKeyAccess:mock_slack_instance.list_channels.assert_called_once()+ @pytest.mark.parametrize("owns_integration", [True, False])+ @pytest.mark.parametrize(+ "cache_state",+ [+ "present",+ "missing",+ "expires_during_lookup",+ "concurrent_lookup",+ "expires_during_merge",+ "redis_error_during_merge",+ ],+ )+ @override_settings(+ CACHES={+ **settings.CACHES,+ "default": {+ "BACKEND": "django_redis.cache.RedisCache",+ "LOCATION": "redis://slack-channel-cache-test:6379/0",+ "OPTIONS": {"CONNECTION_POOL_KWARGS": {"connection_class": FakeConnection}},+ },+ }+ )+ @patch("posthog.api.integration.SlackIntegration")+ def test_channels_action_id_lookup_updates_existing_search_cache(+ self, mock_slack_class: MagicMock, owns_integration: bool, cache_state: str, client: HttpClient+ ) -> None:+ integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T_CACHE_TEST",+ config={"authed_user": {"id": "test_user_id"}},+ sensitive_config={"access_token": "test-token"},+ created_by=self.user if owns_integration else None,+ )+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value("test_key_slack_cache"),+ scopes=["integration:read"],+ )+ base_url = f"/api/environments/{self.team.pk}/integrations/{integration.id}/channels/"+ cache_key = f"slack/{integration.id}/{owns_integration}/channels"+ other_cache_key = f"slack/{integration.id}/{not owns_integration}/channels"+ cached_data = {"channels": [], "lastRefreshedAt": timezone.now().isoformat()}+ cache.set(other_cache_key, cached_data, 30)+ if cache_state != "missing":+ cache.set(cache_key, cached_data, 30)+ channel: dict[str, str | bool] = {+ "id": "C_CACHE_TEST",+ "name": "release-updates",+ "is_private": owns_integration,+ "is_member": True,+ "is_ext_shared": False,+ "is_private_without_access": False,+ }++ def resolve_channel(*args: object) -> dict[str, str | bool]:+ if cache_state == "expires_during_lookup":+ cache.delete(cache_key)+ return channel++ mock_slack_class.return_value.get_channel_by_id.side_effect = resolve_channel+ redis_client = cast(Any, cache).client.get_client(write=True)+ original_eval = redis_client.eval+ competing_channel = {**channel, "id": "C_OTHER", "name": "other-channel"}+ changed = False++ def merge_with_concurrent_write(*args: object) -> object:+ nonlocal changed+ if not changed:+ changed = True+ if cache_state == "concurrent_lookup":+ IntegrationViewSet._cache_slack_channel(cache_key, competing_channel)+ elif cache_state == "expires_during_merge":+ cache.delete(cache_key)+ elif cache_state == "redis_error_during_merge":+ raise RedisError("connection reset by peer")+ return original_eval(*args)++ with patch.object(redis_client, "eval", side_effect=merge_with_concurrent_write):+ response = client.get(+ base_url, {"channel_id": channel["id"]}, HTTP_AUTHORIZATION="Bearer test_key_slack_cache"+ )+ assert response.status_code == status.HTTP_200_OK+ resolved_channel = response.json()["channels"][0]+ assert resolved_channel["name"] == "release-updates"+ assert cache.get(other_cache_key) == cached_data+ mock_slack_class.return_value.get_channel_by_id.assert_called_once_with(+ channel["id"], owns_integration, "test_user_id"+ )++ if cache_state in ("present", "concurrent_lookup"):+ response = client.get(+ base_url, {"search": "release-updates"}, HTTP_AUTHORIZATION="Bearer test_key_slack_cache"+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["channels"] == [resolved_channel]+ assert response.json()["lastRefreshedAt"] == cached_data["lastRefreshedAt"]+ assert 0 < cast(Any, cache).ttl(cache_key) <= 30+ if cache_state == "concurrent_lookup":+ assert {item["id"] for item in cache.get(cache_key)["channels"]} == {channel["id"], "C_OTHER"}+ elif cache_state == "redis_error_during_merge":+ assert cache.get(cache_key) == cached_data+ else:+ assert cache.get(cache_key) is None+ mock_slack_class.return_value.list_channels.assert_not_called()+@pytest.mark.parametrize("query_string,expected_ids,expected_has_more",[