Skip to content

feat: implement WAMonitoringService for instance lifecycle management and add WhatsApp Baileys integration support - #2671

Open
codedalex wants to merge 1 commit into
evolution-foundation:mainfrom
codedalex:main
Open

feat: implement WAMonitoringService for instance lifecycle management and add WhatsApp Baileys integration support#2671
codedalex wants to merge 1 commit into
evolution-foundation:mainfrom
codedalex:main

Conversation

@codedalex

@codedalex codedalex commented Aug 3, 2026

Copy link
Copy Markdown

Summary by Sourcery

Improve WhatsApp Baileys instance lifecycle handling and message/contact persistence, and adjust local docker networking defaults.

Bug Fixes:

  • Add a fallback mechanism to populate pushName for incoming WhatsApp messages using existing contact records when it is missing from the payload.
  • Prevent duplicate WhatsApp messages from being created by checking for an existing message record before inserting a new one.
  • Ensure WhatsApp instances are not left in a zombie state by forcefully closing and cleaning up any existing instance with the same name before initializing a new one.

Enhancements:

  • Refine WhatsApp contact persistence so pushName is stored only for non-self contacts when available.

Deployment:

  • Update docker-compose to expose the API on a different local port and simplify networking by removing the external dokploy network.

… and add WhatsApp Baileys integration support
@sourcery-ai

sourcery-ai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implements additional robustness and deduplication in the WhatsApp Baileys integration, improves instance lifecycle handling in WAMonitoringService to prevent zombie instances, and updates docker-compose networking/port configuration.

Sequence diagram for WhatsApp Baileys message handling with pushName fallback and deduplication

sequenceDiagram
  participant BaileysStartupService
  participant PrismaRepository
  participant MessageTable as Message
  participant ContactTable as Contact

  BaileysStartupService->>BaileysStartupService: receive message
  alt missing pushName and not fromMe
    BaileysStartupService->>PrismaRepository: contact.findFirst(instanceId, participantJid)
    PrismaRepository-->>BaileysStartupService: contact.pushName
    BaileysStartupService->>BaileysStartupService: set received.pushName
  end

  BaileysStartupService->>BaileysStartupService: prepareMessage(received)

  BaileysStartupService->>PrismaRepository: $queryRaw SELECT FROM Message WHERE instanceId, key.id
  PrismaRepository-->>BaileysStartupService: existingMessage[]

  alt existingMessage found
    BaileysStartupService->>MessageTable: reuse existingMessage[0]
  else no existingMessage
    BaileysStartupService->>PrismaRepository: message.create(messageData)
    PrismaRepository-->>BaileysStartupService: msg
  end

  BaileysStartupService->>BaileysStartupService: use msg.messageTimestamp
Loading

Sequence diagram for WAMonitoringService setInstance zombie instance cleanup

sequenceDiagram
  participant WAMonitoringService
  participant waInstances
  participant Client
  participant WebSocket as client.ws
  participant ChannelController as channelController

  WAMonitoringService->>waInstances: lookup instanceData.instanceName
  alt existing instance found
    WAMonitoringService->>Client: existing.client
    opt client.ws exists
      WAMonitoringService->>WebSocket: close()
    end
    opt client.end exists
      WAMonitoringService->>Client: end(undefined)
    end
    WAMonitoringService->>waInstances: delete existing instance
  end

  WAMonitoringService->>ChannelController: init(instanceData, deps)
  ChannelController-->>WAMonitoringService: new instance
  WAMonitoringService->>waInstances: store new instance
Loading

File-Level Changes

Change Details Files
Enhance inbound message handling in Baileys service with safer pushName resolution and message deduplication before persistence.
  • Add fallback logic to populate missing pushName from existing contact records for non-fromMe messages
  • Before creating a Message DB record, query for an existing record with the same WhatsApp key id and skip creation if found, logging when duplicates are ignored
  • Adjust contact creation/update flow so pushName is optional and only set for non-fromMe messages when available
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Improve WhatsApp instance lifecycle management to avoid zombie instances in monitoring service.
  • On setInstance, detect an existing instance with the same instanceName, attempt to close its websocket and end the client safely, log warnings and errors, and then remove it from the in-memory registry before initializing a new instance
src/api/services/monitor.service.ts
Adjust docker-compose configuration for the evolution service stack networking and port mapping.
  • Change mapped host port for the evolution-api service from 8080 to 8081
  • Remove attachment to the external dokploy-network and its aliases, keeping only the internal evolution-net network and default bridge settings
docker-compose.yaml
package-lock.json

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
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 2 issues, and left some high level feedback:

  • In the duplicate-message handling block, existingMessage is fetched via $queryRaw with only id, status, and messageTimestamp, but the result is then used as msg just like the Prisma-created entity; if downstream code relies on other Message fields or expects a Prisma type, consider normalizing this (e.g., using findFirst with the same selection or at least clearly typing the result).
  • The contactRaw.pushName field has been made optional and is now only set when !received.key.fromMe && received.pushName; if the underlying schema or any consumer code assumes a non-null pushName, consider ensuring a consistent fallback (e.g., empty string) to avoid unexpected undefined values.
  • In WAMonitoringService.setInstance, the forceful shutdown of existing instances (ws.close() and client.end()) before re-init may introduce subtle race conditions if setInstance is invoked concurrently; it could be safer to guard this path (e.g., with a per-instance lock or a state flag) to prevent overlapping close/re-init cycles.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the duplicate-message handling block, `existingMessage` is fetched via `$queryRaw` with only `id`, `status`, and `messageTimestamp`, but the result is then used as `msg` just like the Prisma-created entity; if downstream code relies on other `Message` fields or expects a Prisma type, consider normalizing this (e.g., using `findFirst` with the same selection or at least clearly typing the result).
- The `contactRaw.pushName` field has been made optional and is now only set when `!received.key.fromMe && received.pushName`; if the underlying schema or any consumer code assumes a non-null `pushName`, consider ensuring a consistent fallback (e.g., empty string) to avoid unexpected `undefined` values.
- In `WAMonitoringService.setInstance`, the forceful shutdown of existing instances (`ws.close()` and `client.end()`) before re-init may introduce subtle race conditions if `setInstance` is invoked concurrently; it could be safer to guard this path (e.g., with a per-instance lock or a state flag) to prevent overlapping close/re-init cycles.

## Individual Comments

### Comment 1
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="1205-1212" />
<code_context>
           }

+          // FIX: Fallback pushName if not present in received payload
+          if (!received.pushName && !received.key.fromMe) {
+            const participantJid = received.participant || received.key.participant || received.key.remoteJid;
+            if (participantJid) {
+              const contact = await this.prismaRepository.contact.findFirst({
+                where: { instanceId: this.instanceId, remoteJid: participantJid },
+                select: { pushName: true }
+              });
+              if (contact && contact.pushName) {
+                received.pushName = contact.pushName;
+              }
</code_context>
<issue_to_address>
**suggestion (performance):** Avoid per-message lookup for pushName where possible to reduce database load.

This path triggers a `contact.findFirst` for every message without `pushName`, which can become an N+1 query pattern under high throughput. To mitigate this, you could restrict the fallback (e.g. only for group messages where `participant` is set) and/or add a short-lived in-memory cache keyed by `participantJid` and `instanceId` so repeated messages from the same JID don’t repeatedly hit the DB. Alternatively, consider batching contact lookups earlier in the pipeline if you can determine the relevant JIDs in advance.

Suggested implementation:

```typescript
          // FIX: Fallback pushName if not present in received payload.
          // Restrict to group messages (participant present) and use a small in-memory cache
          // to avoid per-message DB lookups for the same JID.
          if (
            !received.pushName &&
            !received.key.fromMe &&
            (received.participant || received.key?.participant)
          ) {
            const participantJid =
              received.participant || received.key.participant;

            if (participantJid) {
              const cacheKey = `${this.instanceId}:${participantJid}`;

              // In-memory cache for pushName lookups, keyed by instance + JID
              let cachedPushName =
                this.pushNameCache && this.pushNameCache.get(cacheKey);

              if (!cachedPushName) {
                const contact = await this.prismaRepository.contact.findFirst({
                  where: {
                    instanceId: this.instanceId,
                    remoteJid: participantJid,
                  },
                  select: { pushName: true },
                });

                if (contact?.pushName) {
                  cachedPushName = contact.pushName;

                  if (this.pushNameCache) {
                    this.pushNameCache.set(cacheKey, cachedPushName);
                  }
                }
              }

              if (cachedPushName) {
                received.pushName = cachedPushName;
              }
            }

```

1. Add an in-memory cache field to the WhatsApp Baileys service class, for example:
   `private readonly pushNameCache = new Map<string, string>();`
   Place this alongside other private fields on the service.
2. If you want cache eviction, you can later wrap this Map with a TTL mechanism or use an LRU cache implementation already present in your codebase (if any).
</issue_to_address>

### Comment 2
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="1373-1380" />
<code_context>
             const { pollUpdates, ...messageData } = messageRaw;
-            const msg = await this.prismaRepository.message.create({ data: messageData });
+
+            const existingMessage = await this.prismaRepository.$queryRaw`
+              SELECT id, status, "messageTimestamp" FROM "Message"
+              WHERE "instanceId" = ${this.instanceId}
+              AND "key"->>'id' = ${received.key.id}
+            ` as any[];
+
+            let msg;
+            if (existingMessage && existingMessage.length > 0) {
+              msg = existingMessage[0];
+              this.logger.info(`Message already exists, ignoring create: ${received.key.id}`);
</code_context>
<issue_to_address>
**issue (bug_risk):** Use a uniqueness constraint or upsert instead of a raw pre-check query to prevent duplicates.

Because the `SELECT` + conditional `create` flow is not atomic, concurrent deliveries of the same message ID can still result in duplicate rows. It would be safer to enforce a unique index on `(instanceId, key->>'id')` and rely on the DB to handle conflicts (e.g., via an upsert or `create` with `ON CONFLICT DO NOTHING` using `$executeRaw`).
</issue_to_address>

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.

Comment on lines +1205 to +1212
if (!received.pushName && !received.key.fromMe) {
const participantJid = received.participant || received.key.participant || received.key.remoteJid;
if (participantJid) {
const contact = await this.prismaRepository.contact.findFirst({
where: { instanceId: this.instanceId, remoteJid: participantJid },
select: { pushName: true }
});
if (contact && contact.pushName) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion (performance): Avoid per-message lookup for pushName where possible to reduce database load.

This path triggers a contact.findFirst for every message without pushName, which can become an N+1 query pattern under high throughput. To mitigate this, you could restrict the fallback (e.g. only for group messages where participant is set) and/or add a short-lived in-memory cache keyed by participantJid and instanceId so repeated messages from the same JID don’t repeatedly hit the DB. Alternatively, consider batching contact lookups earlier in the pipeline if you can determine the relevant JIDs in advance.

Suggested implementation:

          // FIX: Fallback pushName if not present in received payload.
          // Restrict to group messages (participant present) and use a small in-memory cache
          // to avoid per-message DB lookups for the same JID.
          if (
            !received.pushName &&
            !received.key.fromMe &&
            (received.participant || received.key?.participant)
          ) {
            const participantJid =
              received.participant || received.key.participant;

            if (participantJid) {
              const cacheKey = `${this.instanceId}:${participantJid}`;

              // In-memory cache for pushName lookups, keyed by instance + JID
              let cachedPushName =
                this.pushNameCache && this.pushNameCache.get(cacheKey);

              if (!cachedPushName) {
                const contact = await this.prismaRepository.contact.findFirst({
                  where: {
                    instanceId: this.instanceId,
                    remoteJid: participantJid,
                  },
                  select: { pushName: true },
                });

                if (contact?.pushName) {
                  cachedPushName = contact.pushName;

                  if (this.pushNameCache) {
                    this.pushNameCache.set(cacheKey, cachedPushName);
                  }
                }
              }

              if (cachedPushName) {
                received.pushName = cachedPushName;
              }
            }
  1. Add an in-memory cache field to the WhatsApp Baileys service class, for example:
    private readonly pushNameCache = new Map<string, string>();
    Place this alongside other private fields on the service.
  2. If you want cache eviction, you can later wrap this Map with a TTL mechanism or use an LRU cache implementation already present in your codebase (if any).

Comment on lines +1373 to +1380
const existingMessage = await this.prismaRepository.$queryRaw`
SELECT id, status, "messageTimestamp" FROM "Message"
WHERE "instanceId" = ${this.instanceId}
AND "key"->>'id' = ${received.key.id}
` as any[];

let msg;
if (existingMessage && existingMessage.length > 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Use a uniqueness constraint or upsert instead of a raw pre-check query to prevent duplicates.

Because the SELECT + conditional create flow is not atomic, concurrent deliveries of the same message ID can still result in duplicate rows. It would be safer to enforce a unique index on (instanceId, key->>'id') and rely on the DB to handle conflicts (e.g., via an upsert or create with ON CONFLICT DO NOTHING using $executeRaw).

@dpaes

dpaes commented Aug 4, 2026

Copy link
Copy Markdown

@codedalex send to develop, so we can review that PR (we dont accept anything to main)

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.

2 participants