Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions .sampo/changesets/flags-uuid-request-body.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
posthog: patch
---

Serialize UUID values in feature flag request bodies instead of failing the evaluation, so a UUID distinct id, group key, or flag property reaches the flags service.
3 changes: 3 additions & 0 deletions posthog/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from gzip import GzipFile
from io import BytesIO
from typing import Any, List, Optional, Tuple, Union, cast
from uuid import UUID

import requests
from requests.adapters import HTTPAdapter
Expand Down Expand Up @@ -514,6 +515,8 @@ class DatetimeSerializer(json.JSONEncoder):
def default(self, obj: Any):
if isinstance(obj, (date, datetime)):
return obj.isoformat()
if isinstance(obj, UUID):
return str(obj)

return json.JSONEncoder.default(self, obj)

Expand Down
23 changes: 23 additions & 0 deletions posthog/test/test_async_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import subprocess
import sys
from unittest import mock
from uuid import UUID

import httpx
import pytest
Expand Down Expand Up @@ -252,6 +253,28 @@ async def test_async_flags_sends_v2_request_payload():
assert "Authorization" not in kwargs["headers"]


@pytest.mark.asyncio
async def test_async_flags_sends_uuid_inputs_as_strings():
client = FakeAsyncClient(FakeResponse(200, {"flags": {}}))
user_id = UUID("12345678-1234-5678-1234-567812345678")
company_id = UUID("87654321-4321-8765-4321-876543218765")

await async_flags(
"project-key",
"https://example.com",
timeout=3,
max_retries=0,
client=client,
distinct_id=user_id,
groups={"company": company_id},
)

_, _, kwargs = client.calls[0]
payload = json.loads(kwargs["content"])
assert payload["distinct_id"] == str(user_id)
assert payload["groups"] == {"company": str(company_id)}


@pytest.mark.asyncio
@pytest.mark.parametrize(
("transient_statuses", "expected_delays"),
Expand Down
32 changes: 32 additions & 0 deletions posthog/test/test_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import zlib
from datetime import date, datetime, timedelta
from unittest import mock
from uuid import UUID

import pytest
import requests
Expand Down Expand Up @@ -265,6 +266,11 @@ def test_date_serialization(self):
expected = '{"created": "%s"}' % today.isoformat()
self.assertEqual(result, expected)

def test_uuid_serialization(self):
data = {"id": UUID("12345678-1234-5678-1234-567812345678")}
result = json.dumps(data, cls=DatetimeSerializer)
self.assertEqual(result, '{"id": "12345678-1234-5678-1234-567812345678"}')

def test_should_not_timeout(self):
response = requests.Response()
response.status_code = 200
Expand Down Expand Up @@ -614,6 +620,32 @@ def test_flags_uses_flags_session(self, mock_get_flags_session):
mock_get_flags_session.assert_called_once()
mock_session.post.assert_called_once()

@mock.patch("posthog.request._get_flags_session")
def test_flags_sends_uuid_inputs_as_strings(self, mock_get_flags_session):
mock_response = requests.Response()
mock_response.status_code = 200
mock_response._content = json.dumps(
{"flags": {}, "errorsWhileComputingFlags": False}
).encode("utf-8")
mock_session = mock.MagicMock()
mock_session.post.return_value = mock_response
mock_get_flags_session.return_value = mock_session
user_id = UUID("12345678-1234-5678-1234-567812345678")
company_id = UUID("87654321-4321-8765-4321-876543218765")

flags(
"test-key",
"https://test.posthog.com",
distinct_id=user_id,
groups={"company": company_id},
person_properties={"account_id": user_id},
)

body = json.loads(mock_session.post.call_args.kwargs["data"])
self.assertEqual(body["distinct_id"], str(user_id))
self.assertEqual(body["groups"], {"company": str(company_id)})
self.assertEqual(body["person_properties"], {"account_id": str(user_id)})

@mock.patch("posthog.request._get_flags_session")
def test_flags_no_retry_on_quota_limit(self, mock_get_flags_session):
"""flags() raises QuotaLimitError without retrying (at application level)."""
Expand Down
Loading