anycable-rails-core 1.6.2 → 1.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +17 -0
- data/MIT-LICENSE +1 -1
- data/README.md +12 -0
- data/lib/anycable/rails/channel/presence.rb +1 -1
- data/lib/anycable/rails/version.rb +1 -1
- data/lib/generators/anycable/bin/USAGE +3 -1
- data/lib/generators/anycable/bin/bin_generator.rb +7 -6
- data/lib/generators/anycable/bin/templates/bin/anycable-go.tt +4 -3
- data/lib/generators/anycable/download/download_generator.rb +2 -11
- data/lib/generators/anycable/setup/USAGE +8 -0
- data/lib/generators/anycable/setup/setup_generator.rb +104 -68
- data/lib/generators/anycable/setup/templates/Procfile.dev.tt +1 -1
- data/lib/generators/anycable/with_release_helpers.rb +69 -0
- data/lib/puma/plugin/anycable.rb +171 -0
- data/skills/anycable-rails/SKILL.md +82 -0
- data/skills/anycable-rails/references/deployment.md +187 -0
- data/skills/anycable-rails/references/hotwire.md +269 -0
- data/skills/anycable-rails/references/installation.md +292 -0
- data/skills/anycable-rails/references/live-checks.md +129 -0
- data/skills/anycable-rails/references/personalization.md +114 -0
- data/skills/anycable-rails/references/presence.md +240 -0
- data/skills/anycable-rails/references/realtime-features.md +231 -0
- data/skills/anycable-rails/references/testing.md +145 -0
- data/skills/anycable-rails/references/troubleshooting.md +128 -0
- data/skills/anycable-rails/scenarios/channel.yml +51 -0
- data/skills/anycable-rails/scenarios/signed-stream.yml +38 -0
- metadata +18 -3
- data/lib/generators/anycable/setup/templates/bin/anycable-go.tt +0 -27
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
# Hotwire and Turbo Streams with AnyCable
|
|
2
|
+
|
|
3
|
+
Summary: Turbo Streams work with AnyCable without RPC. Use `@anycable/turbo-stream` instead of `@hotwired/turbo-rails` on the client.
|
|
4
|
+
Sign streams with the AnyCable secret. Broadcast from jobs. Use broadcasts to others and the presence element when the feature needs them.
|
|
5
|
+
|
|
6
|
+
Docs: <https://docs.anycable.io/guides/hotwire>. Package: <https://github.com/anycable/anycable-client/tree/master/packages/turbo-stream>.
|
|
7
|
+
|
|
8
|
+
## 1. How it works
|
|
9
|
+
|
|
10
|
+
```text
|
|
11
|
+
turbo_stream_from → <turbo-cable-stream-source signed-stream-name="...">
|
|
12
|
+
│ subscribe (Turbo::StreamsChannel)
|
|
13
|
+
▼
|
|
14
|
+
Rails ── broadcast ──▶ AnyCable server ── message ──▶ Turbo renders <turbo-stream>
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- The AnyCable server verifies the signed stream name itself. Rails is not called.
|
|
18
|
+
- The view helpers and the model broadcasts of `turbo-rails` do not change.
|
|
19
|
+
- Only the JS side changes: `@anycable/turbo-stream` registers the `<turbo-cable-stream-source>` element with the AnyCable client.
|
|
20
|
+
|
|
21
|
+
## 2. Server and Rails setup
|
|
22
|
+
|
|
23
|
+
The generator does all of this for Hotwire apps (`installation.md` §2). Check each item:
|
|
24
|
+
|
|
25
|
+
1. Rails signs Turbo streams with the AnyCable secret: `config.turbo.signed_stream_verifier_key = AnyCable.config.secret` in `config/application.rb`.
|
|
26
|
+
2. The server accepts Turbo streams: `[streams] turbo = true` in `anycable.toml`, or `ANYCABLE_TURBO_STREAMS=true`.
|
|
27
|
+
3. The server has the same secret: `ANYCABLE_SECRET`.
|
|
28
|
+
4. Apps without custom channels run without RPC: `--rpc=none` (`installation.md` §1). Use JWT for authentication (`installation.md` §4).
|
|
29
|
+
|
|
30
|
+
A `turbo_stream_from` with a custom `channel:` option needs RPC. Only `Turbo::StreamsChannel` works without RPC.
|
|
31
|
+
|
|
32
|
+
## 3. JS packages
|
|
33
|
+
|
|
34
|
+
Install the packages:
|
|
35
|
+
|
|
36
|
+
| Bundler | Command |
|
|
37
|
+
|---|---|
|
|
38
|
+
| Importmap | `bin/importmap pin @hotwired/turbo @anycable/web @anycable/turbo-stream` |
|
|
39
|
+
| Yarn | `yarn add @anycable/web @anycable/turbo-stream` |
|
|
40
|
+
| npm | `npm install @anycable/web @anycable/turbo-stream` |
|
|
41
|
+
|
|
42
|
+
Remove `@hotwired/turbo-rails` from the JS (the Ruby gem `turbo-rails` stays). Pin or install `@hotwired/turbo` instead.
|
|
43
|
+
|
|
44
|
+
Warning: `@hotwired/turbo-rails` also puts the HTTP method of `data-turbo-method` links into a `_method` form param (`fetch_requests.js`). Without it, Turbo sends a real `DELETE` (or `PATCH`, `PUT`). A `302` redirect after it is followed with the same method, and the request fails. Before the switch:
|
|
45
|
+
|
|
46
|
+
1. Find the links and forms with `turbo_method` or `data-turbo-method` (for example, sign-out).
|
|
47
|
+
2. Make sure that their actions redirect with `status: :see_other`.
|
|
48
|
+
|
|
49
|
+
Fix the controllers. Do not copy the `turbo-rails` code into `vendor/` or `app/javascript`.
|
|
50
|
+
|
|
51
|
+
Create one cable module:
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
// app/javascript/cable.js
|
|
55
|
+
import { createCable } from "@anycable/web"
|
|
56
|
+
|
|
57
|
+
export default createCable({ protocol: "actioncable-v1-ext-json" })
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Start the Turbo integration in the entry point:
|
|
61
|
+
|
|
62
|
+
```js
|
|
63
|
+
// app/javascript/application.js
|
|
64
|
+
import "@hotwired/turbo"
|
|
65
|
+
import { start } from "@anycable/turbo-stream"
|
|
66
|
+
import cable from "./cable"
|
|
67
|
+
|
|
68
|
+
start(cable, { delayedUnsubscribe: true, requestSocketIDHeader: true })
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`start` options (source: `packages/turbo-stream/start.js`):
|
|
72
|
+
|
|
73
|
+
| Option | Default | Meaning |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `delayedUnsubscribe` | `0` (`true` = 300 ms) | Keep the subscription for this time after the element leaves the page. Turbo navigation and morphing then do not cause unsubscribe/subscribe cycles. Turn it on. |
|
|
76
|
+
| `requestSocketIDHeader` | off | Add `X-Socket-ID: <cable.sessionId>` to Turbo requests. Needed for broadcasts to others (§5). A string sets a custom header name. |
|
|
77
|
+
| `presence` | `false` | Register `<turbo-cable-presence-source>` (§7). |
|
|
78
|
+
| `channelClass` | `TurboChannel` | A custom JS channel class, for example to log or filter actions. |
|
|
79
|
+
| `tagName` | `turbo-cable-stream-source` | A custom tag for stream sources. Needs a custom Rails helper. |
|
|
80
|
+
| `presenceTagName` | `turbo-cable-presence-source` | A custom tag for the presence element. |
|
|
81
|
+
|
|
82
|
+
Rules:
|
|
83
|
+
|
|
84
|
+
- Do not import `@hotwired/turbo-rails` anywhere. It registers `<turbo-cable-stream-source>` first and opens its own Action Cable connection. Search the JS, including the JS of gems and Stimulus controllers.
|
|
85
|
+
- Import the cable from one module. A second `createCable` call opens a second connection.
|
|
86
|
+
- `@anycable/turbo-stream` does not subscribe elements on Turbo cache previews. That saves subscriptions during navigation.
|
|
87
|
+
|
|
88
|
+
## 4. Streams
|
|
89
|
+
|
|
90
|
+
```erb
|
|
91
|
+
<%# Subscribe the page %>
|
|
92
|
+
<%= turbo_stream_from @chat, :messages %>
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
```ruby
|
|
96
|
+
class Message < ApplicationRecord
|
|
97
|
+
belongs_to :chat
|
|
98
|
+
|
|
99
|
+
# Render and broadcast in a job, not in the request
|
|
100
|
+
after_create_commit -> { broadcast_append_later_to chat, :messages }
|
|
101
|
+
after_update_commit -> { broadcast_replace_later_to chat, :messages }
|
|
102
|
+
after_destroy_commit -> { broadcast_remove_to chat, :messages }
|
|
103
|
+
end
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
- A signed stream name is a capability. Anyone with the name can subscribe. Render `turbo_stream_from` only for users who may read the stream.
|
|
107
|
+
- Name streams after the resource: `[chat, :messages]`. See `realtime-features.md` §7.
|
|
108
|
+
- Give every broadcast element a stable DOM id (`dom_id`). Then a message that arrives twice does no harm (§6).
|
|
109
|
+
- A broadcast partial has no `current_user`. Read `personalization.md` before you put viewer-specific HTML in it.
|
|
110
|
+
|
|
111
|
+
## 5. Broadcasting
|
|
112
|
+
|
|
113
|
+
### Batches
|
|
114
|
+
|
|
115
|
+
Broadcasts of one change must arrive in order. Send them in one batch:
|
|
116
|
+
|
|
117
|
+
```ruby
|
|
118
|
+
AnyCable.broadcast_adapter.batching do
|
|
119
|
+
card.broadcast_remove_to(old_list)
|
|
120
|
+
card.broadcast_append_to(new_list, target: "cards")
|
|
121
|
+
end
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Or batch every request and job: `batch_broadcasts: true` (`ANYCABLE_BATCH_BROADCASTS=true`).
|
|
125
|
+
|
|
126
|
+
### Broadcasts to others
|
|
127
|
+
|
|
128
|
+
Skip the browser tab that made the change. That tab already has the update from the HTTP response.
|
|
129
|
+
|
|
130
|
+
1. The client sends its socket id: `start(cable, { requestSocketIDHeader: true })`.
|
|
131
|
+
2. Rails reads the `X-Socket-ID` header for each controller action. Jobs enqueued in that action keep the socket id. Source: `lib/anycable/rails/socket_id_tracking.rb`.
|
|
132
|
+
3. Wrap the broadcast:
|
|
133
|
+
|
|
134
|
+
```ruby
|
|
135
|
+
def update
|
|
136
|
+
@card.update!(card_params)
|
|
137
|
+
|
|
138
|
+
AnyCable::Rails.broadcasting_to_others do
|
|
139
|
+
@card.broadcast_replace_to(@card.board)
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
respond_to do |format|
|
|
143
|
+
format.turbo_stream
|
|
144
|
+
format.html { redirect_to @card.board }
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Warning: `broadcasting_to_others` affects only the broadcasts in the block. A `broadcast_*_later_to` call in the block enqueues a job. The job keeps the socket id, but not the "to others" option. The job broadcasts to all clients. Source: `lib/anycable/rails.rb` (`with_broadcast_options` is thread-local) and `lib/action_cable/subscription_adapter/any_cable.rb`.
|
|
150
|
+
|
|
151
|
+
Use one of these instead:
|
|
152
|
+
|
|
153
|
+
- a synchronous `broadcast_*_to` in the block (as in the example);
|
|
154
|
+
- your own job that wraps the broadcast in `AnyCable::Rails.broadcasting_to_others`;
|
|
155
|
+
- `ActionCable.server.broadcast(stream, html, to_others: true)` with HTML that you render yourself.
|
|
156
|
+
|
|
157
|
+
### Page refreshes
|
|
158
|
+
|
|
159
|
+
`broadcasts_refreshes` and `broadcast_refresh_later_to` send a refresh signal. Each client then loads the page again with its own `current_user`. Turbo ignores a refresh that comes from the same request.
|
|
160
|
+
|
|
161
|
+
- Good for pages with few viewers and rare updates.
|
|
162
|
+
- Bad for busy pages: each broadcast causes one request from every open page.
|
|
163
|
+
|
|
164
|
+
## 6. Reliable streams
|
|
165
|
+
|
|
166
|
+
Turbo Streams lose messages during reconnects and between the page render and the subscription. AnyCable reliable streams fix that:
|
|
167
|
+
|
|
168
|
+
1. The server runs the broker: `presets = ["broker"]`.
|
|
169
|
+
2. Rails uses the `http` or `redisx` broadcast adapter.
|
|
170
|
+
3. The cable uses `protocol: "actioncable-v1-ext-json"`.
|
|
171
|
+
4. The layout requests the history since the render:
|
|
172
|
+
|
|
173
|
+
```erb
|
|
174
|
+
<meta name="action-cable-history-timestamp" content="<%= Time.now.to_i %>">
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Updates must be idempotent. `replace`, `update` and `remove` with stable DOM ids are safe. For `append` and `prepend`, Turbo replaces an existing element with the same id.
|
|
178
|
+
|
|
179
|
+
Details: `realtime-features.md` §6.
|
|
180
|
+
|
|
181
|
+
## 7. Presence element
|
|
182
|
+
|
|
183
|
+
`<turbo-cable-presence-source>` shows who is on the page with no custom JS. Requirements:
|
|
184
|
+
|
|
185
|
+
- `@anycable/turbo-stream` 0.8.0 or later, and `start(cable, { presence: true })`;
|
|
186
|
+
- the broker on the server (`presets = ["broker"]`);
|
|
187
|
+
- the extended protocol (`actioncable-v1-ext-json`).
|
|
188
|
+
|
|
189
|
+
It works without RPC. Read `presence.md` for presence in general.
|
|
190
|
+
|
|
191
|
+
```erb
|
|
192
|
+
<turbo-cable-presence-source
|
|
193
|
+
signed-stream-name="<%= Turbo::StreamsChannel.signed_stream_name([@document, :presence]) %>"
|
|
194
|
+
presence-id="<%= dom_id(current_user, :presence) %>"
|
|
195
|
+
ignore-self>
|
|
196
|
+
<p>Viewers: <span data-presence-counter>0</span></p>
|
|
197
|
+
<div id="viewers"></div>
|
|
198
|
+
|
|
199
|
+
<template>
|
|
200
|
+
<%= turbo_stream.append "viewers" do %>
|
|
201
|
+
<div id="<%= dom_id(current_user, :presence) %>"><%= current_user.name %></div>
|
|
202
|
+
<% end %>
|
|
203
|
+
</template>
|
|
204
|
+
</turbo-cable-presence-source>
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
How it works (source: `packages/turbo-stream/presence_source_element.js`):
|
|
208
|
+
|
|
209
|
+
1. On connect, the element joins presence with `presence-id`. The presence info is the HTML of the `<template>`.
|
|
210
|
+
2. It reads the current presence set and runs the join HTML of every present user.
|
|
211
|
+
3. On `join`, it runs the new user's HTML as a Turbo Stream action.
|
|
212
|
+
4. On `leave`, it removes the element whose `id` equals the presence id. Use the same value for `presence-id` and for the DOM id in the template.
|
|
213
|
+
|
|
214
|
+
| Attribute | Set by | Meaning |
|
|
215
|
+
|---|---|---|
|
|
216
|
+
| `signed-stream-name` | you | The stream. Sign it with `Turbo::StreamsChannel.signed_stream_name`. |
|
|
217
|
+
| `presence-id` | you | Required. One id per user. Several tabs with the same id count as one user. |
|
|
218
|
+
| `ignore-self` | you | Do not show the current user and do not count them. |
|
|
219
|
+
| `connected` | element | The subscription is active. |
|
|
220
|
+
| `present` | element | At least one user is present. Use it in CSS, for example `[present] .empty { display: none }`. |
|
|
221
|
+
|
|
222
|
+
- `[data-presence-counter]` inside the element shows the number of users.
|
|
223
|
+
- Each user renders their own template. No personalized broadcast is needed.
|
|
224
|
+
|
|
225
|
+
Warning: the template HTML comes from the client. Any holder of the signed stream name can send any HTML to the other viewers. Render the element only for trusted, signed-in users. Keep a strict Content Security Policy.
|
|
226
|
+
|
|
227
|
+
Article: <https://evilmartians.com/chronicles/simple-declarative-presence-for-hotwire-apps-with-anycable>. Example: <https://github.com/anycable/anycasts_demo/pull/17>.
|
|
228
|
+
|
|
229
|
+
## 8. Custom channel classes and tags
|
|
230
|
+
|
|
231
|
+
A custom JS channel class can intercept Turbo Stream actions:
|
|
232
|
+
|
|
233
|
+
```js
|
|
234
|
+
import { start, TurboChannel } from "@anycable/turbo-stream"
|
|
235
|
+
import cable from "./cable"
|
|
236
|
+
|
|
237
|
+
class LogChannel extends TurboChannel {
|
|
238
|
+
receive(message) {
|
|
239
|
+
console.debug("turbo action", message)
|
|
240
|
+
super.receive(message)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
start(cable, { channelClass: LogChannel, delayedUnsubscribe: true })
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
A custom tag (`tagName`) needs a Rails helper that renders it. See the package README.
|
|
248
|
+
|
|
249
|
+
## 9. Turbo Streams over SSE
|
|
250
|
+
|
|
251
|
+
Pages that only receive updates can use Server-Sent Events. No JS client is needed:
|
|
252
|
+
|
|
253
|
+
```erb
|
|
254
|
+
<turbo-stream-source src="<%= "https://ws.example.com/events?turbo_signed_stream_name=#{Turbo::StreamsChannel.signed_stream_name(@chat)}" %>"></turbo-stream-source>
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
SSE reconnects with `Last-Event-ID`. Turn on reliable streams to get the missed messages. Docs: <https://docs.anycable.io/anycable-go/sse>.
|
|
258
|
+
|
|
259
|
+
## 10. Checks
|
|
260
|
+
|
|
261
|
+
- DevTools → Network → WS: one connection to the AnyCable host.
|
|
262
|
+
- `turbo-cable-stream-source[connected]` is on the page after the subscription. Use it in system tests (`testing.md`).
|
|
263
|
+
- A broadcast from the console arrives:
|
|
264
|
+
|
|
265
|
+
```sh
|
|
266
|
+
bin/rails runner 'Turbo::StreamsChannel.broadcast_append_to(Chat.first, :messages, target: "messages", html: "<p>ping</p>"); AnyCable.broadcast_adapter.shutdown'
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
- A scripted check of one signed stream: `live-checks.md`.
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
# Installing and configuring AnyCable
|
|
2
|
+
|
|
3
|
+
Summary: add the gem, run `bin/rails g anycable:setup` with explicit flags, then tune the output.
|
|
4
|
+
Prefer the RPC-less setup (JWT + signed streams) when the app has no custom channels.
|
|
5
|
+
|
|
6
|
+
Docs: <https://docs.anycable.io/rails/getting_started>, <https://docs.anycable.io/getting_started>.
|
|
7
|
+
|
|
8
|
+
## 1. Choose the RPC mode first
|
|
9
|
+
|
|
10
|
+
RPC is how the AnyCable server calls Rails to run `Connection#connect` and channel code.
|
|
11
|
+
|
|
12
|
+
| Mode | Use it when | Gem | Server setting |
|
|
13
|
+
|---|---|---|---|
|
|
14
|
+
| `none` (standalone) | The app uses only Turbo Streams or `$pubsub` signed streams, and no custom channels | `anycable-rails-core` | `[rpc] implementation = "none"` or `--norpc` |
|
|
15
|
+
| `http` | Custom channels, plus a platform with one web service only (Heroku, Render, Cloud Run), or AnyCable+ | `anycable-rails-core` | `ANYCABLE_RPC_HOST=https://app.example.com/_anycable` |
|
|
16
|
+
| `grpc` | Custom channels, high load, a separate RPC process is possible | `anycable-rails` | `ANYCABLE_RPC_HOST=rpc-host:50051` |
|
|
17
|
+
|
|
18
|
+
Decision rules:
|
|
19
|
+
|
|
20
|
+
1. No files in `app/channels/*_channel.rb` except `application_cable/` → `none`.
|
|
21
|
+
2. Custom channels exist → ask the user if they can be replaced with signed streams and whispers (see `realtime-features.md` §1). If yes → `none`.
|
|
22
|
+
3. Channels must stay and the platform runs only one service → `http`.
|
|
23
|
+
4. Otherwise → `grpc`.
|
|
24
|
+
|
|
25
|
+
The `none` mode needs JWT authentication. With JWT, `Connection#connect` does not run. Move side effects from `connect` (for example, activity tracking) to a controller or a job before you switch.
|
|
26
|
+
|
|
27
|
+
Docs: <https://docs.anycable.io/anycable-go/rpc>, <https://docs.anycable.io/ruby/http_rpc>, <https://docs.anycable.io/guides/hotwire>.
|
|
28
|
+
|
|
29
|
+
## 2. Run the generator
|
|
30
|
+
|
|
31
|
+
1. Add the gem:
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
bundle add anycable-rails-core # for none or http RPC
|
|
35
|
+
# or
|
|
36
|
+
bundle add anycable-rails # for gRPC (adds the gRPC server)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
2. Ask the user how to run the AnyCable server in development. Recommend the option from §8. Do not select it yourself.
|
|
40
|
+
3. Run the generator with explicit flags. Without flags, it asks questions in the terminal.
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
bin/rails g anycable:setup --rpc=none --development=puma --version=1.6
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
| Flag | Values | Meaning |
|
|
47
|
+
|---|---|---|
|
|
48
|
+
| `--rpc` | `none`, `http`, `grpc` | RPC mode. Without it, the generator detects Hotwire-only apps as `none` and asks otherwise. |
|
|
49
|
+
| `--development` | `bin`, `puma`, `docker`, `skip` | How to run the server locally (§8). Without it, the generator uses `bin` if `bin/dev` and `Procfile.dev` exist, and asks otherwise. |
|
|
50
|
+
| `--version` | for example `1.6` | The `anycable-go` version for `bin/anycable-go`. Default is `latest`. Pin a minor version: the generator writes the latest patch release (for example, `1.6.22`) into `bin/anycable-go`. |
|
|
51
|
+
| `--skip-procfile` | | Do not create `Procfile.dev`. |
|
|
52
|
+
|
|
53
|
+
4. Read the generator output. It ends with a TODO list. Do every item.
|
|
54
|
+
|
|
55
|
+
## 3. What the generator changes
|
|
56
|
+
|
|
57
|
+
| File | Change | Check after |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| `config/anycable.yml` | Rails-side config. `broadcast_adapter: http`, a development `secret`, `websocket_url: ws://localhost:8080/cable`. Production values are `~`. | Production gets `ANYCABLE_SECRET` and `ANYCABLE_WEBSOCKET_URL` from env or credentials. |
|
|
60
|
+
| `anycable.toml` | Server config: secret, `presets = ["broker"]`, broadcast adapters, `[rpc]`, `[streams] turbo = true`, `whisper = true`. | Only keep development values here. |
|
|
61
|
+
| `config/cable.yml` | All adapters except `test` become `any_cable`. | `test` stays `test` unless you run system tests against AnyCable (`testing.md`). |
|
|
62
|
+
| Layout `application.html.erb` | Adds `action_cable_meta_tag` (RPC) or `action_cable_with_jwt_meta_tag` (no RPC) after `csp_meta_tag`. | Pass the identifiers to the JWT tag (§4). |
|
|
63
|
+
| `config/application.rb` | Adds `config.turbo.signed_stream_verifier_key = AnyCable.config.secret` (Hotwire apps). Adds `require "action_cable/engine"` if missing. | Keep it. Turbo and AnyCable must sign streams with the same key. |
|
|
64
|
+
| JS entry point | Replaces `@hotwired/turbo-rails` with `@hotwired/turbo` + `@anycable/web` + `@anycable/turbo-stream`. Installs the packages. | Check that the packages are in `package.json` or `config/importmap.rb`. |
|
|
65
|
+
| `config/importmap.rb` | Pins `@hotwired/turbo`, `@anycable/web`, `@anycable/turbo-stream`. Removes the `@hotwired/turbo-rails` pin. | Links with `data-turbo-method` need `status: :see_other` redirects (`hotwire.md` §3). |
|
|
66
|
+
| `bin/anycable-go` | Local server binary (downloaded to `bin/dist/`). | Commit the script. `bin/dist/` goes to `.gitignore`. |
|
|
67
|
+
| `Procfile.dev`, `bin/dev` (`--development=bin`) | A `ws:` process, and `anycable:` (gRPC only). A `bin/dev` that only runs `rails server` becomes a foreman/overmind script. | `bin/dev` starts all processes. |
|
|
68
|
+
| `config/puma.rb` (`--development=puma`) | `plugin :anycable if ENV["ANYCABLE_IN_PUMA"]`, before `plugin :solid_queue`. | §8. |
|
|
69
|
+
| Nothing (`--development=docker`) | Prints a Docker Compose snippet only. | Add the services to the Compose file yourself (§8). |
|
|
70
|
+
|
|
71
|
+
The generator also runs RuboCop compatibility checks if RuboCop is in the bundle. Fix every `AnyCable/*` offense (see <https://docs.anycable.io/rails/compatibility>).
|
|
72
|
+
|
|
73
|
+
## 4. Authentication
|
|
74
|
+
|
|
75
|
+
Use JWT. Use cookies only when RPC is on and the WebSocket host shares the cookie domain.
|
|
76
|
+
|
|
77
|
+
**JWT in the layout.** The keyword names must match `identified_by` in `ApplicationCable::Connection`:
|
|
78
|
+
|
|
79
|
+
```erb
|
|
80
|
+
<%= action_cable_with_jwt_meta_tag(user: current_user) if current_user %>
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
- The helper puts the token into the URL (`?jid=<token>`). `@anycable/web` reads the URL from the `action-cable-url` meta tag.
|
|
84
|
+
- `anycable_token_meta_tag(user: current_user)` is the alternative: it renders `<meta name="cable-token">` and keeps the URL clean.
|
|
85
|
+
- The token lives 1 hour by default (`jwt_ttl`). Add a token refresher on the client (`realtime-features.md` §2).
|
|
86
|
+
- Guests: in `none` mode, a client without a token cannot connect (`Auth Failed`). If guests need live updates, render the tag without the `if` and with no identifiers for guests. Signed streams then do the access control.
|
|
87
|
+
|
|
88
|
+
**JWT with the Action Cable server too** (for example, in tests or during a migration):
|
|
89
|
+
|
|
90
|
+
```ruby
|
|
91
|
+
module ApplicationCable
|
|
92
|
+
class Connection < ActionCable::Connection::Base
|
|
93
|
+
prepend AnyCable::Rails::Ext::JWT
|
|
94
|
+
|
|
95
|
+
identified_by :user
|
|
96
|
+
|
|
97
|
+
def connect
|
|
98
|
+
return identify_from_anycable_jwt! if anycable_jwt_present?
|
|
99
|
+
|
|
100
|
+
self.user = find_verified_user
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
**Cookies (RPC only).** AnyCable runs `connect` through RPC with the request cookies. Devise/Warden works automatically. If the WebSocket server is on a subdomain, share the session cookie:
|
|
107
|
+
|
|
108
|
+
```ruby
|
|
109
|
+
# config/initializers/session_store.rb
|
|
110
|
+
Rails.application.config.session_store :cookie_store, key: "_app_session", domain: :all
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Shared cookies do not work across `*.herokuapp.com` or `*.fly.dev` subdomains. Use JWT there.
|
|
114
|
+
|
|
115
|
+
Docs: <https://docs.anycable.io/rails/authentication>, <https://docs.anycable.io/anycable-go/jwt_identification>.
|
|
116
|
+
|
|
117
|
+
## 5. Client setup
|
|
118
|
+
|
|
119
|
+
Create one cable for the whole page:
|
|
120
|
+
|
|
121
|
+
```js
|
|
122
|
+
// app/javascript/cable.js
|
|
123
|
+
import { createCable } from "@anycable/web"
|
|
124
|
+
|
|
125
|
+
// The extended protocol enables session recovery, reliable streams and presence
|
|
126
|
+
export default createCable({ protocol: "actioncable-v1-ext-json" })
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Hotwire apps:
|
|
130
|
+
|
|
131
|
+
```js
|
|
132
|
+
import "@hotwired/turbo"
|
|
133
|
+
import { start } from "@anycable/turbo-stream"
|
|
134
|
+
import cable from "./cable"
|
|
135
|
+
|
|
136
|
+
// Avoid resubscriptions during Turbo navigation and morphing
|
|
137
|
+
start(cable, { delayedUnsubscribe: true })
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Apps with channels and `@rails/actioncable` code: replace `createConsumer` from `@rails/actioncable` with the one from `@anycable/web`. The subscription code stays the same:
|
|
141
|
+
|
|
142
|
+
```js
|
|
143
|
+
import { createConsumer } from "@anycable/web"
|
|
144
|
+
|
|
145
|
+
export default createConsumer()
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The client reads the URL from `<meta name="action-cable-url">`. Put the meta tag in `<head>` before the JS.
|
|
149
|
+
|
|
150
|
+
With a Content Security Policy, add the WebSocket origin to `connect_src`.
|
|
151
|
+
|
|
152
|
+
Docs: <https://docs.anycable.io/guides/client-side>, <https://github.com/anycable/anycable-client>.
|
|
153
|
+
|
|
154
|
+
## 6. Broadcast adapter and broker
|
|
155
|
+
|
|
156
|
+
The broadcast adapter carries messages from Rails to the AnyCable server.
|
|
157
|
+
|
|
158
|
+
| Adapter | Use it when | Notes |
|
|
159
|
+
|---|---|---|
|
|
160
|
+
| `http` (default from the generator) | Most apps. No extra infrastructure. | Works with reliable streams. With a secret set, the server accepts broadcasts on its main port at `/_broadcast` with a bearer token. |
|
|
161
|
+
| `redisx` | The app already runs Redis and you want to decouple Rails from the server address | Needs the `redis` gem and Redis 6.2+. Works with reliable streams. |
|
|
162
|
+
| `nats` | Multi-node servers with embedded NATS | Needs `nats-pure`. |
|
|
163
|
+
| `redis` (legacy) | Avoid. | Does not work with reliable streams. |
|
|
164
|
+
|
|
165
|
+
The broker keeps stream history and sessions. It enables reliable streams and presence.
|
|
166
|
+
|
|
167
|
+
- One server node: `presets = ["broker"]` (the generator default) uses an in-memory broker.
|
|
168
|
+
- Several server nodes: add `--pubsub=redis` or `--pubsub=nats`. A shared broker for history (Redis) is an AnyCable Pro feature.
|
|
169
|
+
|
|
170
|
+
Docs: <https://docs.anycable.io/anycable-go/broadcasting>, <https://docs.anycable.io/anycable-go/reliable_streams>, <https://docs.anycable.io/anycable-go/broker>.
|
|
171
|
+
|
|
172
|
+
## 7. Rails-side settings
|
|
173
|
+
|
|
174
|
+
Set these in `config/anycable.yml`, Rails credentials (`anycable:` key), or `ANYCABLE_*` env vars.
|
|
175
|
+
|
|
176
|
+
| Setting | Env var | Meaning |
|
|
177
|
+
|---|---|---|
|
|
178
|
+
| `secret` | `ANYCABLE_SECRET` | Shared secret for JWT, signed streams, broadcasts and HTTP RPC. Must match the server. |
|
|
179
|
+
| `websocket_url` | `ANYCABLE_WEBSOCKET_URL` | Public WebSocket URL. Sets `config.action_cable.url`. |
|
|
180
|
+
| `broadcast_adapter` | `ANYCABLE_BROADCAST_ADAPTER` | `http`, `redisx`, `nats`, `redis`. |
|
|
181
|
+
| `http_broadcast_url` | `ANYCABLE_HTTP_BROADCAST_URL` | Where to send HTTP broadcasts. Default: `http://localhost:8080/_broadcast` with a secret, port 8090 without. Set it when the server is on another host or port. |
|
|
182
|
+
| `http_rpc_mount_path` | `ANYCABLE_HTTP_RPC_MOUNT_PATH` | HTTP RPC endpoint, usually `/_anycable`. |
|
|
183
|
+
| `jwt_ttl` | `ANYCABLE_JWT_TTL` | Token lifetime in seconds. Default `3600`. |
|
|
184
|
+
| `batch_broadcasts` | `ANYCABLE_BATCH_BROADCASTS` | Send all broadcasts of one request or job in one batch. |
|
|
185
|
+
| `socket_id_header` | `ANYCABLE_SOCKET_ID_HEADER` | Header for broadcasts to others. Default `X-Socket-ID`. |
|
|
186
|
+
| `access_logs_disabled` | `ANYCABLE_ACCESS_LOGS_DISABLED` | Hide `Started`/`Finished` lines for RPC calls. |
|
|
187
|
+
|
|
188
|
+
Source: `lib/anycable/rails/config.rb`. Full list: <https://docs.anycable.io/ruby/configuration>.
|
|
189
|
+
|
|
190
|
+
## 8. Local development
|
|
191
|
+
|
|
192
|
+
Ask the user how to run the AnyCable server in development. Recommend the option from this table:
|
|
193
|
+
|
|
194
|
+
| The app has | Recommend | Generator flag |
|
|
195
|
+
|---|---|---|
|
|
196
|
+
| `Procfile.dev` (and `bin/dev` with foreman or overmind) | A `ws` process in `Procfile.dev` | `--development=bin` |
|
|
197
|
+
| No `Procfile.dev` (`bin/dev` runs `rails server`) | The Puma plugin. Do not add a `Procfile.dev` only for AnyCable. | `--development=puma` |
|
|
198
|
+
| Development in Docker Compose | A `ws` service with the `anycable/anycable-go` image | `--development=docker` |
|
|
199
|
+
| gRPC RPC | `Procfile.dev`. The Puma plugin does not run the gRPC server. | `--development=bin` |
|
|
200
|
+
|
|
201
|
+
Rules:
|
|
202
|
+
|
|
203
|
+
- Do not suggest AnyCable Thruster for development. If the app already uses it in development, keep it. Reasons: Puma runs as a child process of `thrust`, so the debugger (`debugger`, `binding.irb`) is difficult to use, and Thruster is a production proxy. System tests with `capybara-thruster` are a different case (`testing.md`).
|
|
204
|
+
- Run the local server with `bin/anycable-go` (from `bin/rails g anycable:bin`). Do not use `brew` or `npx`.
|
|
205
|
+
- A local setup and a Docker setup can be different. Do not change one to match the other.
|
|
206
|
+
|
|
207
|
+
`bin/anycable-go` downloads the server binary into `bin/dist/`. To change the version, run `bin/rails g anycable:bin --version=1.6` again.
|
|
208
|
+
|
|
209
|
+
### Procfile.dev
|
|
210
|
+
|
|
211
|
+
`bin/dev` runs `Procfile.dev`: `web` (Rails), `ws` (`bin/anycable-go --port 8080`), and `anycable` (gRPC only).
|
|
212
|
+
|
|
213
|
+
### Puma plugin
|
|
214
|
+
|
|
215
|
+
The plugin comes with the gem. It runs `bin/anycable-go` together with `bin/rails server`. Source: `lib/puma/plugin/anycable.rb`.
|
|
216
|
+
|
|
217
|
+
```ruby
|
|
218
|
+
# config/puma.rb
|
|
219
|
+
plugin :anycable if ENV["ANYCABLE_IN_PUMA"]
|
|
220
|
+
|
|
221
|
+
# Optional settings, after the plugin line
|
|
222
|
+
anycable_log "log/anycable.log"
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
| Setting | Default | Meaning |
|
|
226
|
+
|---|---|---|
|
|
227
|
+
| `anycable_command` | `"bin/anycable-go"` | The command that starts the server. |
|
|
228
|
+
| `anycable_log` | Puma output | A file for the server output. |
|
|
229
|
+
| `anycable_pidfile` | `"tmp/pids/anycable.pid"` | Keeps the server PID between Puma restarts. |
|
|
230
|
+
|
|
231
|
+
The plugin runs only when `ANYCABLE_IN_PUMA` is set. Suggest to the user to set it in `bin/dev`, so that production and tests do not start the server:
|
|
232
|
+
|
|
233
|
+
```ruby
|
|
234
|
+
#!/usr/bin/env ruby
|
|
235
|
+
ENV["ANYCABLE_IN_PUMA"] ||= "1"
|
|
236
|
+
|
|
237
|
+
exec "./bin/rails", "server", *ARGV
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
- The server starts after Puma boots and stops when Puma stops.
|
|
241
|
+
- The server stays alive when Puma restarts (`tmp_restart`, `bin/rails restart`).
|
|
242
|
+
- If Puma was killed, the next start stops the old server.
|
|
243
|
+
- Keep `plugin :anycable` before `plugin :solid_queue`. Puma runs the stop hooks in the order of the plugins. If one hook fails, the next hooks do not run.
|
|
244
|
+
|
|
245
|
+
### Docker Compose
|
|
246
|
+
|
|
247
|
+
`--development=docker` does not change the Compose file. It only prints a snippet. Add the services and the env vars yourself:
|
|
248
|
+
|
|
249
|
+
```yaml
|
|
250
|
+
services:
|
|
251
|
+
rails:
|
|
252
|
+
# ...
|
|
253
|
+
environment:
|
|
254
|
+
ANYCABLE_HTTP_BROADCAST_URL: http://ws:8080/_broadcast
|
|
255
|
+
depends_on:
|
|
256
|
+
- ws
|
|
257
|
+
|
|
258
|
+
ws:
|
|
259
|
+
image: anycable/anycable-go:1.6
|
|
260
|
+
ports:
|
|
261
|
+
- "8080:8080"
|
|
262
|
+
volumes:
|
|
263
|
+
- ./anycable.toml:/etc/anycable/anycable.toml:ro
|
|
264
|
+
environment:
|
|
265
|
+
ANYCABLE_HOST: "0.0.0.0"
|
|
266
|
+
# HTTP RPC only:
|
|
267
|
+
# ANYCABLE_RPC_HOST: http://rails:3000/_anycable
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
- The server reads `/etc/anycable/anycable.toml`. Override with env vars only the values that are different in Docker.
|
|
271
|
+
- With a secret, the server accepts broadcasts on its main port (8080).
|
|
272
|
+
- Keep `websocket_url: ws://localhost:8080/cable`. The browser connects from the host.
|
|
273
|
+
|
|
274
|
+
### Switch back to Action Cable
|
|
275
|
+
|
|
276
|
+
To switch back to Action Cable quickly, make the adapter configurable:
|
|
277
|
+
|
|
278
|
+
```yaml
|
|
279
|
+
# config/cable.yml
|
|
280
|
+
development:
|
|
281
|
+
adapter: <%= ENV.fetch("ACTION_CABLE_ADAPTER", "any_cable") %>
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
## 9. Verify the setup
|
|
285
|
+
|
|
286
|
+
1. Start the app (`bin/dev`, or `bin/rails s` with the Puma plugin). Check the server log (the `ws` process, or the Puma output) for these lines:
|
|
287
|
+
- `Starting AnyCable <version>`;
|
|
288
|
+
- `RPC controller initialized: <host>` (RPC modes) or `no RPC configured` (`none` mode);
|
|
289
|
+
- `Using in-memory broker` (broker preset);
|
|
290
|
+
- `Handle WebSocket connections at http://localhost:8080/cable`.
|
|
291
|
+
2. Open a page in the browser. In DevTools → Network → WS, check that the request goes to port 8080 (not 3000) and gets status 101.
|
|
292
|
+
3. Trigger a broadcast and see it arrive. Or run a scripted check: `live-checks.md`.
|