Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add native gzip support to the core (#11833)

Patryk Zawadzki95623d165d25
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5cb3783e04..6bcaa6ef17 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,7 @@ All notable, unreleased changes to this project will be documented in this file.
- `PRODUCT_MEDIA_DELETED`
- `THUMBNAIL_CREATED`
- CORS is now handled in the ASGI layer - #11415 by @patrys
+- Added native support for gzip compression - #11833 by @patrys
# 3.11.0
diff --git a/saleor/asgi/__init__.py b/saleor/asgi/__init__.py
index 3c181c0229..44df76bfd7 100644
--- a/saleor/asgi/__init__.py
+++ b/saleor/asgi/__init__.py
@@ -10,11 +10,13 @@ import os
from django.core.asgi import get_asgi_application
-from saleor.asgi.cors_handler import cors_handler
-from saleor.asgi.health_check import health_check
+from .cors_handler import cors_handler
+from .gzip_compression import gzip_compression
+from .health_check import health_check
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saleor.settings")
application = get_asgi_application()
application = health_check(application, "/health/") # type: ignore[arg-type] # Django's ASGI app is less strict than the spec # noqa: E501
+application = gzip_compression(application)
application = cors_handler(application)
diff --git a/saleor/asgi/gzip_compression.py b/saleor/asgi/gzip_compression.py
new file mode 100644
index 0000000000..96fb1a43f7
--- /dev/null
+++ b/saleor/asgi/gzip_compression.py
@@ -0,0 +1,146 @@
+# adapted from Starlette's GZipMiddleware
+# Starlette does not work with Django's case-sensitive headers
+
+import gzip
+import io
+from typing import Optional
+
+from asgiref.typing import (
+ ASGI3Application,
+ ASGIReceiveCallable,
+ ASGISendCallable,
+ ASGISendEvent,
+ HTTPResponseStartEvent,
+ Scope,
+)
+
+
+def gzip_compression(
+ app: ASGI3Application, minimum_size: int = 500, compresslevel: int = 9
+) -> ASGI3Application:
+ async def gzip_compression_wrapper(
+ scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
+ ) -> None:
+ if scope["type"] == "http":
+ accepted_encoding = next(
+ (
+ value
+ for key, value in scope["headers"]
+ if key.lower() == b"accept-encoding"
+ ),
+ b"",
+ )
+ if b"gzip" in accepted_encoding:
+ start_message: Optional[HTTPResponseStartEvent] = None
+ content_encoding_set = False
+ started = False
+ gzip_buffer = io.BytesIO()
+ gzip_file = gzip.GzipFile(
+ mode="wb", fileobj=gzip_buffer, compresslevel=compresslevel
+ )
+
+ async def send_compressed(message: ASGISendEvent) -> None:
+ nonlocal content_encoding_set
+ nonlocal start_message
+ nonlocal started
+ if message["type"] == "http.response.start":
+ start_message = message
+ headers = start_message["headers"]
+ content_encoding_set = any(
+ value
+ for key, value in headers
+ if key.lower() == b"content-encoding"
+ )
+ elif (
+ message["type"] == "http.response.body" and content_encoding_set
+ ):
+ if not started:
+ assert start_message is not None
+ started = True
+ await send(start_message)
+ await send(message)
+ elif message["type"] == "http.response.body" and not started:
+ assert start_message is not None
+ started = True
+ body = message.get("body", b"")
+ more_body = message.get("more_body", False)
+ if len(body) < minimum_size and not more_body:
+ # Don't apply GZip to small outgoing responses.
+ await send(start_message)
+ await send(message)
+ elif not more_body:
+ # Standard GZip response.
+ gzip_file.write(body)
+ gzip_file.close()
+ body = gzip_buffer.getvalue()
+
+ headers = start_message["headers"]
+ headers = [
+ (key, value)
+ for key, value in headers
+ if key.lower()
+ not in (b"content-length", b"content-encoding")
+ ]
+ headers.append((b"content-encoding", b"gzip"))
+ headers.append(
+ (
+ b"content-length",
+ str(len(body)).encode("latin-1"),
+ )
+ )
+ for key, value in headers:
+ if key.lower() == b"vary":
+ if b"Accept-Encoding" not in value:
+ value += b", Accept-Encoding"
+ break
+ start_message["headers"] = headers
+
+ message["body"] = body
+
+ await send(start_message)
+ await send(message)
+ else:
+ # Initial body in streaming GZip response.
+ headers = start_message["headers"]
+ headers = [
+ (key, value)
+ for key, value in headers
+ if key.lower()
+ not in (b"content-length", b"content-encoding")
+ ]
+ headers.append((b"content-encoding", b"gzip"))
+ for key, value in headers:
+ if key.lower() == b"vary":
+ if b"Accept-Encoding" not in value:
+ value += b", Accept-Encoding"
+ break
+ start_message["headers"] = headers
+
+ gzip_file.write(body)
+ message["body"] = gzip_buffer.getvalue()
+ gzip_buffer.seek(0)
+ gzip_buffer.truncate()
+
+ await send(start_message)
+ await send(message)
+
+ elif message["type"] == "http.response.body":
+ # Remaining body in streaming GZip response.
+ body = message.get("body", b"")
+ more_body = message.get("more_body", False)
+
+ gzip_file.write(body)
+ if not more_body:
+ gzip_file.close()
+
+ message["body"] = gzip_buffer.getvalue()
+ gzip_buffer.seek(0)
+ gzip_buffer.truncate()
+
+ await send(message)
+
+ await app(scope, receive, send_compressed)
+ return
+ await app(scope, receive, send)
+
+ return gzip_compression_wrapper
diff --git a/saleor/asgi/tests/conftest.py b/saleor/asgi/tests/conftest.py
index e6ed224cf8..a7db99a13e 100644
--- a/saleor/asgi/tests/conftest.py
+++ b/saleor/asgi/tests/conftest.py
@@ -19,6 +19,7 @@ def asgi_app() -> ASGI3Application:
type="http.response.start",
status=200,
headers=[(b"content-type", b"text/plain")],
+ trailers=False,
)
)
await send(
@@ -26,3 +27,28 @@ def asgi_app() -> ASGI3Application:
)
return fake_app
+
+
+def large_asgi_app() -> ASGI3Application:
+ async def fake_app(
+ scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
+ ) -> None:
+ await send(
+ HTTPResponseStartEvent(
+ type="http.response.start",
+ status=200,
+ headers=[
+ (b"content-length", b"10000"),
+ (b"content-type", b"text/plain"),
+ ],
+ trailers=False,
+ )
+ )
+ await send(
+ HTTPResponseBodyEvent(
+ type="http.response.body", body=10000 * b"x", more_body=False
+ )
+ )
+
+ return fake_app
diff --git a/saleor/asgi/tests/test_gzip.py b/saleor/asgi/tests/test_gzip.py
new file mode 100644
index 0000000000..d7a764358c
--- /dev/null
+++ b/saleor/asgi/tests/test_gzip.py
@@ -0,0 +1,89 @@
+import gzip
+from typing import List
+
+from asgiref.typing import (
+ ASGI3Application,
+ ASGIReceiveEvent,
+ HTTPResponseBodyEvent,
+ HTTPResponseStartEvent,
+ HTTPScope,
+)
+
+from ..gzip_compression import gzip_compression
+
+
+def build_scope(origin: str, encodings: bytes) -> HTTPScope:
+ return {
+ "type": "http",
+ "asgi": {"spec_version": "2.1", "version": "3.0"},
+ "http_version": "2",
+ "method": "OPTIONS",
+ "scheme": "https",
+ "path": "/",
+ "raw_path": b"/",
+ "query_string": b"",
+ "root_path": "",
+ "headers": [
+ (b"accept-encoding", encodings),
+ (b"hostname", b"localhost:3000"),
+ (b"origin", origin.encode("latin1")),
+ ],
+ "client": ("127.0.0.1", 80),
+ "server": None,
+ "extensions": {},
+ }
+
+
+async def run_app(app: ASGI3Application, scope: HTTPScope) -> List[dict]:
+ events = []
+
+ async def send(event) -> None:
+ events.append(event)
+
+ async def receive() -> ASGIReceiveEvent:
+ raise NotImplementedError()
+
+ await app(scope, receive, send)
+ return events
+
+
+async def test_no_compression(large_asgi_app: ASGI3Application, settings):
+ settings.ALLOWED_GRAPHQL_ORIGINS = ["*"]
+ cors_app = gzip_compression(large_asgi_app)
+ events = await run_app(cors_app, build_scope("http://localhost:3000", b"identity"))
+ assert events == [
+ HTTPResponseStartEvent(
+ type="http.response.start",
+ status=200,
+ headers=[
+ (b"content-length", b"10000"),
+ (b"content-type", b"text/plain"),
+ ],
+ trailers=False,
+ ),
+ HTTPResponseBodyEvent(
+ type="http.response.body", body=10000 * b"x", more_body=False
+ ),
+ ]
+
+
+async def test_with_supported_compression(large_asgi_app: ASGI3Application, settings):
+ settings.ALLOWED_GRAPHQL_ORIGINS = ["*"]
+ cors_app = gzip_compression(large_asgi_app)
+ events = await run_app(cors_app, build_scope("http://localhost:3000", b"gzip"))
+ expected_payload = gzip.compress(10000 * b"x", compresslevel=9)
+ assert events == [
+ HTTPResponseStartEvent(
+ type="http.response.start",
+ status=200,
+ headers=[
+ (b"content-type", b"text/plain"),
+ (b"content-encoding", b"gzip"),
+ (b"content-length", str(len(expected_payload)).encode("latin1")),
+ ],
+ trailers=False,
+ ),
+ HTTPResponseBodyEvent(
+ type="http.response.body", body=expected_payload, more_body=False
+ ),
+ ]