Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Stop the shared aiohttp session from keeping a cookie jar (#5685)

Dhruv Bhanushali6c333319c1e1
diff --git a/api/api/utils/aiohttp.py b/api/api/utils/aiohttp.py
index c3dacf1ba..43624b01a 100644
--- a/api/api/utils/aiohttp.py
+++ b/api/api/utils/aiohttp.py
@@ -72,7 +72,15 @@ async def get_aiohttp_session() -> aiohttp.ClientSession:
logger.info(msg)
if create_session:
- session = aiohttp.ClientSession(trace_configs=[LogTiming()])
+ # The default `CookieJar` leaks: `filter_cookies` is called for
+ # every request and, once the jar holds a single cookie, inserts an
+ # empty entry for each (domain, path) pair of the URL it has never
+ # seen (aiohttp < 3.12.3). Dead-link checks and thumbnails request
+ # millions of distinct provider URLs and never need cookies.
+ session = aiohttp.ClientSession(
+ cookie_jar=aiohttp.DummyCookieJar(),
+ trace_configs=[LogTiming()],
+ )
_SESSIONS[loop] = session
return _SESSIONS[loop]
diff --git a/api/test/unit/utils/test_aiohttp.py b/api/test/unit/utils/test_aiohttp.py
index 24e16bea9..071fe34d7 100644
--- a/api/test/unit/utils/test_aiohttp.py
+++ b/api/test/unit/utils/test_aiohttp.py
@@ -1,8 +1,10 @@
import asyncio
+from http.cookies import SimpleCookie
import aiohttp
import pytest
from structlog.testing import capture_logs
+from yarl import URL
from api.utils.aiohttp import get_aiohttp_session
@@ -16,6 +18,26 @@ def test_reuses_session_within_same_loop(get_new_loop):
assert session_1 is session_2
+def test_session_does_not_keep_cookies(get_new_loop):
+ """
+ The default ``CookieJar`` grows by one empty entry per (domain, path)
+ prefix of every URL looked up once it holds any cookie, which leaked
+ ~200 MB/day per task in production.
+ """
+ loop = get_new_loop()
+
+ session = loop.run_until_complete(get_aiohttp_session())
+ session.cookie_jar.update_cookies(
+ SimpleCookie("session=1; Domain=example.com; Path=/"),
+ URL("https://example.com/"),
+ )
+ for i in range(50):
+ session.cookie_jar.filter_cookies(URL(f"https://cdn.example.org/a/b/{i}.jpg"))
+
+ assert isinstance(session.cookie_jar, aiohttp.DummyCookieJar)
+ assert len(session.cookie_jar) == 0
+
+
def test_creates_new_session_for_separate_loops(get_new_loop):
loop_1 = get_new_loop()
loop_2 = get_new_loop()