Causation

The core of the command dispatcher.

Note

Middleware uses ContextVar to store state per thread or async tasks.

Usage

Tracks the requests that trigger other request. The middleware will add a causation and correlation identifier to every message.

  • The causation identifier relates to the request that triggered this request.

  • The correlation identifier relates to the original request that triggered all parent requests. The request passed to the message bus.

This middleware relies on the Identity context added by the IdentityMiddleware.

Registration

Add the middleware to your bus. This middleware should come after the IdentityMiddleware.

bus = (
    banshee.builder()
    .with_middleware(banshee.IdentityMiddleware())
    .with_middleware(banshee.CausationMiddleware())
    .with_locator(registry)
    .build()
)

Context

A Causation context instance stores the causation and correlation identifiers for the message.

causation_id = message[banshee.Causation].causation_id
correlation_id = message[banshee.Causation].correlation_id

Reference

class banshee.Causation(causation_id, correlation_id)

Bases: object

Causation context.

Holds the identity of the request that created this request, and the root request for correlating related events.

Parameters
  • causation_id (UUID) – parent identifier

  • correlation_id (UUID) – root identifier

Return type

None

causation_id: UUID

parent identifier

correlation_id: UUID

root identifier

class banshee.CausationMiddleware

Bases: Middleware

Causation middleware.

Add causation and correlation identifiers to messages based on the messages Identity context.

The correlation_id will be set based on the first message in a chains unique_id, and the causation_id will be set based on the previous message in a chains unique_id.

When no Identity context is present this handler will pass the message unchanged.

Return type

None

async __call__(message, handle)

Handle message.

Add causation and correlation identifiers to the message and forward it to the next handler in the chain.

Parameters
Returns

processed message

Return type

Message[T]