Skip to content

Conversation

@vduggen
Copy link

@vduggen vduggen commented Jan 14, 2026

📋 Description

This PR implements two improvements to the WhatsApp Web version fetching mechanism:

1. Caching Mechanism

Added caching functionality to fetchLatestWaWebVersion to reduce unnecessary HTTP requests to https://web.whatsapp.com/sw.js. The implementation:

  • Caches the WhatsApp Web version for 1 hour (3600 seconds) to avoid repeated requests
  • Caches the Baileys fallback version to protect against rate limits when the WhatsApp Web domain is blocked
  • Accepts an optional CacheService parameter for dependency injection, maintaining backward compatibility
  • Uses the project's standard cache infrastructure (CacheService with CacheEngine)

2. Error Logging

Added error logging for WhatsApp Web version fetch operations to improve debugging capabilities. When the request fails (e.g., due to network issues, rate limiting, or API changes), the error is now logged with detailed information. This helps identify when Baileys might be using an outdated version due to fetch failures.

Benefits:

  • Performance: Reduces HTTP requests, especially during frequent reconnections
  • Rate Limit Protection: Cached fallback version prevents repeated calls to fetchLatestBaileysVersion() when the WhatsApp Web domain is blocked
  • Debugging: Better visibility into version detection issues and fetch failures
  • Scalability: Shared cache across all instances and calls

🔗 Related Issue

🧪 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
  • 🧹 Code cleanup
  • 🔒 Security fix

🧪 Testing

  • Manual testing completed
  • Functionality verified in development environment
  • No breaking changes introduced
  • Tested with different connection types (if applicable)

Test Scenarios:

  • ✅ Verified caching works correctly - subsequent calls return cached version
  • ✅ Verified cache expiration after TTL period
  • ✅ Verified error logging when network request fails
  • ✅ Verified no errors logged when fetch succeeds
  • ✅ Verified fallback version caching when WhatsApp Web request fails
  • ✅ Verified cache parameter injection works correctly
  • ✅ Confirmed backward compatibility (works without cache parameter)
  • ✅ Tested with successful version fetch
  • ✅ Tested with blocked/failed requests (rate limit scenarios)

📸 Screenshots (if applicable)

Example log output when error occurs:

[ERROR] Failed to fetch latest WhatsApp Web version: Request failed with status code 429
[INFO] Using cached Baileys fallback version

✅ Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have manually tested my changes thoroughly
  • I have verified the changes work with different scenarios
  • Any dependent changes have been merged and published

📝 Additional Notes

Implementation Details

Cache Keys:

  • whatsapp_web_version: Stores the successfully fetched WhatsApp Web version
  • baileys_fallback_version: Stores the Baileys fallback version when HTTP request fails

Cache Configuration:

  • TTL: 3600 seconds (1 hour) for both cache keys
  • Module: whatsapp-version (uses project's cache infrastructure)
  • Respects project cache configuration (Redis if enabled, otherwise Local)

Code Changes:

  • src/utils/fetchLatestWaWebVersion.ts: Added caching logic and error logging
  • src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts: Updated to pass cache to the function

Known Issues

Note: The TypeScript compilation errors shown in the build are pre-existing issues in the codebase and are not related to this PR. The modified files (fetchLatestWaWebVersion.ts and the single line change in whatsapp.baileys.service.ts) have no TypeScript errors.

The errors are in:

  • whatsapp.business.service.ts (1 error)
  • whatsapp.baileys.service.ts (15 errors - unrelated to this change)
  • chatwoot.service.ts (4 errors)
  • channel.service.ts (8 errors)
  • onWhatsappCache.ts (2 errors)

These should be addressed in separate PRs.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jan 14, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adds error-aware logging after fetching the latest WhatsApp Web (Baileys) version so failures in the version fetch are surfaced without changing existing behavior when the fetch succeeds.

Sequence diagram for Baileys version fetch and error logging

sequenceDiagram
    participant BaileysStartupService
    participant BaileysLibrary as BaileysLibrary
    participant Logger

    BaileysStartupService->>BaileysLibrary: fetchLatestWaWebVersion()
    BaileysLibrary-->>BaileysStartupService: baileysVersion(version, error?)

    BaileysStartupService->>Logger: info("Baileys version: " + version.join('.'))

    alt error present on baileysVersion
        BaileysStartupService->>Logger: error("Fetch latest WaWeb version error: " + error.message)
    else no error
        BaileysStartupService->>Logger: info("Group Ignore: " + localSettings.groupsIgnore)
    end

    BaileysStartupService->>Logger: info("Group Ignore: " + localSettings.groupsIgnore)
Loading

Flow diagram for Baileys WaWeb version error-aware logging

flowchart TD
    A[Start BaileysStartupService startup] --> B[Call fetchLatestWaWebVersion]
    B --> C[Receive baileysVersion with version and optional error]
    C --> D[Log info Baileys version]
    D --> E{baileysVersion.error is not null?}
    E -- Yes --> F[Log error Fetch latest WaWeb version error with error.message]
    E -- No --> G[Skip error logging]
    F --> H[Log info Group Ignore settings]
    G --> H[Log info Group Ignore settings]
    H --> I[Continue startup process]
Loading

File-Level Changes

Change Details Files
Log detailed errors when fetching the latest WhatsApp Web version fails, while keeping existing startup behavior intact.
  • Capture a possible error from the Baileys version fetch result using optional chaining and null fallback.
  • Conditionally log an error message if a fetch error exists, including the underlying error message text.
  • Ensure the new error logging executes after the version is logged and before other startup logs, without altering the existing control flow.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

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

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • Consider handling cases where baileysVersion?.error is not an Error instance (e.g., string or unknown) by safely stringifying it or using a type guard, instead of assuming .message exists.
  • If your logger supports structured logging, it may be more useful to pass the full error object (and possibly the requested version/URL) as metadata rather than only logging error.message in the string.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider handling cases where `baileysVersion?.error` is not an `Error` instance (e.g., string or unknown) by safely stringifying it or using a type guard, instead of assuming `.message` exists.
- If your logger supports structured logging, it may be more useful to pass the full `error` object (and possibly the requested version/URL) as metadata rather than only logging `error.message` in the string.

## Individual Comments

### Comment 1
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:649-651` </location>
<code_context>
     const log = `Baileys version: ${version.join('.')}`;
     this.logger.info(log);

+    const error = baileysVersion?.error ?? null;
+    if (error) {
+      this.logger.error(`Fetch latest WaWeb version error: ${error.message}`);
+    }
+
</code_context>

<issue_to_address>
**suggestion:** Log the error object (and/or stack) in addition to the message for better diagnostics.

Currently only `error.message` is logged, which loses useful context (e.g. stack trace or custom fields on non-standard error objects). Instead, log the full error object and/or stack, e.g.:

```ts
const error = baileysVersion?.error;
if (error) {
  this.logger.error('Fetch latest WaWeb version error', { error });
}
```

so failures in fetching the latest WaWeb version are easier to diagnose.
</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.

- Added caching mechanism to store and retrieve the latest WhatsApp Web version
- Enhanced error handling to utilize cached fallback versions when fetching fails
- Updated the fetchLatestWaWebVersion function to accept a cache service as an optional parameter
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.

1 participant