From 322671766dc5f0ab7f2bd77c386d7a57850b992b Mon Sep 17 00:00:00 2001 From: Ankush Menat Date: Fri, 15 Mar 2024 10:50:18 +0530 Subject: [PATCH] perf: avoid importing posthog if not required Avoids 7MB of overhead and cleanup costs for each background job :tada: --- frappe/hooks.py | 2 +- frappe/utils/background_jobs.py | 11 +++++++++++ frappe/utils/telemetry.py | 10 ---------- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/frappe/hooks.py b/frappe/hooks.py index 868d3889e2..3487a73fa5 100644 --- a/frappe/hooks.py +++ b/frappe/hooks.py @@ -441,7 +441,7 @@ after_job = [ "frappe.recorder.dump", "frappe.monitor.stop", "frappe.utils.file_lock.release_document_locks", - "frappe.utils.telemetry.flush", + "frappe.utils.background_jobs.flush_telemetry", ] extend_bootinfo = [ diff --git a/frappe/utils/background_jobs.py b/frappe/utils/background_jobs.py index 2cffd2b5b7..e7fe1424fc 100644 --- a/frappe/utils/background_jobs.py +++ b/frappe/utils/background_jobs.py @@ -4,6 +4,7 @@ import socket import time from collections import defaultdict from collections.abc import Callable +from contextlib import suppress from functools import lru_cache from typing import Any, NoReturn from uuid import uuid4 @@ -606,6 +607,16 @@ def truncate_failed_registry(job, connection, type, value, traceback): job_obj and fail_registry.remove(job_obj, delete_job=True) +def flush_telemetry(): + """Forcefully flush pending events. + + This is required in context of background jobs where process might die before posthog gets time + to push events.""" + ph = getattr(frappe.local, "posthog", None) + with suppress(Exception): + ph and ph.flush() + + def _start_sentry(): sentry_dsn = os.getenv("FRAPPE_SENTRY_DSN") if not sentry_dsn: diff --git a/frappe/utils/telemetry.py b/frappe/utils/telemetry.py index 2fa657fc8e..fc9e24e304 100644 --- a/frappe/utils/telemetry.py +++ b/frappe/utils/telemetry.py @@ -60,16 +60,6 @@ def capture(event, app, **kwargs): ph and ph.capture(distinct_id=frappe.local.site, event=f"{app}_{event}", **kwargs) -def flush(): - """Forcefully flush pending events. - - This is required in context of background jobs where process might die before posthog gets time - to push events.""" - ph: Posthog = getattr(frappe.local, "posthog", None) - with suppress(Exception): - ph and ph.flush() - - def capture_doc(doc, action): with suppress(Exception): age = site_age()