Open
Conversation
Contributor
Reviewer's GuideImproves the robustness of the WhatsApp Baileys logout and connection lifecycle handling by marking sessions as ended before teardown, hardening logout against already-closed clients, ensuring database connection status is updated on logout, preventing reconnection loops on timeout, and guarding against null user data on connection open. Sequence diagram for the new logoutInstance flowsequenceDiagram
actor AdminUser
participant ApiServer
participant BaileysStartupService
participant MessageProcessor as messageProcessor
participant Client as client
participant WebSocket as client_ws
participant Prisma as prismaRepository
participant Database as instanceTable
AdminUser ->> ApiServer: Request logout of WhatsApp instance
ApiServer ->> BaileysStartupService: logoutInstance()
activate BaileysStartupService
BaileysStartupService ->> BaileysStartupService: endSession = true
BaileysStartupService ->> MessageProcessor: onDestroy()
BaileysStartupService ->> Client: logout("Log out instance: " + instanceName)
alt logout throws
Client -->> BaileysStartupService: Error
BaileysStartupService ->> BaileysStartupService: logger.warn(...)
else logout succeeds
Client -->> BaileysStartupService: resolved
end
BaileysStartupService ->> WebSocket: close()
alt ws.close throws
WebSocket -->> BaileysStartupService: Error (ignored)
else ws.close succeeds
WebSocket -->> BaileysStartupService: closed
end
BaileysStartupService ->> BaileysStartupService: stateConnection = { state: close, statusReason: 401 }
BaileysStartupService ->> Prisma: session.delete({ sessionId: instanceId })
Prisma ->> Database: delete session
Database -->> Prisma: success
BaileysStartupService ->> Prisma: instance.update({ id: instanceId, connectionStatus: close })
Prisma ->> Database: update instance.connectionStatus = close
Database -->> Prisma: success
Prisma -->> BaileysStartupService: done
deactivate BaileysStartupService
BaileysStartupService -->> ApiServer: logout completed
ApiServer -->> AdminUser: Logout successful
Class diagram for updated BaileysStartupService connection lifecycle handlingclassDiagram
class ChannelStartupService {
}
class BaileysStartupService {
- boolean endSession
- any messageProcessor
- any client
- any logger
- any configService
- any prismaRepository
- any instance
- string instanceId
- string instanceName
- string phoneNumber
- any stateConnection
+ logoutInstance() Promise~void~
+ connectToWhatsapp(phoneNumber string) Promise~void~
+ connectionUpdate(connection string, lastDisconnect any) Promise~void~
+ getProfileName() Promise~string~
+ profilePicture(wuid string) Promise~string~
}
ChannelStartupService <|-- BaileysStartupService
class PrismaRepository {
+ sessionDelete(sessionId string) Promise~void~
+ instanceUpdate(id string, connectionStatus string) Promise~void~
}
class Client {
+ logout(reason string) Promise~void~
+ wsClose() void
+ user any
}
class Instance {
+ string id
+ string wuid
+ string connectionStatus
}
BaileysStartupService o-- PrismaRepository : uses
BaileysStartupService o-- Client : manages
BaileysStartupService o-- Instance : updates
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey - I've left some high level feedback:
- In
logoutInstance, consider handling or at least logging failures from theinstance.updatecall so that DB write issues during logout are visible rather than silently failing after the state has been set toclosein memory. - When setting
this.stateConnection = { state: 'close', statusReason: 401 }, consider deriving the status code from the actual disconnect reason (similar tostatusCodehandling inconnection === 'close') so the in-memory state more accurately reflects the underlying cause.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In `logoutInstance`, consider handling or at least logging failures from the `instance.update` call so that DB write issues during logout are visible rather than silently failing after the state has been set to `close` in memory.
- When setting `this.stateConnection = { state: 'close', statusReason: 401 }`, consider deriving the status code from the actual disconnect reason (similar to `statusCode` handling in `connection === 'close'`) so the in-memory state more accurately reflects the underlying cause.Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
📋 Description
Improves the reliability of the WhatsApp instance logout flow and prevents crashes during connection lifecycle events.
Changes in
BaileysStartupService:logoutInstance(): setsendSession = truebefore teardown so reconnection is suppressed; wrapsclient.logout()andclient.ws.close()in individual try/catch blocks to gracefully handle already-disconnected states; forcesstateConnectionto{ state: 'close', statusReason: 401 }and updates the instanceconnectionStatusto'close'in the database after cleanup.408tocodesToNotReconnectto avoid reconnection loops on request-timeout disconnects.client.user?.idonconnection === 'open'to prevent aTypeErrorcrash when Baileys fires the open event before the user object is populated.🔗 Related Issue
Closes #(issue_number)
🧪 Type of Change
🧪 Testing
📸 Screenshots (if applicable)
N/A
✅ Checklist
📝 Additional Notes
The
client.logout()call can throw when the WebSocket is already closed (e.g. after a network drop). Previously this would leave the instance in an inconsistent state in the database. The new flow ensures the database record always reflectsconnectionStatus: 'close'regardless of whether the Baileys client was reachable during logout.Summary by Sourcery
Improve reliability and safety of WhatsApp instance logout and connection handling.
Bug Fixes:
Enhancements: