Skip to content

refactor: admin api using session factory#29628

Merged
fatelei merged 1 commit intolanggenius:mainfrom
fatelei:admin_api_using_session_factory
Dec 15, 2025
Merged

refactor: admin api using session factory#29628
fatelei merged 1 commit intolanggenius:mainfrom
fatelei:admin_api_using_session_factory

Conversation

@fatelei
Copy link
Copy Markdown
Contributor

@fatelei fatelei commented Dec 14, 2025

Important

  1. Make sure you have read our contribution guidelines
  2. Ensure there is an associated issue and you have been assigned to it
  3. Use the correct syntax to link this PR: Fixes #<issue number>.

Summary

#24245

admin api using session factory instead of Session

Screenshots

Before After
... ...

test in local

10ca8175cd7b766c75d7efadd15fad3a cb7a6fd8d8c631f314df04d0dd320f37 17eac58c44c42a8e10181f0c81e11414 e99a94271528cd9a07c2e1ab6b9b9f08

Checklist

  • This change requires a documentation update, included: Dify Document
  • I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.
  • I ran dev/reformat(backend) and cd web && npx lint-staged(frontend) to appease the lint gods

@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Dec 14, 2025
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @fatelei, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refactors the database session management within the admin API by introducing a dedicated SessionFactory. This change aims to standardize how database sessions are created and managed, moving away from direct Session instantiation. The new factory pattern improves code consistency, maintainability, and prepares the codebase for more advanced session handling if needed.

Highlights

  • Database Session Management Refactor: Introduced a new SessionFactory to centralize and standardize the creation and management of SQLAlchemy database sessions across the application.
  • Admin API Update: Refactored the admin API endpoints to utilize the new session_factory.create_session() method, replacing direct Session(db.engine) calls for improved consistency.
  • New Session Factory Module: Added api/core/db/session_factory.py to define the SessionFactory class and its related functions for configuring and creating sessions.
  • New Session Factory Extension: Created api/extensions/ext_session_factory.py to integrate the session factory configuration into the application's extension initialization process.
  • Unit Tests Added: A new unit test file api/tests/unit_tests/controllers/console/test_admin.py was added, providing comprehensive tests for the admin console API endpoints, including payload validation and authentication.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

The pull request introduces a new session_factory module and extension to centralize and manage SQLAlchemy database sessions, replacing direct Session(db.engine) calls in api/controllers/console/admin.py with session_factory.create_session(). New files api/core/db/session_factory.py and api/extensions/ext_session_factory.py were added to define and initialize this factory, respectively. Additionally, a new unit test file, api/tests/unit_tests/controllers/console/test_admin.py, was added to cover the business logic of admin endpoints. Review comments indicate that the admin.py controller still incorrectly mixes database sessions, suggesting that all database operations within a method should use a single session from the new session_factory. The reviewer also proposes a refactoring of api/core/db/session_factory.py to simplify its design by encapsulating the session maker state within the SessionFactory class, thereby avoiding global variables and redundant module-level functions.

I am having trouble creating individual review comments. Click here to see my feedback.

api/controllers/console/admin.py (94)

critical

This method incorrectly mixes database sessions. The app object is fetched using db.session (line 78), while recommended_app is fetched using a new session from session_factory. Then, db.session is used to add and commit changes (lines 111, 114, 128).

This will lead to errors or incorrect behavior:

  • In the if not recommended_app: block, you are adding an object (recommended_app) to db.session that was not created in its scope.
  • In the else block, you are modifying recommended_app which was fetched from a session that is now closed. These changes will be lost when db.session.commit() is called.

All database operations within this method should use a single session from session_factory to ensure correctness. The entire method should be wrapped in a single with session_factory.create_session() as session: block.

api/core/db/session_factory.py (4-41)

medium

The current implementation with module-level functions and a class wrapper with static methods is a bit redundant and uses a global variable. It can be simplified by encapsulating the session maker state within the SessionFactory class itself. This avoids using global and makes the code cleaner and more object-oriented. Note that this change will require updating api/extensions/ext_session_factory.py to call session_factory.configure().

class SessionFactory:
    _session_maker: sessionmaker | None = None

    def configure(self, engine: Engine, expire_on_commit: bool = False):
        """Configure the session factory"""
        self._session_maker = sessionmaker(
            bind=engine,
            expire_on_commit=expire_on_commit
        )

    def get_session_maker(self) -> sessionmaker:
        if self._session_maker is None:
            raise RuntimeError("Session factory not configured. Call configure() first.")
        return self._session_maker

    def create_session(self) -> Session:
        return self.get_session_maker()()


session_factory = SessionFactory()

@fatelei fatelei force-pushed the admin_api_using_session_factory branch from b7c75fa to b1bfae1 Compare December 14, 2025 06:00
@fatelei fatelei force-pushed the admin_api_using_session_factory branch from 478d55c to 0a655d8 Compare December 14, 2025 06:03
@dosubot dosubot bot added the lgtm This PR has been approved by a maintainer label Dec 15, 2025
@QuantumGhost
Copy link
Copy Markdown
Contributor

LGTM

@fatelei fatelei merged commit 094f417 into langgenius:main Dec 15, 2025
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants