Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Action Cable command callbacks at the connection level #44696

Merged
merged 1 commit into from
May 16, 2022

Conversation

palkan
Copy link
Contributor

@palkan palkan commented Mar 15, 2022

Summary

This PR adds support for command callbacks to ActionCable::Connection::Base. For example,
the before_command callback is invoked before a command is processed by a channel. The after_command and around_command callbacks work similarly.

Other Information

The main motivation behind this PR is to make working with multi-tenant apps easier. Most multi-tenancy libs (apartment, acts_as_tenant to name a few) provide an API to set the current tenant for the block. To make sure that channels code is executed within a particular context, we had to either add smth like Tenant.switch! tenant before every action (too error-prone) or patching the #dispatch_websocket_message method (better, but hacky):

class Connection < ActionCable::Base::Connection
  def dispatch_websocket_message(*)
    using_current_tenant { super }
  end
end

I believe, we need an official API for that (and other similar use cases). With the proposed API, the example above could be rewritten as:

class Connection < ActionCable::Base::Connection
  around_command :set_current_tenant

  private

  def set_current_tenant
    using_current_tenant { yield }
  end
end

Copy link
Contributor

@jorgemanrubia jorgemanrubia left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is great, thanks @palkan.

cc @jeremy

@jeremy jeremy added this to the 7.1.0 milestone May 16, 2022
Copy link
Member

@jeremy jeremy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice integration point for instrumentation as well. Thanks @palkan!

@jeremy jeremy merged commit 5d6c1f6 into rails:main May 16, 2022
@palkan palkan deleted the feat/ac-connection-command-callbacks branch May 18, 2022 06:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants