Skip to content

Eflowchat pg fix - #142

Open
soyezeok wants to merge 3 commits into
evolution-foundation:mainfrom
soyezeok:eflowchat-pg-fix
Open

Eflowchat pg fix#142
soyezeok wants to merge 3 commits into
evolution-foundation:mainfrom
soyezeok:eflowchat-pg-fix

Conversation

@soyezeok

@soyezeok soyezeok commented Jul 29, 2026

Copy link
Copy Markdown

Description

Related Issue

Closes #(issue_number)

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement

Testing

  • Manual testing completed
  • Functionality verified in development environment
  • No breaking changes introduced

Screenshots (if applicable)

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have tested my changes thoroughly
  • Any dependent changes have been merged and published

Additional Notes

Summary by Sourcery

Share and reuse a singleton auth database container in the WhatsApp service to avoid leaking connections and validate its retry and reuse semantics with tests.

Bug Fixes:

  • Prevent database connection leaks by sharing a single capped auth store container across client startups and reconnections.

Enhancements:

  • Introduce a singleton auth container with tuned connection pooling for Postgres and SQLite to stabilize WhatsApp auth storage access.

Tests:

  • Add unit test covering auth container retry behavior on initial failure and reuse semantics on subsequent successful calls.

Ay0rus and others added 3 commits July 29, 2026 15:17
…ne per StartClient

StartClient() called sqlstore.New() on every connect AND every reconnect, each
opening a brand-new *sql.DB with MaxOpenConns=0 (unlimited) and ConnMaxLifetime=0
(never expires), and the container was never closed. With instances reconnecting
in a loop (QR expiry, network blips, CONNECT_ON_STARTUP) this leaks one connection
pool per attempt and eventually exhausts Postgres ("sorry, too many clients
already").

Create the auth-store container once (sync.Once) with a bounded pool via
sqlstore.NewWithDB(), and reuse it across all clients — whatsmeow's container is
designed to hold multiple devices. Direct DB connection, capped pool.
…aching the error

  sync.Once memorized the first failure forever: a Postgres hiccup at the
  first StartClient left every future connect returning the same stale
  error until process restart. Replace it with a mutex that only memoizes
  success — failures retry on the next call. Adds a self-contained
  regression test using the sqlite path (no external services required).
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
@sourcery-ai

sourcery-ai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Reviewer's Guide

Introduce a shared, singleton sqlstore.Container for WhatsApp auth storage with connection pooling limits, and add a test to validate retry-on-failure and reuse semantics.

Sequence diagram for shared auth sqlstore.Container lifecycle and reuse

sequenceDiagram
    participant Client1 as StartClient_1
    participant Service as whatsmeowService
    participant DB as sql_DB
    participant Store as sqlstore_Container

    Client1->>Service: StartClient(cd)
    Service->>Service: getAuthContainer()
    alt sharedAuthContainer already set
        Service-->>Service: return sharedAuthContainer
    else first successful creation
        Service->>DB: sql.Open(dialect, address)
        DB-->>Service: *sql.DB
        alt dialect == postgres
            Service->>DB: SetMaxOpenConns(20)
            Service->>DB: SetMaxIdleConns(5)
            Service->>DB: SetConnMaxLifetime(5m)
            Service->>DB: SetConnMaxIdleTime(2m)
        else dialect == sqlite
            Service->>DB: SetMaxOpenConns(1)
        end
        Service->>Store: sqlstore.NewWithDB(db, dialect, dbLog)
        Service->>Store: Upgrade(context.Background())
        Store-->>Service: ok
        Service-->>Service: sharedAuthContainer = container
    end
    Service-->>Client1: client started with container

    %% Retry-on-failure behavior
    Client1->>Service: StartClient(cd)
    Service->>Service: getAuthContainer()
    Service->>DB: sql.Open(...)
    DB-->>Service: error
    Service-->>Client1: log "Failed to get auth container" and return

    Client1->>Service: StartClient(cd) retry
    Service->>Service: getAuthContainer() (retries sql.Open)

    %% Reuse from another client
    participant Client2 as StartClient_2
    Client2->>Service: StartClient(cd2)
    Service->>Service: getAuthContainer()
    Service-->>Client2: returns sharedAuthContainer
Loading

File-Level Changes

Change Details Files
Centralize creation and pooling of the WhatsApp auth sqlstore container into a shared singleton accessed via getAuthContainer, and wire StartClient to use it.
  • Add package-level sharedAuthContainer and mutex to manage a singleton sqlstore.Container instance
  • Implement getAuthContainer to lazily initialize the auth DB connection with sqlite/postgres selection, logging, pool sizing, and schema upgrade, while memoizing only successful containers
  • Configure postgres connection pooling limits (max open/idle connections and lifetimes) and constrain sqlite to a single open connection
  • Update StartClient to obtain the auth container via getAuthContainer and adjust error logging message accordingly
pkg/whatsmeow/service/whatsmeow.go
Add tests to validate that getAuthContainer retries on initial failure and reuses the same container on subsequent successful calls.
  • Reset sharedAuthContainer singleton state at test start to ensure isolation
  • Create a whatsmeowService configured with an invalid exPath to force an Upgrade failure and assert that the error is returned and not memoized
  • Create a whatsmeowService with a valid sqlite path and dbdata directory, call getAuthContainer to obtain a non-nil container, then call again and assert the same instance is reused
pkg/whatsmeow/service/auth_container_retry_test.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • Consider threading a context from callers into getAuthContainer instead of using context.Background() so the Upgrade call can respect timeouts/cancellation during startup.
  • The test directly mutates the sharedAuthContainer singleton; if more tests are added that also rely on the singleton state, it would be safer to centralize a reset helper to avoid inter-test coupling or ordering issues.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider threading a context from callers into getAuthContainer instead of using context.Background() so the Upgrade call can respect timeouts/cancellation during startup.
- The test directly mutates the sharedAuthContainer singleton; if more tests are added that also rely on the singleton state, it would be safer to centralize a reset helper to avoid inter-test coupling or ordering issues.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants