Skip to content

[1.x] Fix MQTT disconnect status message handling #3543

@amnonbb

Description

@amnonbb

What version of Janus is this happening on?
Master

Have you tested a more recent version of Janus too?
Yes

Additional context
Currently, when the MQTT client disconnects normally (via MQTTAsync_disconnect), the status message is not sent reliably. This happens because:

  1. The will message (configured with disconnect status) is not published by the broker during normal disconnect (as per MQTT spec)
  2. The explicit status message publication sometimes fails due to timing issues with the disconnect process

Changes made:

  1. Moved status message publication to the beginning of the disconnect process
  2. Added a small delay after message publication to ensure delivery
  3. Improved error handling to continue disconnect even if status message fails

Code changes:

int janus_mqtt_client_disconnect(janus_mqtt_context *ctx) {
    /* First, send disconnect status message */
    if (ctx->status.enabled && ctx->status.disconnect_message != NULL) {
        int rc = janus_mqtt_client_publish_status_message(ctx, ctx->status.disconnect_message);
        if (rc != MQTTASYNC_SUCCESS) {
            JANUS_LOG(LOG_ERR, "Failed to publish disconnect status MQTT message, topic: %s, message: %s, return code: %d\n", 
                ctx->status.topic, ctx->status.disconnect_message, rc);
            /* Continue disconnect even if status message fails */
        }
    }

    /* Give time for message delivery */
    g_usleep(100000); // 100ms delay

    /* Now proceed with disconnect */
    MQTTAsync_disconnectOptions options = MQTTAsync_disconnectOptions_initializer;
    // ... rest of disconnect code ...
}

Alternative approaches that could be considered:

  1. Use MQTT 5.0's Will Delay Interval property to delay will message publication
  2. Implement a two-phase disconnect process with explicit status message
  3. Use a separate status topic for disconnect notifications
  4. Implement a heartbeat mechanism to detect unexpected disconnects

Testing:

  • Normal disconnect: status message is now sent reliably
  • Unexpected disconnect (e.g., SIGKILL): will message is published by broker
  • No more errors during disconnect process

References:

  • MQTT 3.1.1 spec, section 3.14.4 "DISCONNECT Actions"
  • MQTT 5.0 spec, section 3.14.4 "DISCONNECT Actions"

This fix ensures that the disconnect status is always communicated to the broker, either through explicit message or will message, depending on the disconnect type.

That's what Cursor AI suggest, i don't know if it's best fix, but it's work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions