actioncable 5.0.1 → 6.1.3
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +5 -5
- data/CHANGELOG.md +31 -117
- data/MIT-LICENSE +1 -1
- data/README.md +4 -535
- data/app/assets/javascripts/action_cable.js +517 -0
- data/lib/action_cable.rb +20 -10
- data/lib/action_cable/channel.rb +3 -0
- data/lib/action_cable/channel/base.rb +31 -23
- data/lib/action_cable/channel/broadcasting.rb +22 -10
- data/lib/action_cable/channel/callbacks.rb +4 -2
- data/lib/action_cable/channel/naming.rb +5 -2
- data/lib/action_cable/channel/periodic_timers.rb +4 -3
- data/lib/action_cable/channel/streams.rb +39 -11
- data/lib/action_cable/channel/test_case.rb +310 -0
- data/lib/action_cable/connection.rb +3 -2
- data/lib/action_cable/connection/authorization.rb +8 -6
- data/lib/action_cable/connection/base.rb +34 -26
- data/lib/action_cable/connection/client_socket.rb +20 -18
- data/lib/action_cable/connection/identification.rb +5 -4
- data/lib/action_cable/connection/internal_channel.rb +4 -2
- data/lib/action_cable/connection/message_buffer.rb +3 -2
- data/lib/action_cable/connection/stream.rb +9 -5
- data/lib/action_cable/connection/stream_event_loop.rb +4 -2
- data/lib/action_cable/connection/subscriptions.rb +14 -13
- data/lib/action_cable/connection/tagged_logger_proxy.rb +4 -2
- data/lib/action_cable/connection/test_case.rb +234 -0
- data/lib/action_cable/connection/web_socket.rb +7 -5
- data/lib/action_cable/engine.rb +7 -5
- data/lib/action_cable/gem_version.rb +5 -3
- data/lib/action_cable/helpers/action_cable_helper.rb +6 -4
- data/lib/action_cable/remote_connections.rb +9 -4
- data/lib/action_cable/server.rb +2 -1
- data/lib/action_cable/server/base.rb +17 -10
- data/lib/action_cable/server/broadcasting.rb +9 -3
- data/lib/action_cable/server/configuration.rb +21 -22
- data/lib/action_cable/server/connections.rb +2 -0
- data/lib/action_cable/server/worker.rb +11 -11
- data/lib/action_cable/server/worker/active_record_connection_management.rb +2 -0
- data/lib/action_cable/subscription_adapter.rb +4 -0
- data/lib/action_cable/subscription_adapter/async.rb +3 -1
- data/lib/action_cable/subscription_adapter/base.rb +6 -0
- data/lib/action_cable/subscription_adapter/channel_prefix.rb +28 -0
- data/lib/action_cable/subscription_adapter/inline.rb +2 -0
- data/lib/action_cable/subscription_adapter/postgresql.rb +40 -14
- data/lib/action_cable/subscription_adapter/redis.rb +19 -11
- data/lib/action_cable/subscription_adapter/subscriber_map.rb +3 -1
- data/lib/action_cable/subscription_adapter/test.rb +40 -0
- data/lib/action_cable/test_case.rb +11 -0
- data/lib/action_cable/test_helper.rb +133 -0
- data/lib/action_cable/version.rb +3 -1
- data/lib/rails/generators/channel/USAGE +5 -6
- data/lib/rails/generators/channel/channel_generator.rb +16 -11
- data/lib/rails/generators/channel/templates/application_cable/{channel.rb → channel.rb.tt} +0 -0
- data/lib/rails/generators/channel/templates/application_cable/{connection.rb → connection.rb.tt} +0 -0
- data/lib/rails/generators/channel/templates/{channel.rb → channel.rb.tt} +0 -0
- data/lib/rails/generators/channel/templates/{assets/channel.js → javascript/channel.js.tt} +6 -4
- data/lib/rails/generators/channel/templates/javascript/consumer.js.tt +6 -0
- data/lib/rails/generators/channel/templates/javascript/index.js.tt +5 -0
- data/lib/rails/generators/test_unit/channel_generator.rb +20 -0
- data/lib/rails/generators/test_unit/templates/channel_test.rb.tt +8 -0
- metadata +46 -38
- data/lib/action_cable/connection/faye_client_socket.rb +0 -48
- data/lib/action_cable/connection/faye_event_loop.rb +0 -44
- data/lib/action_cable/subscription_adapter/evented_redis.rb +0 -79
- data/lib/assets/compiled/action_cable.js +0 -597
- data/lib/rails/generators/channel/templates/assets/cable.js +0 -13
- data/lib/rails/generators/channel/templates/assets/channel.coffee +0 -14
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
|
-
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 7bf2f7592d39b77dce7363898a15d105fa654c8dfe8144b6b07eebbb62304850
|
4
|
+
data.tar.gz: fee2ad27c35d436b4ecff6c112738ee4acfadecd4de3702781ca4537a671bb21
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: 9b26fd705356a9ba97348ed0f45e134bb588fcc3d7498b4c445b345d7452e804c9027784073a7c20d4025d338c9ffd2469bd4856ecf72ec2bc4ed758aaa71ed0
|
7
|
+
data.tar.gz: 710400f215950d2df3515c051d607d92287cf2e47638c979bf6babfae90045f320cf6d18fa08f73d63d62346334e7f3f5cf3871bbe9772f01492818a721ebf3e
|
data/CHANGELOG.md
CHANGED
@@ -1,146 +1,60 @@
|
|
1
|
-
## Rails
|
1
|
+
## Rails 6.1.3 (February 17, 2021) ##
|
2
2
|
|
3
3
|
* No changes.
|
4
4
|
|
5
5
|
|
6
|
-
## Rails
|
6
|
+
## Rails 6.1.2.1 (February 10, 2021) ##
|
7
7
|
|
8
8
|
* No changes.
|
9
9
|
|
10
10
|
|
11
|
-
## Rails
|
11
|
+
## Rails 6.1.2 (February 09, 2021) ##
|
12
12
|
|
13
|
-
*
|
14
|
-
|
15
|
-
New option `config.action_cable.allow_same_origin_as_host = false`
|
16
|
-
to disable.
|
17
|
-
|
18
|
-
*Dávid Halász*, *Matthew Draper*
|
19
|
-
|
20
|
-
* Fixed and added a workaround to avoid race condition, when one
|
21
|
-
thread closed the IO, when an another thread was still trying read
|
22
|
-
from IO on a connection.
|
23
|
-
|
24
|
-
*Matthew Draper*
|
25
|
-
|
26
|
-
* Shutdown pubsub connection before classes are reloaded, to avoid
|
27
|
-
hangups caused by pubsub still holding reference to Active Record
|
28
|
-
connection from the pool, and Active Record trying to cleanup the pool.
|
29
|
-
|
30
|
-
*Jon Moss*
|
31
|
-
|
32
|
-
* Prevent race where the client could receive and act upon a
|
33
|
-
subscription confirmation before the channel's `subscribed` method
|
34
|
-
completed.
|
35
|
-
|
36
|
-
Fixes #25381.
|
37
|
-
|
38
|
-
*Vladimir Dementyev*
|
39
|
-
|
40
|
-
* Buffer writes to websocket connections, to avoid blocking threads
|
41
|
-
that could be doing more useful things.
|
42
|
-
|
43
|
-
*Matthew Draper*, *Tinco Andringa*
|
44
|
-
|
45
|
-
* Invocation of channel action is now prevented, if subscription
|
46
|
-
connection was rejected.
|
47
|
-
|
48
|
-
Fixes #23757.
|
49
|
-
|
50
|
-
*Jon Moss*
|
51
|
-
|
52
|
-
* Protect against concurrent writes to a websocket connection from
|
53
|
-
multiple threads; the underlying OS write is not always threadsafe.
|
54
|
-
|
55
|
-
*Tinco Andringa*
|
56
|
-
|
57
|
-
* Close hijacked socket when connection is shut down.
|
58
|
-
|
59
|
-
Fixes #25613.
|
60
|
-
|
61
|
-
*Tinco Andringa*
|
62
|
-
|
63
|
-
|
64
|
-
## Rails 5.0.0 (June 30, 2016) ##
|
65
|
-
|
66
|
-
* Fix development reloading support: new cable connections are now correctly
|
67
|
-
dispatched to the reloaded channel class, instead of using a cached reference
|
68
|
-
to the originally-loaded version.
|
69
|
-
|
70
|
-
*Matthew Draper*
|
13
|
+
* No changes.
|
71
14
|
|
72
|
-
* WebSocket protocol negotiation.
|
73
15
|
|
74
|
-
|
75
|
-
of and, hopefully, more slowly than Action Cable itself. Client sockets
|
76
|
-
negotiate a protocol with the Cable server using WebSockets' native
|
77
|
-
subprotocol support:
|
78
|
-
* https://tools.ietf.org/html/rfc6455#section-1.9
|
79
|
-
* https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#Subprotocols
|
16
|
+
## Rails 6.1.1 (January 07, 2021) ##
|
80
17
|
|
81
|
-
|
82
|
-
the Cable server with a browser still running old JavaScript) then the
|
83
|
-
client knows to disconnect, cease retrying, and tell the app that it hit
|
84
|
-
a protocol mismatch.
|
18
|
+
* No changes.
|
85
19
|
|
86
|
-
This allows us to evolve the Action Cable message format, handshaking,
|
87
|
-
pings, acknowledgements, and more without breaking older clients'
|
88
|
-
expectations of server behavior.
|
89
20
|
|
90
|
-
|
21
|
+
## Rails 6.1.0 (December 09, 2020) ##
|
91
22
|
|
92
|
-
*
|
23
|
+
* `ActionCable::Connection::Base` now allows intercepting unhandled exceptions
|
24
|
+
with `rescue_from` before they are logged, which is useful for error reporting
|
25
|
+
tools and other integrations.
|
93
26
|
|
94
|
-
|
95
|
-
# `message` is a Ruby hash here instead of a JSON string
|
27
|
+
*Justin Talbott*
|
96
28
|
|
97
|
-
|
98
|
-
which skips decoding entirely.
|
29
|
+
* Add `ActionCable::Channel#stream_or_reject_for` to stream if record is present, otherwise reject the connection
|
99
30
|
|
100
|
-
*
|
31
|
+
*Atul Bhosale*
|
101
32
|
|
102
|
-
* Add
|
33
|
+
* Add `ActionCable::Channel#stop_stream_from` and `#stop_stream_for` to unsubscribe from a specific stream.
|
103
34
|
|
104
|
-
*
|
35
|
+
*Zhang Kang*
|
105
36
|
|
106
|
-
*
|
107
|
-
loads, and disconnecting all cables during reload.
|
37
|
+
* Add PostgreSQL subscription connection identificator.
|
108
38
|
|
109
|
-
|
39
|
+
Now you can distinguish Action Cable PostgreSQL subscription connections among others.
|
40
|
+
Also, you can set custom `id` in `cable.yml` configuration.
|
110
41
|
|
111
|
-
|
42
|
+
```sql
|
43
|
+
SELECT application_name FROM pg_stat_activity;
|
44
|
+
/*
|
45
|
+
application_name
|
46
|
+
------------------------
|
47
|
+
psql
|
48
|
+
ActionCable-PID-42
|
49
|
+
(2 rows)
|
50
|
+
*/
|
51
|
+
```
|
112
52
|
|
113
|
-
*
|
53
|
+
*Sergey Ponomarev*
|
114
54
|
|
115
|
-
*
|
116
|
-
`ActionCable::SubscriptionAdapter::EventedRedis` and added `redis_connector`
|
117
|
-
to `ActionCable::SubscriptionAdapter::Redis`, so you can overwrite with your
|
118
|
-
own initializers. This is used when you want to use different-than-standard
|
119
|
-
Redis adapters, like for Makara distributed Redis.
|
55
|
+
* Subscription confirmations and rejections are now logged at the `DEBUG` level instead of `INFO`.
|
120
56
|
|
121
57
|
*DHH*
|
122
58
|
|
123
|
-
* Support PostgreSQL pubsub adapter.
|
124
|
-
|
125
|
-
*Jon Moss*
|
126
59
|
|
127
|
-
|
128
|
-
|
129
|
-
*Matthew Draper*
|
130
|
-
|
131
|
-
* Remove Celluloid dependency.
|
132
|
-
|
133
|
-
*Mike Perham*
|
134
|
-
|
135
|
-
* Create notion of an `ActionCable::SubscriptionAdapter`.
|
136
|
-
Separate out Redis functionality into
|
137
|
-
`ActionCable::SubscriptionAdapter::Redis`, and add a
|
138
|
-
PostgreSQL adapter as well. Configuration file for
|
139
|
-
ActionCable was changed from`config/redis/cable.yml` to
|
140
|
-
`config/cable.yml`.
|
141
|
-
|
142
|
-
*Jon Moss*
|
143
|
-
|
144
|
-
* Added to Rails!
|
145
|
-
|
146
|
-
*DHH*
|
60
|
+
Please check [6-0-stable](https://github.com/rails/rails/blob/6-0-stable/actioncable/CHANGELOG.md) for previous changes.
|
data/MIT-LICENSE
CHANGED
data/README.md
CHANGED
@@ -7,549 +7,18 @@ and scalable. It's a full-stack offering that provides both a client-side
|
|
7
7
|
JavaScript framework and a server-side Ruby framework. You have access to your full
|
8
8
|
domain model written with Active Record or your ORM of choice.
|
9
9
|
|
10
|
-
|
11
|
-
## Terminology
|
12
|
-
|
13
|
-
A single Action Cable server can handle multiple connection instances. It has one
|
14
|
-
connection instance per WebSocket connection. A single user may have multiple
|
15
|
-
WebSockets open to your application if they use multiple browser tabs or devices.
|
16
|
-
The client of a WebSocket connection is called the consumer.
|
17
|
-
|
18
|
-
Each consumer can in turn subscribe to multiple cable channels. Each channel encapsulates
|
19
|
-
a logical unit of work, similar to what a controller does in a regular MVC setup. For example,
|
20
|
-
you could have a `ChatChannel` and an `AppearancesChannel`, and a consumer could be subscribed to either
|
21
|
-
or to both of these channels. At the very least, a consumer should be subscribed to one channel.
|
22
|
-
|
23
|
-
When the consumer is subscribed to a channel, they act as a subscriber. The connection between
|
24
|
-
the subscriber and the channel is, surprise-surprise, called a subscription. A consumer
|
25
|
-
can act as a subscriber to a given channel any number of times. For example, a consumer
|
26
|
-
could subscribe to multiple chat rooms at the same time. (And remember that a physical user may
|
27
|
-
have multiple consumers, one per tab/device open to your connection).
|
28
|
-
|
29
|
-
Each channel can then again be streaming zero or more broadcastings. A broadcasting is a
|
30
|
-
pubsub link where anything transmitted by the broadcaster is sent directly to the channel
|
31
|
-
subscribers who are streaming that named broadcasting.
|
32
|
-
|
33
|
-
As you can see, this is a fairly deep architectural stack. There's a lot of new terminology
|
34
|
-
to identify the new pieces, and on top of that, you're dealing with both client and server side
|
35
|
-
reflections of each unit.
|
36
|
-
|
37
|
-
## Examples
|
38
|
-
|
39
|
-
### A full-stack example
|
40
|
-
|
41
|
-
The first thing you must do is define your `ApplicationCable::Connection` class in Ruby. This
|
42
|
-
is the place where you authorize the incoming connection, and proceed to establish it,
|
43
|
-
if all is well. Here's the simplest example starting with the server-side connection class:
|
44
|
-
|
45
|
-
```ruby
|
46
|
-
# app/channels/application_cable/connection.rb
|
47
|
-
module ApplicationCable
|
48
|
-
class Connection < ActionCable::Connection::Base
|
49
|
-
identified_by :current_user
|
50
|
-
|
51
|
-
def connect
|
52
|
-
self.current_user = find_verified_user
|
53
|
-
end
|
54
|
-
|
55
|
-
protected
|
56
|
-
def find_verified_user
|
57
|
-
if current_user = User.find_by(id: cookies.signed[:user_id])
|
58
|
-
current_user
|
59
|
-
else
|
60
|
-
reject_unauthorized_connection
|
61
|
-
end
|
62
|
-
end
|
63
|
-
end
|
64
|
-
end
|
65
|
-
```
|
66
|
-
Here `identified_by` is a connection identifier that can be used to find the specific connection again or later.
|
67
|
-
Note that anything marked as an identifier will automatically create a delegate by the same name on any channel instances created off the connection.
|
68
|
-
|
69
|
-
This relies on the fact that you will already have handled authentication of the user, and
|
70
|
-
that a successful authentication sets a signed cookie with the `user_id`. This cookie is then
|
71
|
-
automatically sent to the connection instance when a new connection is attempted, and you
|
72
|
-
use that to set the `current_user`. By identifying the connection by this same current_user,
|
73
|
-
you're also ensuring that you can later retrieve all open connections by a given user (and
|
74
|
-
potentially disconnect them all if the user is deleted or deauthorized).
|
75
|
-
|
76
|
-
Next, you should define your `ApplicationCable::Channel` class in Ruby. This is the place where you put
|
77
|
-
shared logic between your channels.
|
78
|
-
|
79
|
-
```ruby
|
80
|
-
# app/channels/application_cable/channel.rb
|
81
|
-
module ApplicationCable
|
82
|
-
class Channel < ActionCable::Channel::Base
|
83
|
-
end
|
84
|
-
end
|
85
|
-
```
|
86
|
-
|
87
|
-
The client-side needs to setup a consumer instance of this connection. That's done like so:
|
88
|
-
|
89
|
-
```coffeescript
|
90
|
-
# app/assets/javascripts/cable.coffee
|
91
|
-
#= require action_cable
|
92
|
-
|
93
|
-
@App = {}
|
94
|
-
App.cable = ActionCable.createConsumer("ws://cable.example.com")
|
95
|
-
```
|
96
|
-
|
97
|
-
The `ws://cable.example.com` address must point to your Action Cable server(s), and it
|
98
|
-
must share a cookie namespace with the rest of the application (which may live under http://example.com).
|
99
|
-
This ensures that the signed cookie will be correctly sent.
|
100
|
-
|
101
|
-
That's all you need to establish the connection! But of course, this isn't very useful in
|
102
|
-
itself. This just gives you the plumbing. To make stuff happen, you need content. That content
|
103
|
-
is defined by declaring channels on the server and allowing the consumer to subscribe to them.
|
104
|
-
|
105
|
-
|
106
|
-
### Channel example 1: User appearances
|
107
|
-
|
108
|
-
Here's a simple example of a channel that tracks whether a user is online or not, and also what page they are currently on.
|
109
|
-
(This is useful for creating presence features like showing a green dot next to a user's name if they're online).
|
110
|
-
|
111
|
-
First you declare the server-side channel:
|
112
|
-
|
113
|
-
```ruby
|
114
|
-
# app/channels/appearance_channel.rb
|
115
|
-
class AppearanceChannel < ApplicationCable::Channel
|
116
|
-
def subscribed
|
117
|
-
current_user.appear
|
118
|
-
end
|
119
|
-
|
120
|
-
def unsubscribed
|
121
|
-
current_user.disappear
|
122
|
-
end
|
123
|
-
|
124
|
-
def appear(data)
|
125
|
-
current_user.appear on: data['appearing_on']
|
126
|
-
end
|
127
|
-
|
128
|
-
def away
|
129
|
-
current_user.away
|
130
|
-
end
|
131
|
-
end
|
132
|
-
```
|
133
|
-
|
134
|
-
The `#subscribed` callback is invoked when, as we'll show below, a client-side subscription is initiated. In this case,
|
135
|
-
we take that opportunity to say "the current user has indeed appeared". That appear/disappear API could be backed by
|
136
|
-
Redis or a database or whatever else. Here's what the client-side of that looks like:
|
137
|
-
|
138
|
-
```coffeescript
|
139
|
-
# app/assets/javascripts/cable/subscriptions/appearance.coffee
|
140
|
-
App.cable.subscriptions.create "AppearanceChannel",
|
141
|
-
# Called when the subscription is ready for use on the server
|
142
|
-
connected: ->
|
143
|
-
@install()
|
144
|
-
@appear()
|
145
|
-
|
146
|
-
# Called when the WebSocket connection is closed
|
147
|
-
disconnected: ->
|
148
|
-
@uninstall()
|
149
|
-
|
150
|
-
# Called when the subscription is rejected by the server
|
151
|
-
rejected: ->
|
152
|
-
@uninstall()
|
153
|
-
|
154
|
-
appear: ->
|
155
|
-
# Calls `AppearanceChannel#appear(data)` on the server
|
156
|
-
@perform("appear", appearing_on: $("main").data("appearing-on"))
|
157
|
-
|
158
|
-
away: ->
|
159
|
-
# Calls `AppearanceChannel#away` on the server
|
160
|
-
@perform("away")
|
161
|
-
|
162
|
-
|
163
|
-
buttonSelector = "[data-behavior~=appear_away]"
|
164
|
-
|
165
|
-
install: ->
|
166
|
-
$(document).on "page:change.appearance", =>
|
167
|
-
@appear()
|
168
|
-
|
169
|
-
$(document).on "click.appearance", buttonSelector, =>
|
170
|
-
@away()
|
171
|
-
false
|
172
|
-
|
173
|
-
$(buttonSelector).show()
|
174
|
-
|
175
|
-
uninstall: ->
|
176
|
-
$(document).off(".appearance")
|
177
|
-
$(buttonSelector).hide()
|
178
|
-
```
|
179
|
-
|
180
|
-
Simply calling `App.cable.subscriptions.create` will setup the subscription, which will call `AppearanceChannel#subscribed`,
|
181
|
-
which in turn is linked to the original `App.cable` -> `ApplicationCable::Connection` instances.
|
182
|
-
|
183
|
-
Next, we link the client-side `appear` method to `AppearanceChannel#appear(data)`. This is possible because the server-side
|
184
|
-
channel instance will automatically expose the public methods declared on the class (minus the callbacks), so that these
|
185
|
-
can be reached as remote procedure calls via a subscription's `perform` method.
|
186
|
-
|
187
|
-
### Channel example 2: Receiving new web notifications
|
188
|
-
|
189
|
-
The appearance example was all about exposing server functionality to client-side invocation over the WebSocket connection.
|
190
|
-
But the great thing about WebSockets is that it's a two-way street. So now let's show an example where the server invokes
|
191
|
-
an action on the client.
|
192
|
-
|
193
|
-
This is a web notification channel that allows you to trigger client-side web notifications when you broadcast to the right
|
194
|
-
streams:
|
195
|
-
|
196
|
-
```ruby
|
197
|
-
# app/channels/web_notifications_channel.rb
|
198
|
-
class WebNotificationsChannel < ApplicationCable::Channel
|
199
|
-
def subscribed
|
200
|
-
stream_from "web_notifications_#{current_user.id}"
|
201
|
-
end
|
202
|
-
end
|
203
|
-
```
|
204
|
-
|
205
|
-
```coffeescript
|
206
|
-
# Client-side, which assumes you've already requested the right to send web notifications
|
207
|
-
App.cable.subscriptions.create "WebNotificationsChannel",
|
208
|
-
received: (data) ->
|
209
|
-
new Notification data["title"], body: data["body"]
|
210
|
-
```
|
211
|
-
|
212
|
-
```ruby
|
213
|
-
# Somewhere in your app this is called, perhaps from a NewCommentJob
|
214
|
-
ActionCable.server.broadcast \
|
215
|
-
"web_notifications_#{current_user.id}", { title: 'New things!', body: 'All the news that is fit to print' }
|
216
|
-
```
|
217
|
-
|
218
|
-
The `ActionCable.server.broadcast` call places a message in the Action Cable pubsub queue under a separate broadcasting name for each user. For a user with an ID of 1, the broadcasting name would be `web_notifications_1`.
|
219
|
-
The channel has been instructed to stream everything that arrives at `web_notifications_1` directly to the client by invoking the
|
220
|
-
`#received(data)` callback. The data is the hash sent as the second parameter to the server-side broadcast call, JSON encoded for the trip
|
221
|
-
across the wire, and unpacked for the data argument arriving to `#received`.
|
222
|
-
|
223
|
-
|
224
|
-
### Passing Parameters to Channel
|
225
|
-
|
226
|
-
You can pass parameters from the client side to the server side when creating a subscription. For example:
|
227
|
-
|
228
|
-
```ruby
|
229
|
-
# app/channels/chat_channel.rb
|
230
|
-
class ChatChannel < ApplicationCable::Channel
|
231
|
-
def subscribed
|
232
|
-
stream_from "chat_#{params[:room]}"
|
233
|
-
end
|
234
|
-
end
|
235
|
-
```
|
236
|
-
|
237
|
-
If you pass an object as the first argument to `subscriptions.create`, that object will become the params hash in your cable channel. The keyword `channel` is required.
|
238
|
-
|
239
|
-
```coffeescript
|
240
|
-
# Client-side, which assumes you've already requested the right to send web notifications
|
241
|
-
App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
|
242
|
-
received: (data) ->
|
243
|
-
@appendLine(data)
|
244
|
-
|
245
|
-
appendLine: (data) ->
|
246
|
-
html = @createLine(data)
|
247
|
-
$("[data-chat-room='Best Room']").append(html)
|
248
|
-
|
249
|
-
createLine: (data) ->
|
250
|
-
"""
|
251
|
-
<article class="chat-line">
|
252
|
-
<span class="speaker">#{data["sent_by"]}</span>
|
253
|
-
<span class="body">#{data["body"]}</span>
|
254
|
-
</article>
|
255
|
-
"""
|
256
|
-
```
|
257
|
-
|
258
|
-
```ruby
|
259
|
-
# Somewhere in your app this is called, perhaps from a NewCommentJob
|
260
|
-
ActionCable.server.broadcast \
|
261
|
-
"chat_#{room}", { sent_by: 'Paul', body: 'This is a cool chat app.' }
|
262
|
-
```
|
263
|
-
|
264
|
-
|
265
|
-
### Rebroadcasting message
|
266
|
-
|
267
|
-
A common use case is to rebroadcast a message sent by one client to any other connected clients.
|
268
|
-
|
269
|
-
```ruby
|
270
|
-
# app/channels/chat_channel.rb
|
271
|
-
class ChatChannel < ApplicationCable::Channel
|
272
|
-
def subscribed
|
273
|
-
stream_from "chat_#{params[:room]}"
|
274
|
-
end
|
275
|
-
|
276
|
-
def receive(data)
|
277
|
-
ActionCable.server.broadcast "chat_#{params[:room]}", data
|
278
|
-
end
|
279
|
-
end
|
280
|
-
```
|
281
|
-
|
282
|
-
```coffeescript
|
283
|
-
# Client-side, which assumes you've already requested the right to send web notifications
|
284
|
-
App.chatChannel = App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
|
285
|
-
received: (data) ->
|
286
|
-
# data => { sent_by: "Paul", body: "This is a cool chat app." }
|
287
|
-
|
288
|
-
App.chatChannel.send({ sent_by: "Paul", body: "This is a cool chat app." })
|
289
|
-
```
|
290
|
-
|
291
|
-
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.
|
292
|
-
|
293
|
-
|
294
|
-
### More complete examples
|
295
|
-
|
296
|
-
See the [rails/actioncable-examples](http://github.com/rails/actioncable-examples) repository for a full example of how to setup Action Cable in a Rails app, and how to add channels.
|
297
|
-
|
298
|
-
|
299
|
-
## Configuration
|
300
|
-
|
301
|
-
Action Cable has three required configurations: a subscription adapter, allowed request origins, and the cable server URL (which can optionally be set on the client side).
|
302
|
-
|
303
|
-
### Redis
|
304
|
-
|
305
|
-
By default, `ActionCable::Server::Base` will look for a configuration file in `Rails.root.join('config/cable.yml')`.
|
306
|
-
This file must specify an adapter and a URL for each Rails environment. It may use the following format:
|
307
|
-
|
308
|
-
```yaml
|
309
|
-
production: &production
|
310
|
-
adapter: redis
|
311
|
-
url: redis://10.10.3.153:6381
|
312
|
-
development: &development
|
313
|
-
adapter: redis
|
314
|
-
url: redis://localhost:6379
|
315
|
-
test: *development
|
316
|
-
```
|
317
|
-
|
318
|
-
You can also change the location of the Action Cable config file in a Rails initializer with something like:
|
319
|
-
|
320
|
-
```ruby
|
321
|
-
Rails.application.paths.add "config/cable", with: "somewhere/else/cable.yml"
|
322
|
-
```
|
323
|
-
|
324
|
-
### Allowed Request Origins
|
325
|
-
|
326
|
-
Action Cable will only accept requests from specific origins.
|
327
|
-
|
328
|
-
By default, only an origin matching the cable server itself will be permitted.
|
329
|
-
Additional origins can be specified using strings or regular expressions, provided in an array.
|
330
|
-
|
331
|
-
```ruby
|
332
|
-
Rails.application.config.action_cable.allowed_request_origins = ['http://rubyonrails.com', /http:\/\/ruby.*/]
|
333
|
-
```
|
334
|
-
|
335
|
-
When running in the development environment, this defaults to "http://localhost:3000".
|
336
|
-
|
337
|
-
To disable protection and allow requests from any origin:
|
338
|
-
|
339
|
-
```ruby
|
340
|
-
Rails.application.config.action_cable.disable_request_forgery_protection = true
|
341
|
-
```
|
342
|
-
|
343
|
-
To disable automatic access for same-origin requests, and strictly allow
|
344
|
-
only the configured origins:
|
345
|
-
|
346
|
-
```ruby
|
347
|
-
Rails.application.config.action_cable.allow_same_origin_as_host = false
|
348
|
-
```
|
349
|
-
|
350
|
-
### Consumer Configuration
|
351
|
-
|
352
|
-
Once you have decided how to run your cable server (see below), you must provide the server URL (or path) to your client-side setup.
|
353
|
-
There are two ways you can do this.
|
354
|
-
|
355
|
-
The first is to simply pass it in when creating your consumer. For a standalone server,
|
356
|
-
this would be something like: `App.cable = ActionCable.createConsumer("ws://example.com:28080")`, and for an in-app server,
|
357
|
-
something like: `App.cable = ActionCable.createConsumer("/cable")`.
|
358
|
-
|
359
|
-
The second option is to pass the server URL through the `action_cable_meta_tag` in your layout.
|
360
|
-
This uses a URL or path typically set via `config.action_cable.url` in the environment configuration files, or defaults to "/cable".
|
361
|
-
|
362
|
-
This method is especially useful if your WebSocket URL might change between environments. If you host your production server via https, you will need to use the wss scheme
|
363
|
-
for your Action Cable server, but development might remain http and use the ws scheme. You might use localhost in development and your
|
364
|
-
domain in production.
|
365
|
-
|
366
|
-
In any case, to vary the WebSocket URL between environments, add the following configuration to each environment:
|
367
|
-
|
368
|
-
```ruby
|
369
|
-
config.action_cable.url = "ws://example.com:28080"
|
370
|
-
```
|
371
|
-
|
372
|
-
Then add the following line to your layout before your JavaScript tag:
|
373
|
-
|
374
|
-
```erb
|
375
|
-
<%= action_cable_meta_tag %>
|
376
|
-
```
|
377
|
-
|
378
|
-
And finally, create your consumer like so:
|
379
|
-
|
380
|
-
```coffeescript
|
381
|
-
App.cable = ActionCable.createConsumer()
|
382
|
-
```
|
383
|
-
|
384
|
-
### Other Configurations
|
385
|
-
|
386
|
-
The other common option to configure is the log tags applied to the per-connection logger. Here's close to what we're using in Basecamp:
|
387
|
-
|
388
|
-
```ruby
|
389
|
-
Rails.application.config.action_cable.log_tags = [
|
390
|
-
-> request { request.env['bc.account_id'] || "no-account" },
|
391
|
-
:action_cable,
|
392
|
-
-> request { request.uuid }
|
393
|
-
]
|
394
|
-
```
|
395
|
-
|
396
|
-
For a full list of all configuration options, see the `ActionCable::Server::Configuration` class.
|
397
|
-
|
398
|
-
Also note that your server must provide at least the same number of database connections as you have workers. The default worker pool is set to 4, so that means you have to make at least that available. You can change that in `config/database.yml` through the `pool` attribute.
|
399
|
-
|
400
|
-
|
401
|
-
## Running the cable server
|
402
|
-
|
403
|
-
### Standalone
|
404
|
-
The cable server(s) is separated from your normal application server. It's still a Rack application, but it is its own Rack
|
405
|
-
application. The recommended basic setup is as follows:
|
406
|
-
|
407
|
-
```ruby
|
408
|
-
# cable/config.ru
|
409
|
-
require ::File.expand_path('../../config/environment', __FILE__)
|
410
|
-
Rails.application.eager_load!
|
411
|
-
|
412
|
-
run ActionCable.server
|
413
|
-
```
|
414
|
-
|
415
|
-
Then you start the server using a binstub in bin/cable ala:
|
416
|
-
```
|
417
|
-
#!/bin/bash
|
418
|
-
bundle exec puma -p 28080 cable/config.ru
|
419
|
-
```
|
420
|
-
|
421
|
-
The above will start a cable server on port 28080.
|
422
|
-
|
423
|
-
### In app
|
424
|
-
|
425
|
-
If you are using a server that supports the [Rack socket hijacking API](http://www.rubydoc.info/github/rack/rack/file/SPEC#Hijacking), Action Cable can run alongside your Rails application. For example, to listen for WebSocket requests on `/websocket`, specify that path to `config.action_cable.mount_path`:
|
426
|
-
|
427
|
-
```ruby
|
428
|
-
# config/application.rb
|
429
|
-
class Application < Rails::Application
|
430
|
-
config.action_cable.mount_path = '/websocket'
|
431
|
-
end
|
432
|
-
```
|
433
|
-
|
434
|
-
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.
|
435
|
-
|
436
|
-
### Notes
|
437
|
-
|
438
|
-
Beware that currently the cable server will _not_ auto-reload any changes in the framework. As we've discussed, long-running cable connections mean long-running objects. We don't yet have a way of reloading the classes of those objects in a safe manner. So when you change your channels, or the model your channels use, you must restart the cable server.
|
439
|
-
|
440
|
-
We'll get all this abstracted properly when the framework is integrated into Rails.
|
441
|
-
|
442
|
-
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 authentication. You can see one way of doing that with Devise in this [article](http://www.rubytutorial.io/actioncable-devise-authentication).
|
443
|
-
|
444
|
-
## Dependencies
|
445
|
-
|
446
|
-
Action Cable provides a subscription adapter interface to process its pubsub internals. By default, asynchronous, inline, PostgreSQL, evented Redis, and non-evented Redis adapters are included. The default adapter in new Rails applications is the asynchronous (`async`) adapter. To create your own adapter, you can look at `ActionCable::SubscriptionAdapter::Base` for all methods that must be implemented, and any of the adapters included within Action Cable as example implementations.
|
447
|
-
|
448
|
-
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).
|
449
|
-
|
450
|
-
|
451
|
-
## Deployment
|
452
|
-
|
453
|
-
Action Cable is powered by a combination of WebSockets and threads. All of the
|
454
|
-
connection management is handled internally by utilizing Ruby’s native thread
|
455
|
-
support, which means you can use all your regular Rails models with no problems
|
456
|
-
as long as you haven’t committed any thread-safety sins.
|
457
|
-
|
458
|
-
The Action Cable server does _not_ need to be a multi-threaded application server.
|
459
|
-
This is because Action Cable uses the [Rack socket hijacking API](http://www.rubydoc.info/github/rack/rack/file/SPEC#Hijacking)
|
460
|
-
to take over control of connections from the application server. Action Cable
|
461
|
-
then manages connections internally, in a multithreaded manner, regardless of
|
462
|
-
whether the application server is multi-threaded or not. So Action Cable works
|
463
|
-
with all the popular application servers -- Unicorn, Puma and Passenger.
|
464
|
-
|
465
|
-
Action Cable does not work with WEBrick, because WEBrick does not support the
|
466
|
-
Rack socket hijacking API.
|
467
|
-
|
468
|
-
## Frontend assets
|
469
|
-
|
470
|
-
Action Cable's frontend assets are distributed through two channels: the
|
471
|
-
official gem and npm package, both titled `actioncable`.
|
472
|
-
|
473
|
-
### Gem usage
|
474
|
-
|
475
|
-
Through the `actioncable` gem, Action Cable's frontend assets are
|
476
|
-
available through the Rails Asset Pipeline. Create a `cable.js` or
|
477
|
-
`cable.coffee` file (this is automatically done for you with Rails
|
478
|
-
generators), and then simply require the assets:
|
479
|
-
|
480
|
-
In JavaScript...
|
481
|
-
|
482
|
-
```javascript
|
483
|
-
//= require action_cable
|
484
|
-
```
|
485
|
-
|
486
|
-
... and in CoffeeScript:
|
487
|
-
|
488
|
-
```coffeescript
|
489
|
-
#= require action_cable
|
490
|
-
```
|
491
|
-
|
492
|
-
### npm usage
|
493
|
-
|
494
|
-
In addition to being available through the `actioncable` gem, Action Cable's
|
495
|
-
frontend JS assets are also bundled in an officially supported npm module,
|
496
|
-
intended for usage in standalone frontend applications that communicate with a
|
497
|
-
Rails application. A common use case for this could be if you have a decoupled
|
498
|
-
frontend application written in React, Ember.js, etc. and want to add real-time
|
499
|
-
WebSocket functionality.
|
500
|
-
|
501
|
-
### Installation
|
502
|
-
|
503
|
-
```
|
504
|
-
npm install actioncable --save
|
505
|
-
```
|
506
|
-
|
507
|
-
### Usage
|
508
|
-
|
509
|
-
The `ActionCable` constant is available as a `require`-able module, so
|
510
|
-
you only have to require the package to gain access to the API that is
|
511
|
-
provided.
|
512
|
-
|
513
|
-
In JavaScript...
|
514
|
-
|
515
|
-
```javascript
|
516
|
-
ActionCable = require('actioncable')
|
517
|
-
|
518
|
-
var cable = ActionCable.createConsumer('wss://RAILS-API-PATH.com/cable')
|
519
|
-
|
520
|
-
cable.subscriptions.create('AppearanceChannel', {
|
521
|
-
// normal channel code goes here...
|
522
|
-
});
|
523
|
-
```
|
524
|
-
|
525
|
-
and in CoffeeScript...
|
526
|
-
|
527
|
-
```coffeescript
|
528
|
-
ActionCable = require('actioncable')
|
529
|
-
|
530
|
-
cable = ActionCable.createConsumer('wss://RAILS-API-PATH.com/cable')
|
531
|
-
|
532
|
-
cable.subscriptions.create 'AppearanceChannel',
|
533
|
-
# normal channel code goes here...
|
534
|
-
```
|
535
|
-
|
536
|
-
## License
|
537
|
-
|
538
|
-
Action Cable is released under the MIT license:
|
539
|
-
|
540
|
-
* http://www.opensource.org/licenses/MIT
|
541
|
-
|
10
|
+
You can read more about Action Cable in the [Action Cable Overview](https://edgeguides.rubyonrails.org/action_cable_overview.html) guide.
|
542
11
|
|
543
12
|
## Support
|
544
13
|
|
545
14
|
API documentation is at:
|
546
15
|
|
547
|
-
*
|
16
|
+
* https://api.rubyonrails.org
|
548
17
|
|
549
|
-
Bug reports
|
18
|
+
Bug reports for the Ruby on Rails project can be filed here:
|
550
19
|
|
551
20
|
* https://github.com/rails/rails/issues
|
552
21
|
|
553
22
|
Feature requests should be discussed on the rails-core mailing list here:
|
554
23
|
|
555
|
-
* https://
|
24
|
+
* https://discuss.rubyonrails.org/c/rubyonrails-core
|