action_cable_overview.md 24.8 KB
Newer Older
1
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
2

3 4 5
Action Cable Overview
=====================

6
In this guide, you will learn how Action Cable works and how to use WebSockets to
7 8 9 10
incorporate real-time features into your Rails application.

After reading this guide, you will know:

11
* What Action Cable is and its integration backend and frontend
12 13
* How to setup Action Cable
* How to setup channels
14 15 16
* Deployment and Architecture setup for running Action Cable

--------------------------------------------------------------------------------
D
David Kuhta 已提交
17

18 19 20
Introduction
------------

21 22 23 24 25 26 27 28
Action Cable seamlessly integrates
[WebSockets](https://en.wikipedia.org/wiki/WebSocket) with the rest of your
Rails application. It allows for real-time features to be written in Ruby in the
same style and form as the rest of your Rails application, while still being
performant and scalable. It's a full-stack offering that provides both a
client-side JavaScript framework and a server-side Ruby framework. You have
access to your full domain model written with Active Record or your ORM of
choice.
29

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
Terminology
-----------

A single Action Cable server can handle multiple connection instances. It has one
connection instance per WebSocket connection. A single user may have multiple
WebSockets open to your application if they use multiple browser tabs or devices.
The client of a WebSocket connection is called the consumer.

Each consumer can in turn subscribe to multiple cable channels. Each channel
encapsulates a logical unit of work, similar to what a controller does in
a regular MVC setup. For example, you could have a `ChatChannel` and
an `AppearancesChannel`, and a consumer could be subscribed to either
or to both of these channels. At the very least, a consumer should be subscribed
to one channel.

When the consumer is subscribed to a channel, they act as a subscriber.
The connection between the subscriber and the channel is, surprise-surprise,
called a subscription. A consumer can act as a subscriber to a given channel
any number of times. For example, a consumer could subscribe to multiple chat rooms
at the same time. (And remember that a physical user may have multiple consumers,
one per tab/device open to your connection).

Each channel can then again be streaming zero or more broadcastings.
A broadcasting is a pubsub link where anything transmitted by the broadcaster is
sent directly to the channel subscribers who are streaming that named broadcasting.

As you can see, this is a fairly deep architectural stack. There's a lot of new
terminology to identify the new pieces, and on top of that, you're dealing
with both client and server side reflections of each unit.

60 61 62
What is Pub/Sub
---------------

63 64 65 66 67
[Pub/Sub](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern), or
Publish-Subscribe, refers to a message queue paradigm whereby senders of
information (publishers), send data to an abstract class of recipients
(subscribers), without specifying individual recipients. Action Cable uses this
approach to communicate between the server and many clients.
68 69 70 71

## Server-Side Components

### Connections
72

73 74 75 76 77 78 79
*Connections* form the foundation of the client-server relationship. For every
WebSocket accepted by the server, a connection object is instantiated. This
object becomes the parent of all the *channel subscriptions* that are created
from there on. The connection itself does not deal with any specific application
logic beyond authentication and authorization. The client of a WebSocket
connection is called the connection *consumer*. An individual user will create
one consumer-connection pair per browser tab, window, or device they have open.
80

81 82 83
Connections are instances of `ApplicationCable::Connection`. In this class, you
authorize the incoming connection, and proceed to establish it if the user can
be identified.
84 85

#### Connection Setup
86

87 88 89 90 91 92 93 94 95 96
```ruby
# app/channels/application_cable/connection.rb
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

A
Akira Matsuda 已提交
97
    private
98
      def find_verified_user
99
        if verified_user = User.find_by(id: cookies.encrypted[:user_id])
100
          verified_user
101 102 103 104 105 106 107
        else
          reject_unauthorized_connection
        end
      end
  end
end
```
108

109
Here `identified_by` is a connection identifier that can be used to find the
110
specific connection later. Note that anything marked as an identifier will automatically
111
create a delegate by the same name on any channel instances created off the connection.
112

113
This example relies on the fact that you will already have handled authentication of the user
114
somewhere else in your application, and that a successful authentication sets a signed
115
cookie with the user ID.
116 117

The cookie is then automatically sent to the connection instance when a new connection
118
is attempted, and you use that to set the `current_user`. By identifying the connection
119
by this same current user, you're also ensuring that you can later retrieve all open
120
connections by a given user (and potentially disconnect them all if the user is deleted
121
or unauthorized).
122 123

### Channels
124

125
A *channel* encapsulates a logical unit of work, similar to what a controller does in a
126 127
regular MVC setup. By default, Rails creates a parent `ApplicationCable::Channel` class
for encapsulating shared logic between your channels.
128 129

#### Parent Channel Setup
130

131 132 133 134 135 136 137
```ruby
# app/channels/application_cable/channel.rb
module ApplicationCable
  class Channel < ActionCable::Channel::Base
  end
end
```
138 139

Then you would create your own channel classes. For example, you could have a
140
`ChatChannel` and an `AppearanceChannel`:
141 142

```ruby
Y
yuuji.yaginuma 已提交
143
# app/channels/chat_channel.rb
144 145 146
class ChatChannel < ApplicationCable::Channel
end

Y
yuuji.yaginuma 已提交
147
# app/channels/appearance_channel.rb
148 149 150 151
class AppearanceChannel < ApplicationCable::Channel
end
```

152
A consumer could then be subscribed to either or both of these channels.
153 154 155

#### Subscriptions

156 157 158
Consumers subscribe to channels, acting as *subscribers*. Their connection is
called a *subscription*. Produced messages are then routed to these channel
subscriptions based on an identifier sent by the cable consumer.
159 160

```ruby
Y
yuuji.yaginuma 已提交
161
# app/channels/chat_channel.rb
162
class ChatChannel < ApplicationCable::Channel
163
  # Called when the consumer has successfully
164
  # become a subscriber to this channel.
165 166 167 168 169 170
  def subscribed
  end
end
```

## Client-Side Components
171

172
### Connections
173

174
Consumers require an instance of the connection on their side. This can be
175
established using the following JavaScript, which is generated by default by Rails:
176 177

#### Connect Consumer
178

179
```js
180 181 182
// app/javascript/channels/consumer.js
// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
183

184
import { createConsumer } from "@rails/actioncable"
185

186
export default createConsumer()
187
```
188

189
This will ready a consumer that'll connect against `/cable` on your server by default.
190 191
The connection won't be established until you've also specified at least one subscription
you're interested in having.
192 193

#### Subscriber
194

195
A consumer becomes a subscriber by creating a subscription to a given channel:
196

197
```js
198
// app/javascript/channels/chat_channel.js
199 200 201 202
import consumer from "./consumer"

consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" })

203
// app/javascript/channels/appearance_channel.js
204
import consumer from "./consumer"
205

206
consumer.subscriptions.create({ channel: "AppearanceChannel" })
207 208 209 210 211
```

While this creates the subscription, the functionality needed to respond to
received data will be described later on.

212 213 214
A consumer can act as a subscriber to a given channel any number of times. For
example, a consumer could subscribe to multiple chat rooms at the same time:

215
```js
216
// app/javascript/channels/chat_channel.js
217 218 219 220
import consumer from "./consumer"

consumer.subscriptions.create({ channel: "ChatChannel", room: "1st Room" })
consumer.subscriptions.create({ channel: "ChatChannel", room: "2nd Room" })
221 222
```

223 224 225
## Client-Server Interactions

### Streams
226

227 228
*Streams* provide the mechanism by which channels route published content
(broadcasts) to their subscribers.
229 230

```ruby
Y
yuuji.yaginuma 已提交
231
# app/channels/chat_channel.rb
232 233 234 235 236 237 238
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_#{params[:room]}"
  end
end
```

D
David Kuhta 已提交
239 240 241 242 243 244 245 246 247 248 249 250
If you have a stream that is related to a model, then the broadcasting used
can be generated from the model and channel. The following example would
subscribe to a broadcasting like `comments:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE`

```ruby
class CommentsChannel < ApplicationCable::Channel
  def subscribed
    post = Post.find(params[:id])
    stream_for post
  end
end
```
251

252 253 254 255 256
You can then broadcast to this channel like this:

```ruby
CommentsChannel.broadcast_to(@post, @comment)
```
D
David Kuhta 已提交
257

258
### Broadcasting
259

260
A *broadcasting* is a pub/sub link where anything transmitted by a publisher
261
is routed directly to the channel subscribers who are streaming that named
262
broadcasting. Each channel can be streaming zero or more broadcastings.
263

264
Broadcastings are purely an online queue and time-dependent. If a consumer is
265 266
not streaming (subscribed to a given channel), they'll not get the broadcast
should they connect later.
267 268

Broadcasts are called elsewhere in your Rails application:
269

270
```ruby
271 272 273 274 275
WebNotificationsChannel.broadcast_to(
  current_user,
  title: 'New things!',
  body: 'All the news fit to print'
)
276 277
```

278
The `WebNotificationsChannel.broadcast_to` call places a message in the current
279 280 281
subscription adapter's pubsub queue under a separate broadcasting name for each user.
The default pubsub queue for Action Cable is `redis` in production and `async` in development and
test environments. For a user with an ID of 1, the broadcasting name would be `web_notifications:1`.
282 283

The channel has been instructed to stream everything that arrives at
284
`web_notifications:1` directly to the client by invoking the `received`
285 286 287 288
callback.

### Subscriptions

289 290 291
When a consumer is subscribed to a channel, they act as a subscriber. This
connection is called a subscription. Incoming messages are then routed to
these channel subscriptions based on an identifier sent by the cable consumer.
292

293
```js
294
// app/javascript/channels/chat_channel.js
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
// Assumes you've already requested the right to send web notifications
import consumer from "./consumer"

consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
  received(data) {
    this.appendLine(data)
  },

  appendLine(data) {
    const html = this.createLine(data)
    const element = document.querySelector("[data-chat-room='Best Room']")
    element.insertAdjacentHTML("beforeend", html)
  },

  createLine(data) {
    return `
      <article class="chat-line">
        <span class="speaker">${data["sent_by"]}</span>
        <span class="body">${data["body"]}</span>
      </article>
    `
  }
})
318 319
```

320
### Passing Parameters to Channels
321

322 323
You can pass parameters from the client side to the server side when creating a
subscription. For example:
324 325 326 327 328 329 330 331 332 333

```ruby
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_#{params[:room]}"
  end
end
```

334 335
An object passed as the first argument to `subscriptions.create` becomes the
params hash in the cable channel. The keyword `channel` is required:
336

337
```js
338
// app/javascript/channels/chat_channel.js
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
import consumer from "./consumer"

consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
  received(data) {
    this.appendLine(data)
  },

  appendLine(data) {
    const html = this.createLine(data)
    const element = document.querySelector("[data-chat-room='Best Room']")
    element.insertAdjacentHTML("beforeend", html)
  },

  createLine(data) {
    return `
      <article class="chat-line">
        <span class="speaker">${data["sent_by"]}</span>
        <span class="body">${data["body"]}</span>
      </article>
    `
  }
})
361 362 363
```

```ruby
364 365
# Somewhere in your app this is called, perhaps
# from a NewCommentJob.
366
ActionCable.server.broadcast(
367 368 369 370
  "chat_#{room}",
  sent_by: 'Paul',
  body: 'This is a cool chat app.'
)
371 372
```

373
### Rebroadcasting a Message
374

375
A common use case is to *rebroadcast* a message sent by one client to any
376 377 378 379 380 381 382 383 384 385
other connected clients.

```ruby
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_#{params[:room]}"
  end

  def receive(data)
386
    ActionCable.server.broadcast("chat_#{params[:room]}", data)
387 388 389 390
  end
end
```

391
```js
392
// app/javascript/channels/chat_channel.js
393 394 395 396 397 398 399
import consumer from "./consumer"

const chatChannel = consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
  received(data) {
    // data => { sent_by: "Paul", body: "This is a cool chat app." }
  }
}
400

401
chatChannel.send({ sent_by: "Paul", body: "This is a cool chat app." })
402 403 404 405 406 407
```

The rebroadcast will be received by all connected clients, _including_ the
client that sent the message. Note that params are the same as they were when
you subscribed to the channel.

408
## Full-Stack Examples
409 410 411

The following setup steps are common to both examples:

412 413 414 415 416
  1. [Setup your connection](#connection-setup).
  2. [Setup your parent channel](#parent-channel-setup).
  3. [Connect your consumer](#connect-consumer).

### Example 1: User Appearances
417 418 419 420 421

Here's a simple example of a channel that tracks whether a user is online or not
and what page they're on. (This is useful for creating presence features like showing
a green dot next to a user name if they're online).

422
Create the server-side appearance channel:
423 424 425 426 427 428 429 430 431 432 433 434 435

```ruby
# app/channels/appearance_channel.rb
class AppearanceChannel < ApplicationCable::Channel
  def subscribed
    current_user.appear
  end

  def unsubscribed
    current_user.disappear
  end

  def appear(data)
436
    current_user.appear(on: data['appearing_on'])
437 438 439 440 441 442 443 444
  end

  def away
    current_user.away
  end
end
```

445 446 447
When a subscription is initiated the `subscribed` callback gets fired and we
take that opportunity to say "the current user has indeed appeared". That
appear/disappear API could be backed by Redis, a database, or whatever else.
448

449
Create the client-side appearance channel subscription:
450

451
```js
452
// app/javascript/channels/appearance_channel.js
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
import consumer from "./consumer"

consumer.subscriptions.create("AppearanceChannel", {
  // Called once when the subscription is created.
  initialized() {
    this.update = this.update.bind(this)
  },

  // Called when the subscription is ready for use on the server.
  connected() {
    this.install()
    this.update()
  },

  // Called when the WebSocket connection is closed.
  disconnected() {
    this.uninstall()
  },

  // Called when the subscription is rejected by the server.
  rejected() {
    this.uninstall()
  },

  update() {
    this.documentIsActive ? this.appear() : this.away()
  },

  appear() {
    // Calls `AppearanceChannel#appear(data)` on the server.
    this.perform("appear", { appearing_on: this.appearingOn })
  },

  away() {
    // Calls `AppearanceChannel#away` on the server.
    this.perform("away")
  },

  install() {
    window.addEventListener("focus", this.update)
    window.addEventListener("blur", this.update)
    document.addEventListener("turbolinks:load", this.update)
    document.addEventListener("visibilitychange", this.update)
  },

  uninstall() {
    window.removeEventListener("focus", this.update)
    window.removeEventListener("blur", this.update)
    document.removeEventListener("turbolinks:load", this.update)
    document.removeEventListener("visibilitychange", this.update)
  },

  get documentIsActive() {
    return document.visibilityState == "visible" && document.hasFocus()
  },

  get appearingOn() {
    const element = document.querySelector("[data-appearing-on]")
    return element ? element.getAttribute("data-appearing-on") : null
  }
})
514 515 516 517
```

##### Client-Server Interaction

518 519 520 521 522
1. **Client** connects to the **Server** via `App.cable =
ActionCable.createConsumer("ws://cable.example.com")`. (`cable.js`). The
**Server** identifies this connection by `current_user`.

2. **Client** subscribes to the appearance channel via
523
`consumer.subscriptions.create({ channel: "AppearanceChannel" })`. (`appearance_channel.js`)
524 525 526 527 528 529

3. **Server** recognizes a new subscription has been initiated for the
appearance channel and runs its `subscribed` callback, calling the `appear`
method on `current_user`. (`appearance_channel.rb`)

4. **Client** recognizes that a subscription has been established and calls
530 531 532
`connected` (`appearance_channel.js`) which in turn calls `install` and `appear`.
`appear` calls `AppearanceChannel#appear(data)` on the server, and supplies a
data hash of `{ appearing_on: this.appearingOn }`. This is
533 534 535 536 537 538 539 540 541 542 543
possible because the server-side channel instance automatically exposes all
public methods declared on the class (minus the callbacks), so that these can be
reached as remote procedure calls via a subscription's `perform` method.

5. **Server** receives the request for the `appear` action on the appearance
channel for the connection identified by `current_user`
(`appearance_channel.rb`). **Server** retrieves the data with the
`:appearing_on` key from the data hash and sets it as the value for the `:on`
key being passed to `current_user.appear`.

### Example 2: Receiving New Web Notifications
544 545 546 547

The appearance example was all about exposing server functionality to
client-side invocation over the WebSocket connection. But the great thing
about WebSockets is that it's a two-way street. So now let's show an example
548
where the server invokes an action on the client.
549 550 551 552

This is a web notification channel that allows you to trigger client-side
web notifications when you broadcast to the right streams:

553
Create the server-side web notifications channel:
554

555 556 557 558
```ruby
# app/channels/web_notifications_channel.rb
class WebNotificationsChannel < ApplicationCable::Channel
  def subscribed
559
    stream_for current_user
560 561 562 563
  end
end
```

564 565
Create the client-side web notifications channel subscription:

566
```js
567
// app/javascript/channels/web_notifications_channel.js
568 569 570 571 572 573 574 575 576
// Client-side which assumes you've already requested
// the right to send web notifications.
import consumer from "./consumer"

consumer.subscriptions.create("WebNotificationsChannel", {
  received(data) {
    new Notification(data["title"], body: data["body"])
  }
})
577 578
```

579 580
Broadcast content to a web notification channel instance from elsewhere in your
application:
581 582 583

```ruby
# Somewhere in your app this is called, perhaps from a NewCommentJob
584 585 586 587 588
WebNotificationsChannel.broadcast_to(
  current_user,
  title: 'New things!',
  body: 'All the news fit to print'
)
589 590
```

591
The `WebNotificationsChannel.broadcast_to` call places a message in the current
592 593
subscription adapter's pubsub queue under a separate broadcasting name for each
user. For a user with an ID of 1, the broadcasting name would be
594
`web_notifications:1`.
595

596
The channel has been instructed to stream everything that arrives at
597
`web_notifications:1` directly to the client by invoking the `received`
598
callback. The data passed as argument is the hash sent as the second parameter
599 600
to the server-side broadcast call, JSON encoded for the trip across the wire
and unpacked for the data argument arriving as `received`.
601

602
### More Complete Examples
603

J
Jon Moss 已提交
604
See the [rails/actioncable-examples](https://github.com/rails/actioncable-examples)
605 606 607 608
repository for a full example of how to setup Action Cable in a Rails app and adding channels.

## Configuration

609
Action Cable has two required configurations: a subscription adapter and allowed request origins.
610 611 612

### Subscription Adapter

613
By default, Action Cable looks for a configuration file in `config/cable.yml`.
614
The file must specify an adapter for each Rails environment. See the
615
[Dependencies](#dependencies) section for additional information on adapters.
616 617

```yaml
618
development:
619
  adapter: async
620

621 622
test:
  adapter: async
623

624 625 626
production:
  adapter: redis
  url: redis://10.10.3.153:6381
627
  channel_prefix: appname_production
628
```
629 630
#### Adapter Configuration

631 632
Below is a list of the subscription adapters available for end users.

633 634 635 636 637 638
##### Async Adapter

The async adapter is intended for development/testing and should not be used in production.

##### Redis Adapter

639
The Redis adapter requires users to provide a URL pointing to the Redis server.
Y
Yauheni Dakuka 已提交
640
Additionally, a `channel_prefix` may be provided to avoid channel name collisions
641
when using the same Redis server for multiple applications. See the [Redis PubSub documentation](https://redis.io/topics/pubsub#database-amp-scoping) for more details.
642

643
##### PostgreSQL Adapter
644

645 646 647
The PostgreSQL adapter uses Active Record's connection pool, and thus the
application's `config/database.yml` database configuration, for its connection.
This may change in the future. [#27214](https://github.com/rails/rails/issues/27214)
648 649 650 651 652

### Allowed Request Origins

Action Cable will only accept requests from specified origins, which are
passed to the server config as an array. The origins can be instances of
653
strings or regular expressions, against which a check for the match will be performed.
654 655

```ruby
656
config.action_cable.allowed_request_origins = ['http://rubyonrails.com', %r{http://ruby.*}]
657 658 659 660 661
```

To disable and allow requests from any origin:

```ruby
662
config.action_cable.disable_request_forgery_protection = true
663 664 665 666 667 668 669
```

By default, Action Cable allows all requests from localhost:3000 when running
in the development environment.

### Consumer Configuration

670 671 672
To configure the URL, add a call to `action_cable_meta_tag` in your HTML layout
HEAD. This uses a URL or path typically set via `config.action_cable.url` in the
environment configuration files.
673 674 675

### Other Configurations

676
The other common option to configure is the log tags applied to the
677 678
per-connection logger. Here's an example that uses
the user account id if available, else "no-account" while tagging:
679 680

```ruby
681
config.action_cable.log_tags = [
682
  -> request { request.env['user_account_id'] || "no-account" },
683 684 685 686 687
  :action_cable,
  -> request { request.uuid }
]
```

688 689
For a full list of all configuration options, see the
`ActionCable::Server::Configuration` class.
690

691
Also, note that your server must provide at least the same number of database
W
willnet 已提交
692
connections as you have workers. The default worker pool size is set to 4, so
693 694
that means you have to make at least that available. You can change that in
`config/database.yml` through the `pool` attribute.
695

696
## Running Standalone Cable Servers
697 698 699 700

### In App

Action Cable can run alongside your Rails application. For example, to
701 702
listen for WebSocket requests on `/websocket`, specify that path to
`config.action_cable.mount_path`:
703 704

```ruby
705 706 707
# config/application.rb
class Application < Rails::Application
  config.action_cable.mount_path = '/websocket'
708 709 710
end
```

711 712 713
You can use `ActionCable.createConsumer()` to connect to the cable
server if `action_cable_meta_tag` is invoked in the layout. Otherwise, A path is
specified as first argument to `createConsumer` (e.g. `ActionCable.createConsumer("/websocket")`).
714

715 716 717
For every instance of your server you create and for every worker your server
spawns, you will also have a new instance of Action Cable, but the use of Redis
keeps messages synced across connections.
718 719

### Standalone
720

721 722 723
The cable servers can be separated from your normal application server. It's
still a Rack application, but it is its own Rack application. The recommended
basic setup is as follows:
724 725 726

```ruby
# cable/config.ru
727
require_relative '../config/environment'
728 729 730 731 732
Rails.application.eager_load!

run ActionCable.server
```

733
Then you start the server using a binstub in `bin/cable` ala:
734

735 736 737 738 739 740 741 742 743 744 745
```
#!/bin/bash
bundle exec puma -p 28080 cable/config.ru
```

The above will start a cable server on port 28080.

### Notes

The WebSocket server doesn't have access to the session, but it has
access to the cookies. This can be used when you need to handle
746
authentication. You can see one way of doing that with Devise in this [article](https://greg.molnar.io/blog/actioncable-devise-authentication/).
747 748 749 750

## Dependencies

Action Cable provides a subscription adapter interface to process its
751 752
pubsub internals. By default, asynchronous, inline, PostgreSQL, and Redis
adapters are included. The default adapter
753 754 755 756 757 758 759 760
in new Rails applications is the asynchronous (`async`) adapter.

The Ruby side of things is built on top of [websocket-driver](https://github.com/faye/websocket-driver-ruby),
[nio4r](https://github.com/celluloid/nio4r), and [concurrent-ruby](https://github.com/ruby-concurrency/concurrent-ruby).

## Deployment

Action Cable is powered by a combination of WebSockets and threads. Both the
761 762
framework plumbing and user-specified channel work are handled internally by
utilizing Ruby's native thread support. This means you can use all your regular
763 764
Rails models with no problem, as long as you haven't committed any thread-safety sins.

765
The Action Cable server implements the Rack socket hijacking API,
766 767 768
thereby allowing the use of a multithreaded pattern for managing connections
internally, irrespective of whether the application server is multi-threaded or not.

769 770
Accordingly, Action Cable works with popular servers like Unicorn, Puma, and
Passenger.
771 772 773 774 775

## Testing

You can find detailed instructions on how to test your Action Cable functionality in the
[testing guide](testing.html#testing-action-cable).