elsa-workflows / elsa-core

A .NET workflows library
https://v3.elsaworkflows.io/
MIT License
6.51k stars 1.2k forks source link

[BUG] Tenant ID Not Propagating Correctly for MassTransit #6133

Open CODEdire opened 2 days ago

CODEdire commented 2 days ago

Description

When MultiTenancy is configured with MassTransit activities, the Tenant ID is missing during the consume phase and in turn does not start a Tenant's workflow with a trigger activity. It appears that during the middleware to assign the current Tenant using the ITenantContextInitializer, the scope for the InitializeAsync sets the variable for the Tenant on the ITenantAccessor, but immediately reverts the value upon leaving InitializeAsync. This appears to be a function of how AsyncLocal works.

Steps to Reproduce

  1. Configure Elsa.Server.Web with MultiTenancy support.
  2. Set up the API and UI to pass the Tenant ID correctly.
  3. Create a workflow to generate a MassTransit message through the UI, ensuring the Tenant ID is populated in the database.
  4. On the workflow, create a publish message activity for MassTransit
  5. Create a workflow to consume a MassTransit message through the UI, ensuring the Tenant ID is populated in the database.
  6. On the workflow, create a trigger for receiving the previously configured message type.
  7. When the generator workflow is executed with the Tenant ID, it does not trigger the consumer workflow because the Tenant ID is not set on the TenantAccessor.

Expected Behavior

MassTransit Middleware for the TenantConsumeMiddleware should be setting the Tenant on the TenantAccessor to the value from the header.

Actual Behavior

TenantAccessor.Tenant is reverted to NULL upon leaving the InitializeAsync of the DefaultTenantContextInitializer implementation for ITenantContextInitializer

Environment

Troubleshooting Attempts

Moved the logic outside of DefaultTenantContextInitializer to the TenantConsumeMiddleware so that the AsyncLocal version of Tenant was in the same async scope as the next middleware call.

Related Issues

Same underlying issue as #6129