Repository navigation
refactor: pass session explicitly in schedule tasks (#37403) #41017
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,19 +11,19 @@ | |
| from datetime import UTC, datetime, timedelta | ||
|
|
||
| import click | ||
| from celery import shared_task | ||
| from sqlalchemy import delete, or_, select | ||
|
|
||
| import app | ||
| from configs import dify_config | ||
| from extensions.ext_database import db | ||
| from core.db.session_factory import session_factory | ||
| from models.oauth import OAuthAccessToken | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| DELETE_BATCH_SIZE = 500 | ||
|
|
||
|
|
||
| @app.celery.task(queue="retention") | ||
| @shared_task(queue="retention") | ||
| def clean_oauth_access_tokens_task(): | ||
| click.echo(click.style("Start clean oauth_access_tokens.", fg="green")) | ||
| retention_days = int(dify_config.OAUTH_ACCESS_TOKEN_RETENTION_DAYS) | ||
|
|
@@ -37,13 +37,14 @@ def clean_oauth_access_tokens_task(): | |
| ) | ||
|
|
||
| total = 0 | ||
| while True: | ||
| ids = db.session.scalars(select(OAuthAccessToken.id).where(candidates).limit(DELETE_BATCH_SIZE)).all() | ||
| if not ids: | ||
| break | ||
| db.session.execute(delete(OAuthAccessToken).where(OAuthAccessToken.id.in_(ids))) | ||
| db.session.commit() | ||
| total += len(ids) | ||
| with session_factory.create_session() as session: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Take the session as a required parameter instead of reaching for a global ( dify-codereview · |
||
| while True: | ||
| ids = session.scalars(select(OAuthAccessToken.id).where(candidates).limit(DELETE_BATCH_SIZE)).all() | ||
| if not ids: | ||
| break | ||
| session.execute(delete(OAuthAccessToken).where(OAuthAccessToken.id.in_(ids))) | ||
| session.commit() | ||
| total += len(ids) | ||
|
|
||
| end_at = time.perf_counter() | ||
| click.echo( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| """Unit tests for ``check_upgradable_plugin_task`` strategy selection. | ||
|
|
||
| The task dispatches upgrade checks for auto-upgrade strategies whose | ||
| ``upgrade_time_of_day`` falls inside the current checking window. Sessions | ||
| are provided by the shared SQLite session factory, which proves the task no | ||
| longer depends on the global Flask-SQLAlchemy session. | ||
| """ | ||
|
|
||
| import time | ||
| import uuid | ||
| from unittest.mock import patch | ||
|
|
||
| import pytest | ||
| from sqlalchemy.orm import Session, sessionmaker | ||
|
|
||
| import schedule.check_upgradable_plugin_task as check_upgradable_module | ||
| from models.account import TenantPluginAutoUpgradeStrategy, TenantPluginAutoUpgradeStrategySetting | ||
| from schedule.check_upgradable_plugin_task import ( | ||
| AUTO_UPGRADE_MINIMAL_CHECKING_INTERVAL, | ||
| check_upgradable_plugin_task, | ||
| ) | ||
|
|
||
|
|
||
| def _make_strategy( | ||
| *, upgrade_time_of_day: int, setting: TenantPluginAutoUpgradeStrategySetting | ||
| ) -> TenantPluginAutoUpgradeStrategy: | ||
| return TenantPluginAutoUpgradeStrategy( | ||
| tenant_id=str(uuid.uuid4()), | ||
| strategy_setting=setting, | ||
| upgrade_time_of_day=upgrade_time_of_day, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def seeded_strategies(sqlite_session_factory: sessionmaker[Session]) -> dict[str, str]: | ||
| """Seed strategies covering each branch of the selection window.""" | ||
| window_start = int(time.time() % 86400 - 30) | ||
| in_window = window_start + 60 | ||
| out_of_window = window_start + AUTO_UPGRADE_MINIMAL_CHECKING_INTERVAL + 3600 | ||
|
|
||
| strategies = { | ||
| "in_window": _make_strategy( | ||
| upgrade_time_of_day=in_window, setting=TenantPluginAutoUpgradeStrategySetting.FIX_ONLY | ||
| ), | ||
| "out_of_window": _make_strategy( | ||
| upgrade_time_of_day=out_of_window, setting=TenantPluginAutoUpgradeStrategySetting.FIX_ONLY | ||
| ), | ||
| "disabled": _make_strategy( | ||
| upgrade_time_of_day=in_window, setting=TenantPluginAutoUpgradeStrategySetting.DISABLED | ||
| ), | ||
| } | ||
| with sqlite_session_factory() as session: | ||
| for strategy in strategies.values(): | ||
| session.add(strategy) | ||
| session.commit() | ||
| return {label: strategy.tenant_id for label, strategy in strategies.items()} | ||
|
|
||
|
|
||
| def test_dispatches_only_in_window_enabled_strategies(seeded_strategies: dict[str, str]) -> None: | ||
| with ( | ||
| patch.object(check_upgradable_module, "fetch_global_plugin_manifest"), | ||
| patch.object( | ||
| check_upgradable_module.check_task, "process_tenant_plugin_autoupgrade_check_task" | ||
| ) as mock_check_task, | ||
| ): | ||
| check_upgradable_plugin_task() | ||
|
|
||
| dispatched_tenants = [call.args[0] for call in mock_check_task.delay.call_args_list] | ||
| assert dispatched_tenants == [seeded_strategies["in_window"]] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Take the session as a required parameter instead of reaching for a global (
@with_sessioninjects it in controllers). If this code must open and commit its own short transaction, take the session factory as a parameter instead (e.g. in__init__). Then tests passsqlite_session/sqlite_session_factorydirectly and need no monkeypatch, and can assert the committed row from another session instead of counting commits.dify-codereview ·
inject-sessionLearned from an earlier review. Reply here if this is wrong.