Skip to content

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

Introduce optional usage telemetry (#18789)

Marcin Wcisło3f4ffe417acb
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 8d9157e8f4..784f87896c 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -11,7 +11,7 @@
"module": "uvicorn",
"args": [
"saleor.asgi:application",
- "--lifespan=off"
+ "--lifespan=on"
]
},
{
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 177ee72d37..ecf1bff233 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -37,6 +37,7 @@ All notable, unreleased changes to this project will be documented in this file.
Validation is now performed on the frontend (Dashboard). This change increases velocity of features related to apps and extensions, now Dashboard is only entity that ensures the contract
- Improve user search. Use search vector functionality to enable searching users by email address, first name, last name, and addresses.
- Improved checkout search with search vectors. The `search_index_dirty` flag is set whenever indexed checkout data changes, and a background task runs every minute to update search vectors for dirty checkouts, processing the oldest first. Search results are returned in order of best match relevance.
+- Add optional usage telemetry. - #18789 by @wcislo-saleor
### Deprecations
- Deprecate the `hasVariants` field on `ProductType`.
diff --git a/Dockerfile b/Dockerfile
index f7fb8fed1b..2bfba1d181 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -62,4 +62,4 @@ LABEL org.opencontainers.image.title="saleor/saleor" \
org.opencontainers.image.authors="Saleor Commerce (https://saleor.io)" \
org.opencontainers.image.licenses="BSD-3-Clause"
-CMD ["uvicorn", "saleor.asgi:application", "--host=0.0.0.0", "--port=8000", "--workers=2", "--lifespan=off", "--ws=none", "--no-server-header", "--no-access-log", "--timeout-keep-alive=35", "--timeout-graceful-shutdown=30", "--limit-max-requests=10000"]
+CMD ["uvicorn", "saleor.asgi:application", "--host=0.0.0.0", "--port=8000", "--workers=2", "--lifespan=on", "--ws=none", "--no-server-header", "--no-access-log", "--timeout-keep-alive=35", "--timeout-graceful-shutdown=30", "--limit-max-requests=10000"]
diff --git a/saleor/__main__.py b/saleor/__main__.py
index f384ab04b9..965c69dd00 100644
--- a/saleor/__main__.py
+++ b/saleor/__main__.py
@@ -1,7 +1,7 @@
import uvicorn
config = uvicorn.Config(
- "saleor.asgi:application", port=8000, reload=True, lifespan="off"
+ "saleor.asgi:application", port=8000, reload=True, lifespan="on"
)
server = uvicorn.Server(config)
server.run()
diff --git a/saleor/asgi/__init__.py b/saleor/asgi/__init__.py
index 977e6e3122..3da3436d44 100644
--- a/saleor/asgi/__init__.py
+++ b/saleor/asgi/__init__.py
@@ -9,12 +9,15 @@ https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
import gc
import os
+from django.conf import settings
+
from ..core.telemetry import initialize_telemetry
from .asgi_handler import get_asgi_application
from .cors_handler import cors_handler
from .gzip_compression import gzip_compression
from .health_check import health_check
from .telemetry import telemetry_middleware
+from .usage_telemetry import usage_telemetry_middleware
def preload_app() -> None:
@@ -38,5 +41,7 @@ application = health_check(application, "/health/")
application = gzip_compression(application)
application = cors_handler(application)
application = telemetry_middleware(application)
+if settings.SEND_USAGE_TELEMETRY is True:
+ application = usage_telemetry_middleware(application)
preload_app()
diff --git a/saleor/asgi/tests/test_usage_telemetry.py b/saleor/asgi/tests/test_usage_telemetry.py
new file mode 100644
index 0000000000..44b48087c2
--- /dev/null
+++ b/saleor/asgi/tests/test_usage_telemetry.py
@@ -0,0 +1,63 @@
+from datetime import timedelta
+
+from django.utils import timezone
+
+from ..usage_telemetry import get_usage_telemetry
+
+
+def test_get_usage_telemetry(site_settings):
+ # given
+ site_settings.usage_telemetry_reported_at = None
+ site_settings.save(update_fields=["usage_telemetry_reported_at"])
+
+ expected_instance_keys = {
+ "instance_id",
+ "python_version",
+ "saleor_version",
+ "is_debug",
+ "is_local",
+ }
+
+ expected_usage_keys = {
+ "app_count",
+ "attribute_count",
+ "attribute_entity_type_count",
+ "attribute_type_count",
+ "attribute_input_type_count",
+ "attribute_page_count",
+ "attribute_variant_count",
+ "attribute_product_count",
+ "channel_count",
+ "currencies",
+ "model_count",
+ "product_count",
+ "saleor_apps",
+ }
+
+ # when
+ data = get_usage_telemetry()
+
+ # then
+ assert data is not None
+
+ assert "reported_at" in data
+
+ instance = data["instance"]
+ assert set(instance.keys()) == expected_instance_keys
+
+ usage = data["usage"]
+ assert set(usage.keys()) == expected_usage_keys
+
+
+def test_get_usage_telemetry_checks_reported_at(site_settings, settings):
+ # given
+ site_settings.usage_telemetry_reported_at = timezone.now() - timedelta(days=30)
+ site_settings.save(update_fields=["usage_telemetry_reported_at"])
+
+ assert settings.SEND_USAGE_TELEMETRY_AFTER_TIMEDELTA.days < 30
+
+ # when
+ data = get_usage_telemetry()
+
+ # then
+ assert data is not None
diff --git a/saleor/asgi/usage_telemetry.py b/saleor/asgi/usage_telemetry.py
new file mode 100644
index 0000000000..6b2fab8112
--- /dev/null
+++ b/saleor/asgi/usage_telemetry.py
@@ -0,0 +1,234 @@
+import asyncio
+import hashlib
+import json
+import logging
+import random
+import sys
+
+from asgiref.sync import sync_to_async
+from asgiref.typing import (
+ ASGI3Application,
+ ASGIReceiveCallable,
+ ASGISendCallable,
+ Scope,
+)
+from django.apps import apps
+from django.conf import settings
+from django.db import connections
+from django.db.models import Count
+from django.utils import timezone
+
+from .. import __version__ as saleor_version
+from ..attribute import AttributeEntityType, AttributeInputType, AttributeType
+from ..core.http_client import HTTPClient
+
+logger = logging.getLogger(__name__)
+
+
+async def send_usage_telemetry_task():
+ # Multiple workers from the same parent process will start almost at the same time.
+ # Randomize the start of actual logic to avoid sending data more than once.
+ await asyncio.sleep(random.randint(0, 5))
+
+ try:
+ data = await sync_to_async(get_usage_telemetry, thread_sensitive=False)()
+ if data is None:
+ return
+
+ await sync_to_async(send_usage_telemetry, thread_sensitive=False)(data)
+ except Exception:
+ logger.exception("Sending usage telemetry has failed")
+
+ # Sending usage telemetry data failed, reset the field so during subsequent startup procedure
+ # another attempt will be made.
+ await sync_to_async(update_usage_telemetry_reported_at, thread_sensitive=False)(
+ dt=None, close_connections=True
+ )
+
+
+def get_usage_telemetry():
+ """Gather usage telemetry data.
+
+ Data will not be gathered if usage telemetry was recently sent.
+ """
+ try:
+ Site = apps.get_model("sites", "Site")
+ site_settings = Site.objects.get_current().settings
+ usage_telemetry_reported_at = site_settings.usage_telemetry_reported_at
+
+ cutoff_datetime = timezone.now() - settings.SEND_USAGE_TELEMETRY_AFTER_TIMEDELTA
+ if (
+ usage_telemetry_reported_at
+ and usage_telemetry_reported_at > cutoff_datetime
+ ):
+ return None
+
+ update_usage_telemetry_reported_at(dt=timezone.now(), close_connections=False)
+
+ instance = {
+ "instance_id": str(site_settings.instance_id),
+ "saleor_version": saleor_version,
+ "python_version": sys.version,
+ "is_debug": settings.DEBUG,
+ "is_local": isinstance(settings.PUBLIC_URL, str)
+ and (
+ "localhost" in settings.PUBLIC_URL or "127.0.0.1" in settings.PUBLIC_URL
+ ),
+ }
+
+ usage = {}
+
+ Product = apps.get_model("product", "Product")
+ usage["product_count"] = Product.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).count()
+
+ Attribute = apps.get_model("attribute", "Attribute")
+ usage["attribute_count"] = Attribute.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).count()
+ usage["attribute_type_count"] = {t[0]: 0 for t in AttributeType.CHOICES}
+ for item in (
+ Attribute.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .values("type")
+ .annotate(total=Count("type"))
+ ):
+ usage["attribute_type_count"][item["type"]] = item["total"]
+
+ usage["attribute_entity_type_count"] = {
+ t[0]: 0 for t in AttributeEntityType.CHOICES
+ }
+ for item in (
+ Attribute.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .exclude(entity_type__isnull=True)
+ .exclude(entity_type="")
+ .values("entity_type")
+ .annotate(total=Count("entity_type"))
+ ):
+ usage["attribute_entity_type_count"][item["entity_type"]] = item["total"]
+
+ usage["attribute_input_type_count"] = {
+ t[0]: 0 for t in AttributeInputType.CHOICES
+ }
+ for item in (
+ Attribute.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .values("input_type")
+ .annotate(total=Count("input_type"))
+ ):
+ usage["attribute_input_type_count"][item["input_type"]] = item["total"]
+
+ AttributePage = apps.get_model("attribute", "AttributePage")
+ usage["attribute_page_count"] = AttributePage.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).count()
+
+ AttributeProduct = apps.get_model("attribute", "AttributeProduct")
+ usage["attribute_product_count"] = AttributeProduct.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).count()
+
+ AttributeVariant = apps.get_model("attribute", "AttributeVariant")
+ usage["attribute_variant_count"] = AttributeVariant.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).count()
+
+ Page = apps.get_model("page", "Page") # also known as Model
+ usage["model_count"] = Page.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).count()
+
+ Channel = apps.get_model("channel", "Channel")
+ usage["channel_count"] = Channel.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).count()
+ usage["currencies"] = list(
+ Channel.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .distinct("currency_code")
+ .values_list("currency_code", flat=True)
+ .order_by("currency_code")
+ )
+
+ App = apps.get_model("app", "App")
+ usage["saleor_apps"] = list(
+ App.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(identifier__startswith="saleor.app")
+ .values_list("identifier", flat=True)
+ )
+ usage["app_count"] = App.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).count()
+
+ return {
+ "instance": instance,
+ "usage": usage,
+ "reported_at": timezone.now().isoformat(timespec="seconds"),
+ }
+ finally:
+ connections.close_all()
+
+
+def send_usage_telemetry(data: dict):
+ url = "https://usage-telemetry.saleor.io/"
+
+ logger.info("Sending usage telemetry data: %s to: %s", data, url)
+
+ json_data = json.dumps(data)
+
+ headers = {
+ "content-type": "application/json",
+ # underlying infrastructure requires hash of the data
+ "x-amz-content-sha256": hashlib.sha256(json_data.encode("utf-8")).hexdigest(),
+ }
+
+ resp = HTTPClient.send_request(
+ "POST",
+ url,
+ json=data,
+ headers=headers,
+ allow_redirects=False,
+ )
+
+ return resp.status_code == 200
+
+
+def update_usage_telemetry_reported_at(dt, close_connections):
+ Site = apps.get_model("sites", "Site")
+ try:
+ site_settings = Site.objects.get_current().settings
+ site_settings.usage_telemetry_reported_at = dt
+ site_settings.save(update_fields=["usage_telemetry_reported_at"])
+ finally:
+ if close_connections:
+ connections.close_all()
+
+
+def usage_telemetry_middleware(application: ASGI3Application) -> ASGI3Application:
+ """Send usage telemetry data.
+
+ Saleor does not extract any personal data from your Saleor instance.
+
+ Find more about motivation and how we use this data to improve Saleor at: https://docs.saleor.io/setup/usage-telemetry.
+ """
+
+ async def wrapper(
+ scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
+ ) -> None:
+ if scope.get("type") != "lifespan":
+ return await application(scope, receive, send)
+
+ while True:
+ message = await receive()
+ if message["type"] == "lifespan.startup":
+ try:
+ asyncio.create_task(send_usage_telemetry_task())
+ except Exception:
+ logger.exception(
+ "Exception happened during scheduling usage telemetry task"
+ )
+ finally:
+ await send({"type": "lifespan.startup.complete"})
+ elif message["type"] == "lifespan.shutdown":
+ await send({"type": "lifespan.shutdown.complete"})
+ return None
+
+ return wrapper
diff --git a/saleor/settings.py b/saleor/settings.py
index ecde78f7d2..45213687f9 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -1212,6 +1212,12 @@ ALLOWED_MIME_TYPES.update(
json.loads(os.environ.get("UPLOAD_ADDITIONAL_ALLOWED_MIME_TYPES", "{}"))
)
+# Usage telemetry
+SEND_USAGE_TELEMETRY = get_bool_from_env("SEND_USAGE_TELEMETRY", True)
+SEND_USAGE_TELEMETRY_AFTER_TIMEDELTA = datetime.timedelta(
+ seconds=parse(os.environ.get("SEND_USAGE_TELEMETRY_AFTER_TIMEDELTA", "1 day"))
+)
+
# Library `google-i18n-address` use `AddressValidationMetadata` form Google to provide address validation rules.
# Patch `i18n` module to allows to override the default address rules.
i18n_rules_override()
diff --git a/saleor/site/migrations/0044_sitesettings_instance_id_and_more.py b/saleor/site/migrations/0044_sitesettings_instance_id_and_more.py
new file mode 100644
index 0000000000..acf1f617b1
--- /dev/null
+++ b/saleor/site/migrations/0044_sitesettings_instance_id_and_more.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.11 on 2026-02-11 13:58
+
+import uuid
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("site", "0043_sitesettings_use_legacy_update_webhook_emission"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sitesettings",
+ name="instance_id",
+ field=models.UUIDField(blank=True, default=uuid.uuid4, null=True),
+ ),
+ migrations.AddField(
+ model_name="sitesettings",
+ name="usage_telemetry_reported_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 59dba28403..4e74ed4704 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -1,3 +1,4 @@
+import uuid
from email.headerregistry import Address
from email.utils import parseaddr
from typing import Final
@@ -100,6 +101,14 @@ class SiteSettings(ModelWithMetadata):
null=True, blank=True, on_delete=models.SET_NULL, to="page.PageType"
)
+ # usage telemetry
+ instance_id = models.UUIDField(
+ default=uuid.uuid4,
+ null=True,
+ blank=True,
+ )
+ usage_telemetry_reported_at = models.DateTimeField(null=True, blank=True)
+
# deprecated
charge_taxes_on_shipping = models.BooleanField(default=True)
include_taxes_in_prices = models.BooleanField(default=True)