Skip to content

fix(instance): preserve partial settings and enforce instance scope - #136

Open
cesar-carlos wants to merge 3 commits into
evolution-foundation:mainfrom
cesar-carlos:fix/instance-settings-partial-update
Open

cesar-carlos wants to merge 3 commits into
evolution-foundation:mainfrom
cesar-carlos:fix/instance-settings-partial-update

Conversation

@cesar-carlos

@cesar-carlos cesar-carlos commented Jul 27, 2026 •

Copy link
Copy Markdown

Summary

Connecting with an empty or partial body could reset persisted event and producer settings. Updating a single advanced flag could also overwrite omitted flags. This change makes these operations preserve existing settings and validates access to path-based advanced settings against the authenticated instance.

  • Persist only provided connect settings, preserving omitted/empty producer fields and event subscriptions. Use MESSAGE only as the initial event default; normalize/deduplicate subscriptions, expand ALL in any position and reject non-empty lists with no valid events.
  • Preserve omitted/null advanced fields while accepting explicit false flags and an empty msgRejectCall to clear the rejection message.
  • Validate the path UUID against the instance authenticated by apikey for both advanced-settings endpoints. Return 400 for invalid input, 403 for a mismatched instance and 404 for a missing row.
  • Reject null root request bodies without panicking, propagate persistence/read failures, and return full persisted settings instead of reporting success with an incomplete request payload.
  • Apply connect settings to a snapshot so failed writes do not mutate the source instance. A runtime sync failure must not replace an already running client.
  • Add HTTP authorization/contract tests, JSON presence tests, scoped PostgreSQL SQL expectations, failure/rollback checks and connect snapshot/runtime regression tests.
  • Update the API guide and regenerate Swagger. Make Swagger generation parse dependencies and propagate generator failures; use the existing pinned swag v1.16.3.

Closes #111

Compatibility

HTTP JSON field names and boolean/string value types are unchanged. PUT advanced-settings intentionally supports partial updates: omitted/null fields preserve saved values, false disables a flag, and msgRejectCall: "" clears the message. Bodies must be JSON objects. Advanced-settings clients must use the matching instance UUID and instance token.

Go callers constructing AdvancedSettings must provide pointer fields, including the newly optional *string MsgRejectCall. Database schema and dependencies are unchanged. Swagger was regenerated from current source; generated definition names now reflect the repository's current module path.

Persistence and runtime synchronization are separate operations: a sync failure or read failure after a successful write may leave the new values saved.

Validation

Executed in Docker with Go 1.25.0, CGO and native media tools:

  • gofmt on changed Go files
  • go build ./...
  • go vet ./...
  • go test -timeout 5m ./...
  • go test -race -timeout 5m ./...
  • make swagger with pinned swag v1.16.3
  • Swagger reference/status validation and git diff --check
  • Regression checks reproduce ignored empty msgRejectCall and missing instance scoping on the previous PR head.
  • A simulated generator failure makes make swagger fail without displaying success.

Also verified the fork's updated local main with build, vet and race tests for instance, user and send packages. No real WhatsApp session or production database was used.

Connect was a destructive upsert: empty subscribe forced events=MESSAGE
and empty rabbitmqEnable/webhook/nats/websocket cleared persisted values
via full Save. Advanced settings PUT wrote omitted bools as false.

Apply connect fields only when explicitly provided, persist with
column-selective Updates, and treat AdvancedSettings bools as pointers
so partial PUTs leave untouched flags alone.

Closes evolution-foundation#111

Co-authored-by: Cursor <cursoragent@cursor.com>

@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.

Sorry @cesar-carlos, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@sourcery-ai

sourcery-ai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Reviewer's Guide

Makes /instance/connect a partial update that only changes explicitly provided fields (preserving existing events and producer flags), switches advanced settings to pointer-based booleans with selective DB updates, and adds tests/utilities to validate the new merge behavior.

Sequence diagram for partial /instance/connect update behavior

