From e27fbb5edea11e2f43baa9958d5d1ba5d7b34300 Mon Sep 17 00:00:00 2001 From: "sentry-autofix[bot]" <157164994+sentry-autofix[bot]@users.noreply.github.com> Date: Wed, 11 Dec 2024 22:12:53 +0000 Subject: [PATCH] Implement Singleton Initialization for Celery App and Database --- src/celery_app/app.py | 11 +++++++++-- src/seer/db.py | 15 +++++++++++++-- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/celery_app/app.py b/src/celery_app/app.py index 421037544..3ac6ff2d0 100644 --- a/src/celery_app/app.py +++ b/src/celery_app/app.py @@ -19,13 +19,20 @@ def setup_celery_entrypoint(app: Celery): app.on_configure.connect(init_celery_app) +# Track if bootup has been performed +_bootup_complete = False + @inject def init_celery_app(*args: Any, sender: Celery, config: CeleryConfig = injected, **kwargs: Any): + global _bootup_complete for k, v in config.items(): setattr(sender.conf, k, v) - bootup(start_model_loading=False, integrations=[CeleryIntegration(propagate_traces=True)]) + + if not _bootup_complete: + bootup(start_model_loading=False, integrations=[CeleryIntegration(propagate_traces=True)]) + _bootup_complete = True + from celery_app.tasks import setup_periodic_tasks - sender.on_after_finalize.connect(setup_periodic_tasks) diff --git a/src/seer/db.py b/src/seer/db.py index a6155822f..65bcf0086 100644 --- a/src/seer/db.py +++ b/src/seer/db.py @@ -35,20 +35,31 @@ from seer.configuration import AppConfig from seer.dependency_injection import inject, injected +# Module-level flag to track initialization state +_db_initialized = False @inject def initialize_database( config: AppConfig = injected, app: Flask = injected, ): - app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URL - app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"connect_args": {"prepare_threshold": None}} + global _db_initialized + if _db_initialized: + return + + try: + app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URL + app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"connect_args": {"prepare_threshold": None}} + db.init_app(app) migrate.init_app(app, db) + with app.app_context(): Session.configure(bind=db.engine) + + _db_initialized = True class Base(DeclarativeBase):