Skip to content

: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.

fix(appsflyer): read report bodies through iter_content (#99343)

Tom Owers73ff3d28e3bc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py
index 1847908b7a80..991fce7956df 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py
@@ -1,9 +1,9 @@
import io
import re
import csv
-from collections.abc import Iterable, Iterator
+from collections.abc import Buffer, Iterable, Iterator
from datetime import UTC, date, datetime, timedelta
-from typing import IO, Any, cast
+from typing import Any
from urllib.parse import quote, urlencode
import requests
@@ -50,6 +50,8 @@ REQUEST_TIMEOUT_SECONDS = 300
MAX_RETRY_ATTEMPTS = 5
# Yield rows in chunks so huge reports don't build one giant list.
CHUNK_SIZE = 5000
+# Pull the report CSV off the wire in 64 KiB reads.
+REPORT_CHUNK_BYTES = 1 << 16
@frozen
@@ -58,6 +60,36 @@ class _ReportWindow:
end: date
+class _ResponseByteStream(io.RawIOBase):
+ """Read a streaming response body through ``iter_content`` as a binary file.
+
+ Wrapping ``response.raw`` directly crashes once the body is read: urllib3 closes
+ the raw stream as it reads the last byte, and a ``TextIOWrapper`` over the
+ now-closed stream raises ``ValueError: I/O operation on closed file`` instead of
+ reporting EOF. ``iter_content`` also turns a dropped connection into a retryable
+ ``requests`` error mid-stream.
+ """
+
+ def __init__(self, response: requests.Response, chunk_size: int) -> None:
+ self._chunks = response.iter_content(chunk_size=chunk_size)
+ self._buffer = b""
+
+ def readable(self) -> bool:
+ return True
+
+ def readinto(self, target: Buffer) -> int:
+ while not self._buffer:
+ try:
+ self._buffer = next(self._chunks)
+ except StopIteration:
+ return 0
+ view = memoryview(target).cast("B")
+ take = min(len(view), len(self._buffer))
+ view[:take] = self._buffer[:take]
+ self._buffer = self._buffer[take:]
+ return take
+
+
class AppsFlyerRetryableError(Exception):
pass
@@ -215,10 +247,11 @@ def _iter_report_rows(session: requests.Session, url: str, logger: FilteringBoun
response = _open_report(session, url, logger)
try:
# Read physical lines off the socket rather than buffering the whole body: a raw-data
- # window can hold a million event rows. Wrapping the stream (instead of `iter_lines`)
+ # window can hold a million event rows. Wrapping the byte stream (instead of `iter_lines`)
# keeps the line terminators csv needs for quoted multi-line values.
- response.raw.decode_content = True
- stream = io.TextIOWrapper(cast(IO[bytes], response.raw), encoding="utf-8", newline="")
+ stream = io.TextIOWrapper(
+ io.BufferedReader(_ResponseByteStream(response, REPORT_CHUNK_BYTES)), encoding="utf-8", newline=""
+ )
yield from _parse_csv_rows(stream, logger)
finally:
response.close()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
index fb8ac20c3552..cf1ed3009463 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
@@ -1,4 +1,5 @@
import io
+from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from urllib.parse import parse_qs, urlparse
@@ -41,15 +42,43 @@ _CSV = (
class _Raw(io.BytesIO):
- """Stands in for urllib3's raw stream, which the transport sets `decode_content` on."""
+ """Stands in for urllib3's raw stream, which the transport sets `decode_content` on.
+
+ urllib3 closes the stream on the read that satisfies Content-Length, so anything still
+ holding it open sees a closed file rather than EOF.
+ """
decode_content = False
+ def __init__(self, body: bytes) -> None:
+ super().__init__(body)
+ self._length = len(body)
+
+ def read(self, size: int | None = -1) -> bytes:
+ data = super().read(size)
+ if self.tell() >= self._length:
+ self.close()
+ return data
+
+ def read1(self, size: int | None = -1) -> bytes:
+ return self.read(size)
+
+
+def _iter_content(raw: _Raw, chunk_size: int) -> Iterator[bytes]:
+ """Mirrors `Response.iter_content`, which stops once the body is consumed."""
+ while not raw.closed:
+ chunk = raw.read(chunk_size)
+ if not chunk:
+ return
+ yield chunk
+
def _response(text: str, status: int = 200) -> mock.MagicMock:
resp = mock.MagicMock()
resp.text = text
- resp.raw = _Raw(text.encode())
+ raw = _Raw(text.encode())
+ resp.raw = raw
+ resp.iter_content = lambda chunk_size=8192, **kwargs: _iter_content(raw, chunk_size)
resp.status_code = status
resp.ok = status < 400
return resp
@@ -245,6 +274,20 @@ class TestGetRows:
headers = mock_session.call_args.kwargs["headers"]
assert headers["Accept"] == "text/csv"
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_report_spanning_several_reads_is_returned_whole(self, mock_session):
+ # urllib3 closes the raw stream as it reads the last byte of the body, so reading the
+ # report straight off it lost the report to `I/O operation on closed file` at EOF.
+ header = "Date,Media Source (pid)\n"
+ rows_sent = 4000
+ mock_session.return_value.get.side_effect = _serve(
+ header + "".join(f"2024-01-01,source-{index}\n" for index in range(rows_sent))
+ )
+
+ rows = [row for batch in get_rows("token", "id123", "daily_report", mock.MagicMock()) for row in batch]
+
+ assert [row["media_source_pid"] for row in rows] == [f"source-{index}" for index in range(rows_sent)]
+
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_empty_report_yields_nothing(self, mock_session):
mock_session.return_value.get.side_effect = _serve("Date,Media Source (pid)\n")