sequenceDiagram
  actor Client
  participant InstanceHandler
  participant InstanceService
  participant applyConnectSettings
  participant InstanceRepository
  participant WhatsmeowService

  Client->>InstanceHandler: POST /instance/connect
  InstanceHandler->>InstanceService: Connect(data, instance)
  InstanceService->>applyConnectSettings: applyConnectSettings(instance, data)
  applyConnectSettings-->>InstanceService: updates map[string]interface{}
  alt updates not empty
    InstanceService->>InstanceRepository: UpdateConnectSettings(instance.Id, updates)
    InstanceRepository-->>InstanceService: error or nil
  end
  InstanceService->>WhatsmeowService: UpdateInstanceSettings(instance.Id)
  WhatsmeowService-->>InstanceService: error or nil
  InstanceService-->>InstanceHandler: instance, instance.Jid, eventString
  InstanceHandler-->>Client: 200 OK with events from splitSubscribedEvents(instance.Events)
Loading

File-Level Changes

Change Details Files
Connect endpoint now performs partial updates and persists only explicitly provided connect settings.
  • Refactored Connect to delegate merge logic to applyConnectSettings, which builds a DB updates map based on non-empty incoming fields.
  • Made events subscription logic default to MESSAGE only when both the request and persisted Events are empty.
  • Added splitSubscribedEvents helper to derive subscribedEvents from persisted instance.Events instead of the request body.
  • Introduced repository method UpdateConnectSettings to apply only the computed connect-related field changes in the database.
  • Added logging around changes to events and rabbitmqEnable to surface unexpected config modifications.
pkg/instance/service/instance_service.go
pkg/instance/service/connect_settings.go
pkg/instance/repository/instance_repository.go
pkg/instance/service/connect_settings_test.go
Advanced settings use pointer booleans and selective updates to avoid overwriting unspecified flags.
  • Changed AdvancedSettings struct bools to *bool so JSON omissions are distinguishable from explicit false.
  • Updated Create and GetAdvancedSettings to write/read AdvancedSettings using pointer-aware assignment and BoolPtr helper.
  • Introduced buildAdvancedSettingsUpdates to construct a partial updates map that only includes non-nil booleans and non-empty MsgRejectCall.
  • Updated UpdateAdvancedSettings to use buildAdvancedSettingsUpdates and early-return when there are no fields to persist.
  • Adjusted handler UpdateAdvancedSettings to re-fetch and return persisted settings after update so responses reflect stored values.
  • Added tests for buildAdvancedSettingsUpdates to ensure only intended fields are written.
pkg/instance/model/instance_model.go
pkg/instance/service/instance_service.go
pkg/instance/repository/instance_repository.go
pkg/instance/handler/instance_handler.go
pkg/instance/repository/advanced_settings_test.go

Assessment against linked issues

Issue Objective Addressed Explanation
#111 Prevent /instance/connect from silently resetting Events and RabbitMQ-related settings when fields are omitted, while still defaulting Events to MESSAGE only when no prior value exists, and log changes when these fields are modified. ✅
#111 Make /instance/{id}/advanced-settings a true partial update so omitted boolean flags are not overwritten (e.g., to false), persist only explicitly provided fields, and return the fully persisted settings after update. ✅
#111 Fix the behaviour where an instance stuck in a Reconnecting state causes /instance/qr to never return a QR code, preventing re-pairing. ❌ The PR changes only connect and advanced-settings logic (partial updates, pointer booleans, logging, tests) and does not modify QR code or reconnection handling, so the issue of /instance/qr never returning during a Reconnecting loop remains unaddressed.

Possibly linked issues


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

@cesar-carlos cesar-carlos changed the title fix(instance): stop Connect/advanced-settings from wiping config fix(instance): preserve partial settings and enforce instance scope Oct 8, 2026
C4rlos-Mor4n pushed a commit to C4rlos-Mor4n/evolution-go that referenced this pull request Oct 13, 2026
… branch

Symbol-level comparison (go tool nm) shows rc1 = upstream 0.7.2 + evolution-foundation#117 + evolution-foundation#136 + evolution-foundation#137 + websocket
write serialization + a global ClientMapsMu; all covered (same or superset) by this branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

Instance settings silently reset to defaults (rabbitmqEnable, events, flags) without container restart

1 participant