Skip to content
Draft
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/remote-config-payload-second-decode.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: patch
---

`get_remote_config_payload()` now returns the decoded payload when the endpoint answers with a JSON string holding the payload's JSON text, instead of returning that text. A decoded string is parsed as JSON once more, and a string that is not JSON comes back unchanged. The same applies to `AsyncClient.get_remote_config_payload()`. Callers that worked around this with their own `json.loads()` on the returned string should drop it.
3 changes: 2 additions & 1 deletion posthog/_async_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
QuotaLimitError,
USER_AGENT,
normalize_host,
_decode_remote_config_payload,
_remote_config_path,
)
from .utils import remove_trailing_slash
Expand Down Expand Up @@ -114,7 +115,7 @@ async def async_flags(

def _process_remote_config_response(response: Any) -> Any:
_process_response(response)
return response.json()
return _decode_remote_config_payload(response.json())


async def async_remote_config(
Expand Down
16 changes: 15 additions & 1 deletion posthog/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,20 @@ def _remote_config_path(key: str) -> str:
return f"/api/projects/@current/feature_flags/{quote(key, safe='')}/remote_config"


def _decode_remote_config_payload(data: Any) -> Any:
"""Decode the second layer of a remote config response.

The endpoint answers with a JSON string holding the payload's JSON text, so a
decoded string is parsed once more. A string that is not JSON is returned as is.
"""
if not isinstance(data, str):
return data
try:
return json.loads(data)
except ValueError:
return data


def remote_config(
personal_api_key: str,
project_api_key: str,
Expand All @@ -399,7 +413,7 @@ def remote_config(
host,
timeout,
)
return response.data
return _decode_remote_config_payload(response.data)


def get(
Expand Down
68 changes: 68 additions & 0 deletions posthog/test/test_remote_config_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,71 @@ def test_remote_config_rejects_empty_and_dot_segments(
"configured": True
}
assert len(requests) == 1


@pytest.fixture
def remote_config_body_server():
state = {"body": b"{}"}

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
body = state["body"]
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)

def log_message(self, *args):
pass

server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(
target=lambda: server.serve_forever(poll_interval=0.01), daemon=True
)
thread.start()
try:
yield f"http://127.0.0.1:{server.server_port}", state
finally:
server.shutdown()
server.server_close()
thread.join()


@pytest.mark.parametrize("client_type", ["sync", "async"])
@pytest.mark.parametrize(
"body, payload",
[
("{}", {}),
('{"foo":["bar","baz"]}', {"foo": ["bar", "baz"]}),
('"{ \\"foo\\":[\\"bar\\",\\"baz\\"]}"', {"foo": ["bar", "baz"]}),
('"[1,2]"', [1, 2]),
('"123"', 123),
('["{\\"a\\":1}"]', ['{"a":1}']),
],
)
def test_remote_config_body_decodes_to_the_payload(
remote_config_body_server, client_type, body, payload
):
host, state = remote_config_body_server
state["body"] = body.encode()

assert read_payload(client_type, host, "test-flag") == payload


@pytest.mark.parametrize("client_type", ["sync", "async"])
@pytest.mark.parametrize(
"body, payload",
[
('"hello world"', "hello world"),
('"{broken"', "{broken"),
('""', ""),
],
)
def test_remote_config_string_that_is_not_json_comes_back_unchanged(
remote_config_body_server, client_type, body, payload
):
host, state = remote_config_body_server
state["body"] = body.encode()

assert read_payload(client_type, host, "test-flag") == payload