Skip to content

on_connect handler not invoked on initial connection (race condition) #98

@patsteel

Description

@patsteel

Description

The on_connect handler registered via @mqtt.on_connect() decorator is not invoked during the initial broker connection when using the lifespan pattern.

Root Cause

In fastmqtt.py, mqtt_startup() calls connection() which connects to the broker. The broker immediately fires __on_connect(), which checks:

if self.mqtt_handlers.user_connect_handler is not None:
    self.mqtt_handlers.user_connect_handler(client, flags, rc, properties)

However, if handler registration (via decorators) occurs after mqtt_startup() completes, user_connect_handler is None at connection time, so the callback never fires.

Reproduction

@asynccontextmanager
async def lifespan(app: FastAPI):
    await mqtt.mqtt_startup()  # Connects immediately, on_connect fires here
    yield
    await mqtt.mqtt_shutdown()

@mqtt.on_connect()
def on_connect(client, flags, rc, properties):
    # This never executes on initial connection
    mqtt.client.subscribe("my/topic")

Expected Behavior

on_connect handler should be invoked for the initial connection, not just reconnections.

Suggested Fix

Either:

  1. Defer __on_connect callback until handlers are registered
  2. Re-invoke handlers after mqtt_startup() completes if connection is already established
  3. Document that all decorators must be processed before mqtt_startup()

Environment

  • fastapi-mqtt: 2.2.0
  • Python: 3.11

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions