-
Couldn't load subscription status.
- Fork 4.6k
Implementations and corrections of previous commits in the chatwoot and baileys services #2076
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
Conversation
- Changed the build command in package.json to use TypeScript compiler (tsc) with noEmit option. - Added @swc/core and @swc/helpers as development dependencies for improved performance. refactor: clean up WhatsApp Baileys service - Removed unused properties and interfaces related to message keys. - Simplified message handling logic by removing redundant checks and conditions. - Updated message timestamp handling for consistency. - Improved readability and maintainability by restructuring code and removing commented-out sections. refactor: optimize Chatwoot service - Streamlined database queries by reusing PostgreSQL client connection. - Enhanced conversation creation logic with better cache handling. - Removed unnecessary methods and improved existing ones for clarity. - Updated message sending logic to handle file streams instead of buffers. fix: improve translation loading mechanism - Simplified translation file loading by removing environment variable checks. - Ensured translations are loaded from a consistent path within the project structure.
Reviewer's GuideThis PR refactors database client usage, overhauls conversation and messaging flows in ChatwootService, simplifies message send and streaming logic, cleans up legacy mapping in the Baileys service, streamlines i18n loading, enhances import helper phone binding for groups, and updates build tooling and dependencies. Sequence diagram for the updated Chatwoot conversation creation flowsequenceDiagram
participant User
participant ChatwootService
participant CacheService
participant ChatwootClient
participant Database
User->>ChatwootService: createConversation(instance, body)
ChatwootService->>CacheService: has(cacheKey)?
alt Conversation exists in cache
ChatwootService->>CacheService: get(cacheKey)
ChatwootService->>ChatwootClient: get(conversationId)
alt Conversation exists in Chatwoot
ChatwootService-->>User: return conversationId
else Conversation missing in Chatwoot
ChatwootService->>CacheService: delete(cacheKey)
ChatwootService->>ChatwootService: createConversation(instance, body) (retry)
end
else Conversation not in cache
ChatwootService->>CacheService: has(lockKey)?
alt Lock exists
ChatwootService->>CacheService: wait for release or timeout
end
ChatwootService->>CacheService: set(lockKey)
ChatwootService->>ChatwootClient: get contactConversations
alt Open conversation found
ChatwootService->>CacheService: set(cacheKey, conversationId)
ChatwootService-->>User: return conversationId
else No open conversation
ChatwootService->>ChatwootClient: create new conversation
ChatwootService->>CacheService: set(cacheKey, newConversationId)
ChatwootService-->>User: return newConversationId
end
ChatwootService->>CacheService: delete(lockKey)
end
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
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.
Hey there - I've reviewed your changes - here's some feedback:
Blocking issues:
- Detected that function argument
languagehas entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated. (link)
General comments:
- Replacing
getPgClient()with a singlepgClientproperty could lead to connection reuse issues if it isn’t a pool—please verify that it supports concurrent queries and reconnections or revert to per‐query acquisition. - The recursive retry in
createConversationwhen a cached conversation is missing risks unbounded recursion—consider refactoring it into a loop with a max retry count to avoid potential stack overflows. - The stale‐conversation retry logic was removed from
sendData, so 404 errors on sending may go unhandled; it’d be safer to reintroduce error handling that recreates the conversation before retrying the send.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Replacing `getPgClient()` with a single `pgClient` property could lead to connection reuse issues if it isn’t a pool—please verify that it supports concurrent queries and reconnections or revert to per‐query acquisition.
- The recursive retry in `createConversation` when a cached conversation is missing risks unbounded recursion—consider refactoring it into a loop with a max retry count to avoid potential stack overflows.
- The stale‐conversation retry logic was removed from `sendData`, so 404 errors on sending may go unhandled; it’d be safer to reintroduce error handling that recreates the conversation before retrying the send.
## Individual Comments
### Comment 1
<location> `src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts:627-636` </location>
<code_context>
-
- const client = await this.clientCw(instance);
- if (!client) return null;
+ if (await this.cache.has(cacheKey)) {
+ return (await this.cache.get(cacheKey)) as number;
+ }
const isGroup = remoteJid.includes('@g.us');
const chatId = isGroup ? remoteJid : remoteJid.split('@')[0];
@@ -760,39 +779,34 @@ export class ChatwootService {
return null;
}
- let inboxConversation = null;
-
- if (this.provider.reopenConversation) {
- inboxConversation = this.findOpenConversation(contactConversations.payload, filterInbox.id);
-
- if (inboxConversation) {
- this.logger.verbose(
- `Found open conversation in reopenConversation mode: ${JSON.stringify(inboxConversation)}`,
- );
+ let inboxConversation = contactConversations.payload.find(
+ (conversation) => conversation.inbox_id == filterInbox.id,
+ );
</code_context>
<issue_to_address>
**issue (bug_risk):** Recursive call to createConversation if conversation does not exist may lead to stack overflow in rare cases.
If a conversationId in the cache is consistently missing from Chatwoot, this recursion could become infinite. Please add a retry limit or guard to prevent stack overflow.
</issue_to_address>
### Comment 2
<location> `src/utils/i18n.ts:15` </location>
<code_context>
const translationContent = fs.readFileSync(languagePath, 'utf8');
</code_context>
<issue_to_address>
**security (javascript.lang.security.audit.detect-non-literal-fs-filename):** Detected that function argument `language` has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated.
*Source: opengrep*
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
📋 Description
🔗 Related Issue
Closes #2071, #2065, #2063, #2007, #2003, #1834, #1811
🧪 Type of Change
🧪 Testing
📸 Screenshots (if applicable)
✅ Checklist
📝 Additional Notes
Changes commented on in file change notes.
Summary by Sourcery
Refactor and correct core messaging services to improve connection reuse, cache handling, and event processing, while cleaning up deprecated code and updating tooling configurations.
New Features:
Bug Fixes:
Enhancements:
Build:
Chores: