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.
Files changed (29) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +17 -0
  3. data/MIT-LICENSE +1 -1
  4. data/README.md +12 -0
  5. data/lib/anycable/rails/channel/presence.rb +1 -1
  6. data/lib/anycable/rails/version.rb +1 -1
  7. data/lib/generators/anycable/bin/USAGE +3 -1
  8. data/lib/generators/anycable/bin/bin_generator.rb +7 -6
  9. data/lib/generators/anycable/bin/templates/bin/anycable-go.tt +4 -3
  10. data/lib/generators/anycable/download/download_generator.rb +2 -11
  11. data/lib/generators/anycable/setup/USAGE +8 -0
  12. data/lib/generators/anycable/setup/setup_generator.rb +104 -68
  13. data/lib/generators/anycable/setup/templates/Procfile.dev.tt +1 -1
  14. data/lib/generators/anycable/with_release_helpers.rb +69 -0
  15. data/lib/puma/plugin/anycable.rb +171 -0
  16. data/skills/anycable-rails/SKILL.md +82 -0
  17. data/skills/anycable-rails/references/deployment.md +187 -0
  18. data/skills/anycable-rails/references/hotwire.md +269 -0
  19. data/skills/anycable-rails/references/installation.md +292 -0
  20. data/skills/anycable-rails/references/live-checks.md +129 -0
  21. data/skills/anycable-rails/references/personalization.md +114 -0
  22. data/skills/anycable-rails/references/presence.md +240 -0
  23. data/skills/anycable-rails/references/realtime-features.md +231 -0
  24. data/skills/anycable-rails/references/testing.md +145 -0
  25. data/skills/anycable-rails/references/troubleshooting.md +128 -0
  26. data/skills/anycable-rails/scenarios/channel.yml +51 -0
  27. data/skills/anycable-rails/scenarios/signed-stream.yml +38 -0
  28. metadata +18 -3
  29. data/lib/generators/anycable/setup/templates/bin/anycable-go.tt +0 -27
@@ -0,0 +1,231 @@
1
+ # Building real-time features with AnyCable
2
+
3
+ Summary: start with signed streams and server-side broadcasts. Add a channel only when the client must call the server.
4
+ Use whispers for ephemeral client events and presence for "who is online".
5
+ Use reliable streams so that clients do not miss messages.
6
+
7
+ ## 1. Signed streams or channels
8
+
9
+ | Need | Use |
10
+ |---|---|
11
+ | Server pushes updates to the page (Turbo Streams, JSON) | Signed stream: `turbo_stream_from` or `$pubsub` |
12
+ | Clients send ephemeral events to each other (typing, cursors) | Signed stream + whispers (§3) |
13
+ | Who is online | Signed stream + presence (§4) |
14
+ | The client calls server code over the socket (`perform`) | Channel |
15
+ | Per-subscription server logic: authorization that a signature cannot express, presence controlled by the server, custom stream selection | Channel |
16
+
17
+ Signed streams need no RPC. The server verifies the signature itself. A signed stream name is a capability: anyone with the name can subscribe until the secret changes. Render it only for users who may read the stream.
18
+
19
+ Docs: <https://docs.anycable.io/anycable-go/signed_streams>.
20
+
21
+ ### Turbo Streams
22
+
23
+ No AnyCable-specific Ruby code is needed. Read `hotwire.md` for the JS setup, broadcasts to others and the presence element:
24
+
25
+ ```erb
26
+ <%= turbo_stream_from @chat, :messages %>
27
+ ```
28
+
29
+ ```ruby
30
+ class Message < ApplicationRecord
31
+ belongs_to :chat
32
+
33
+ after_create_commit -> { broadcast_append_later_to chat, :messages }
34
+ end
35
+ ```
36
+
37
+ Requirements: `config.turbo.signed_stream_verifier_key = AnyCable.config.secret` and turbo streams on the server (`[streams] turbo = true`).
38
+
39
+ ### `$pubsub` streams (JSON, non-Turbo clients)
40
+
41
+ ```ruby
42
+ # Render the signed name for the client
43
+ signed_stream_name([chat, :typing]) # view helper
44
+ AnyCable::Rails.signed_stream_name([chat, :typing]) # anywhere
45
+
46
+ # Broadcast to the same stream (anycable-rails turns arrays into stream names)
47
+ ActionCable.server.broadcast([chat, :typing], {event: "typing", user_id: user.id})
48
+ ```
49
+
50
+ ```js
51
+ import cable from "./cable"
52
+
53
+ const channel = cable.streamFromSigned(signedName)
54
+ channel.on("message", (msg) => { /* ... */ })
55
+ ```
56
+
57
+ ### Channels
58
+
59
+ Channels work as in Action Cable, with these AnyCable rules:
60
+
61
+ - A new channel object handles each command. Instance variables set in `subscribed` are gone in the next action. Use `state_attr_accessor`:
62
+
63
+ ```ruby
64
+ class ChatChannel < ApplicationCable::Channel
65
+ state_attr_accessor :room
66
+
67
+ def subscribed
68
+ self.room = Room.find(params[:id])
69
+ stream_for room
70
+ end
71
+
72
+ def speak(data)
73
+ room.messages.create!(body: data["body"], user: current_user)
74
+ end
75
+ end
76
+ ```
77
+
78
+ - No `periodically` timers. No `stream_from` with a block or a custom coder.
79
+ - Every command is an RPC call. Keep actions fast. Move slow work to jobs.
80
+
81
+ Docs: <https://docs.anycable.io/rails/channels_state>, <https://docs.anycable.io/rails/compatibility>.
82
+
83
+ ## 2. Authentication
84
+
85
+ **JWT (recommended).** The token carries the connection identifiers. The server verifies it without RPC.
86
+
87
+ ```erb
88
+ <%# app/views/layouts/application.html.erb %>
89
+ <%= action_cable_with_jwt_meta_tag(user: current_user) %>
90
+ ```
91
+
92
+ - Keywords must match `identified_by`.
93
+ - AnyCable does not call `Connection#connect` with JWT.
94
+ - Tokens expire (`jwt_ttl`, 1 hour by default). The server then disconnects the client with `token_expired`. Add a refresher, so that long-lived pages reconnect:
95
+
96
+ ```js
97
+ import { createCable, fetchTokenFromHTML } from "@anycable/web"
98
+
99
+ // Loads the current page in the background and reads the new meta tag
100
+ export default createCable({
101
+ protocol: "actioncable-v1-ext-json",
102
+ tokenRefresher: fetchTokenFromHTML()
103
+ })
104
+ ```
105
+
106
+ `fetchTokenFromHTML` sends the `X-ANYCABLE-OPERATION: token-refresh` header. Return a minimal page with the meta tag for that header to save server time.
107
+ - Manual tokens (mobile clients, an API): `AnyCable::JWT.encode({user: user}, expires_at: 10.minutes.from_now)`.
108
+ - Keep the token out of URLs and logs: `createCable({websocketAuthStrategy: "sub-protocol"})` with `anycable_token_meta_tag`. Needs AnyCable server 1.6+.
109
+
110
+ **Cookies (RPC).** The server forwards the cookies to Rails. `connect` runs as in Action Cable. Every connection costs an RPC call. The WebSocket host must share the cookie domain.
111
+
112
+ Docs: <https://docs.anycable.io/rails/authentication>, <https://github.com/anycable/anycable-client#token-based-authentication>.
113
+
114
+ ## 3. Whispers
115
+
116
+ A whisper is a client-to-client message. It goes through the AnyCable server to the other subscribers of the stream. Rails does not see it.
117
+
118
+ Use whispers for state that may be lost: typing indicators, cursor positions, "user is viewing". Do not use them for data that must be saved or trusted. Any subscriber can whisper any payload.
119
+
120
+ Signed streams: turn on whispers on the server (`[streams] whisper = true` or `ANYCABLE_STREAMS_WHISPER=true`).
121
+
122
+ ```js
123
+ const channel = cable.streamFromSigned(signedName)
124
+
125
+ channel.whisper({ event: "typing", name: currentUserName })
126
+
127
+ channel.on("message", (msg) => {
128
+ if (msg.event === "typing") showTyping(msg.name)
129
+ })
130
+ ```
131
+
132
+ Channels: declare the whisper stream. Only one whisper stream per subscription:
133
+
134
+ ```ruby
135
+ class ChatChannel < ApplicationCable::Channel
136
+ def subscribed
137
+ stream_for room, whisper: true
138
+ end
139
+ end
140
+ ```
141
+
142
+ - The sender does not get its own whisper (AnyCable server). The Action Cable server sends it back to the sender too.
143
+ - Throttle frequent events (for example, cursor moves to 10–20 per second).
144
+
145
+ Docs: <https://docs.anycable.io/rails/extensions#whispering>.
146
+
147
+ ## 4. Presence
148
+
149
+ Presence keeps the set of users that are online on a stream. It needs the broker and the extended protocol.
150
+
151
+ - Signed streams: the client joins with `channel.presence.join(id, info)`.
152
+ - Channels: the server joins with `join_presence`.
153
+ - Hotwire: the `<turbo-cable-presence-source>` element.
154
+ - Rails code reads the set with the REST API.
155
+
156
+ Read `presence.md` before you build a presence feature.
157
+
158
+ ## 5. Broadcasting
159
+
160
+ **Broadcast from jobs, not from the request.** Use `broadcast_*_later_to` or a job when the broadcast renders a partial. The request stays fast.
161
+
162
+ **Batch broadcasts.** Messages in one batch go in one request and keep their order.
163
+
164
+ ```ruby
165
+ AnyCable.broadcast_adapter.batching do
166
+ Turbo::StreamsChannel.broadcast_remove_to(list, target: card)
167
+ Turbo::StreamsChannel.broadcast_append_to(other_list, target: "cards", partial: "cards/card", locals: {card: card})
168
+ end
169
+ ```
170
+
171
+ Or batch every request and job automatically: `batch_broadcasts: true` (`ANYCABLE_BATCH_BROADCASTS=true`).
172
+
173
+ **Broadcast to others.** Skip the client that made the change (it already has the update from the HTTP response):
174
+
175
+ 1. The client sends its socket id with requests. Turbo: `start(cable, { requestSocketIDHeader: true })`. Other `fetch` calls: add `X-Socket-ID: cable.sessionId`. Turbo details and the `_later_` caveat: `hotwire.md` §5.
176
+ 2. Rails stores the header for the request. Active Job carries it into jobs.
177
+ 3. Broadcast with the option:
178
+
179
+ ```ruby
180
+ ActionCable.server.broadcast(stream, payload, to_others: true)
181
+ ChatChannel.broadcast_to(room, payload, to_others: true)
182
+
183
+ AnyCable::Rails.broadcasting_to_others do
184
+ Turbo::StreamsChannel.broadcast_replace_to(card.board, target: card, partial: "cards/card", locals: {card: card})
185
+ end
186
+ ```
187
+
188
+ Docs: <https://docs.anycable.io/rails/extensions#broadcast-api>, <https://docs.anycable.io/ruby/broadcast_adapters>.
189
+
190
+ **Turbo page refreshes.** `broadcasts_refreshes` and `broadcast_refresh_later_to` send a "reload" signal. Each client then requests the page again. That is simple and handles personalization, but each broadcast causes one request per open page. Use it for low-traffic pages. Debounce bulk updates.
191
+
192
+ ## 6. Reliable streams and the page-load gap
193
+
194
+ Action Cable delivers each message at most once. Messages are lost:
195
+
196
+ - during a reconnect;
197
+ - between the page render and the subscription ("late to the party").
198
+
199
+ AnyCable reliable streams fix both:
200
+
201
+ 1. Server: the broker (`presets = ["broker"]`). Several server nodes need a shared broker (AnyCable Pro) and `pubsub`.
202
+ 2. Rails: the `http` or `redisx` broadcast adapter. The legacy `redis` adapter does not work.
203
+ 3. Client: `createCable({ protocol: "actioncable-v1-ext-json" })`.
204
+ 4. Layout: ask for the history since the page render:
205
+
206
+ ```erb
207
+ <meta name="action-cable-history-timestamp" content="<%= Time.now.to_i %>">
208
+ ```
209
+
210
+ Then:
211
+
212
+ - Updates must be idempotent. A message can arrive twice. `replace` and `update` with stable DOM ids are safe. `append` can duplicate items: give appended elements a DOM id, and Turbo replaces an existing element with the same id.
213
+ - History is limited (100 messages and 5 minutes by default). Handle the loss:
214
+
215
+ ```js
216
+ channel.on("info", (ev) => {
217
+ if (ev.type === "history_not_found") Turbo.visit(window.location.href, { action: "replace" })
218
+ })
219
+ ```
220
+
221
+ - A restored session does not call `subscribed` or `disconnect` again.
222
+
223
+ Docs: <https://docs.anycable.io/anycable-go/reliable_streams>.
224
+
225
+ ## 7. Stream design
226
+
227
+ - Name streams after the resource, not the user: `[chat, :messages]`, not `[user, :chat_messages]`.
228
+ - Per-user streams are fine for truly personal data: notifications, a job's progress for its initiator.
229
+ - For one-off progress (an import, an LLM answer), use a stream per operation: `turbo_stream_from [import, :progress]`.
230
+ - Do not stream unescaped user content with `html:`. Render a partial or escape the content.
231
+ - Personalization: read `personalization.md` before you render user-specific HTML in a broadcast.
@@ -0,0 +1,145 @@
1
+ # Testing AnyCable features
2
+
3
+ Summary: test broadcasts with the `test` adapter in unit tests. Run the main real-time flows in system tests against a real AnyCable server.
4
+
5
+ ## 1. Unit tests: assert broadcasts
6
+
7
+ Keep `adapter: test` for the test environment in `config/cable.yml`. Assert what Rails broadcasts:
8
+
9
+ ```ruby
10
+ # Action Cable (Minitest), ActionCable::TestHelper
11
+ assert_broadcasts("chat_1", 1) do
12
+ message.save!
13
+ end
14
+
15
+ # RSpec
16
+ expect { message.save! }.to have_broadcasted_to("chat_1")
17
+
18
+ # turbo-rails (Minitest), Turbo::Broadcastable::TestHelper
19
+ assert_turbo_stream_broadcasts [chat, :messages] do
20
+ message.save!
21
+ end
22
+ ```
23
+
24
+ These tests do not check AnyCable. They check that Rails sends the right payload to the right stream.
25
+
26
+ Channel unit tests (`ActionCable::Channel::TestCase`, RSpec `type: :channel`) also run without AnyCable.
27
+
28
+ ## 2. System tests against a real AnyCable server
29
+
30
+ Run a real server in system tests for these cases:
31
+
32
+ - the app uses AnyCable-only features: JWT, signed streams without RPC, whispers, presence, reliable streams;
33
+ - you change the AnyCable setup and want a regression test.
34
+
35
+ Two parts are common to all setups:
36
+
37
+ ```ruby
38
+ # config/environments/test.rb
39
+ Rails.application.configure do
40
+ config.action_cable.mount_path = nil
41
+
42
+ config.after_initialize do
43
+ # Point the client to the AnyCable server (set websocket_url in anycable.yml)
44
+ config.action_cable.url = ActionCable.server.config.url = AnyCable.config.websocket_url
45
+
46
+ # Keep the test adapter (for assertions) and also send broadcasts to AnyCable
47
+ AnyCable::Rails.extend_adapter!(ActionCable.server.pubsub)
48
+ end
49
+ end
50
+ ```
51
+
52
+ ```yaml
53
+ # config/anycable.yml
54
+ test:
55
+ <<: *default
56
+ secret: "test"
57
+ broadcast_adapter: http
58
+ ```
59
+
60
+ Then start the server.
61
+
62
+ ### AnyCable Thruster as the Capybara server
63
+
64
+ This setup supports no RPC and HTTP RPC. If the app uses gRPC in production, use HTTP RPC in tests.
65
+
66
+ Thruster starts Puma and the AnyCable server together. Use `capybara-thruster` (<https://github.com/evilmartians/capybara-thruster>).
67
+
68
+ ```ruby
69
+ # Gemfile
70
+ group :test do
71
+ gem "anycable-thruster"
72
+ gem "capybara-thruster"
73
+ end
74
+ ```
75
+
76
+ ```ruby
77
+ # test/application_system_test_case.rb or spec/support/capybara.rb
78
+ Capybara.server_port = 3002
79
+ Capybara.server = :thruster, {
80
+ debug: ENV["DEBUG"] == "1",
81
+ env: {
82
+ "ANYCABLE_SECRET" => "test",
83
+ "ANYCABLE_BROADCAST_ADAPTER" => "http",
84
+ "ANYCABLE_HTTP_BROADCAST_PORT" => "8090",
85
+ "ANYCABLE_TURBO_STREAMS" => "true",
86
+ # none mode:
87
+ "ANYCABLE_NORPC" => "true"
88
+ # HTTP RPC instead (Puma listens on the next port behind Thruster):
89
+ # "ANYCABLE_RPC_HOST" => "http://localhost:3003/_anycable"
90
+ }
91
+ }
92
+ ```
93
+
94
+ Match the Rails side:
95
+
96
+ ```yaml
97
+ # config/anycable.yml
98
+ test:
99
+ <<: *default
100
+ secret: "test"
101
+ broadcast_adapter: http
102
+ websocket_url: "ws://localhost:3002/cable"
103
+ http_broadcast_url: "http://localhost:8090/_broadcast"
104
+ # HTTP RPC only:
105
+ # http_rpc_mount_path: "/_anycable"
106
+ ```
107
+
108
+ Set `http_broadcast_url` explicitly. With a secret, the default URL points to port 8080. The test server listens on 8090.
109
+
110
+ Example app: <https://github.com/anycable/anycasts_demo> (`spec/system/support/capybara_setup.rb`).
111
+
112
+ ## 3. Write the system test
113
+
114
+ - Use two sessions to check that one user sees the change of another:
115
+
116
+ ```ruby
117
+ test "message appears for another user" do
118
+ using_session(:bob) do
119
+ sign_in users(:bob)
120
+ visit chat_path(chats(:general))
121
+ end
122
+
123
+ sign_in users(:alice)
124
+ visit chat_path(chats(:general))
125
+ fill_in "message_body", with: "Hello"
126
+ click_on "Send"
127
+
128
+ using_session(:bob) do
129
+ assert_text "Hello"
130
+ end
131
+ end
132
+ ```
133
+
134
+ - Wait for the subscription before you trigger a change. A Turbo stream source sets the `connected` attribute when it subscribes (`@anycable/turbo-stream`). Check it first:
135
+
136
+ ```ruby
137
+ assert_selector "turbo-cable-stream-source[connected]", visible: :all
138
+ ```
139
+
140
+ - Keep `Capybara.default_max_wait_time` at 2 s or more. Broadcasts are asynchronous.
141
+ - On failure, run with `DEBUG=1` or set `ANYCABLE_DEBUG=1`, and read the server log.
142
+
143
+ ## 4. Command-line checks
144
+
145
+ For quick checks without a browser, use wsdirector. See `live-checks.md`.
@@ -0,0 +1,128 @@
1
+ # Troubleshooting AnyCable
2
+
3
+ Summary: find which hop fails, then fix that hop. There are four hops:
4
+
5
+ ```
6
+ browser ──(1) WebSocket──▶ AnyCable server ──(2) RPC──▶ Rails
7
+ Rails ──(3) broadcast──▶ AnyCable server ──(4) message──▶ browser
8
+ ```
9
+
10
+ Read the official page for the full list of known problems: <https://docs.anycable.io/troubleshooting>.
11
+ Do not guess. Collect evidence from the browser, the server log and the Rails log first. Then check the hop with a script (`live-checks.md`).
12
+
13
+ ## 1. Symptom map
14
+
15
+ | Symptom | Likely cause | Check |
16
+ |---|---|---|
17
+ | `No route matches [GET] "/cable"` in the Rails log | The client connects to Rails, not to AnyCable | The `action-cable-url` meta tag is present, comes before the JS, and has the AnyCable URL. `websocket_url` is set. |
18
+ | `NotImplementedError` in `subscription_adapter/base.rb` | Same: Action Cable serves the connection | Remove `mount ActionCable.server` from routes. Check the proxy target for `/cable`. |
19
+ | Client gets `disconnect` with `reason: "unauthorized"`. Server debug log: `controller authenticate ... response.status=failure` or `no token is found` | JWT missing or expired, wrong secret, cookies do not reach the server | JWT: the token is in the URL or meta tag, and the secrets match. Cookies: same parent domain, `domain: :all`, same `secret_key_base` for web and RPC. |
20
+ | `reject_subscription` for `Turbo::StreamsChannel`. Server debug log: `subscription rejected` | The Turbo verifier key differs from the AnyCable secret, or turbo streams are off on the server | `config.turbo.signed_stream_verifier_key = AnyCable.config.secret`. Server: `ANYCABLE_TURBO_STREAMS=true`. |
21
+ | Subscription confirmed, broadcasts never arrive | The broadcast does not reach the server: wrong adapter, URL, key or Redis channel | Rails log shows the broadcast. Server log (debug) shows the incoming broadcast. Compare `broadcast_adapter`, `http_broadcast_url`, `broadcast_key` on both sides. |
22
+ | A broadcast from `bin/rails runner` or a rake task is lost | The `http` adapter sends from a background thread. The process exits first. | Call `AnyCable.broadcast_adapter.shutdown` at the end of the script. Jobs and web requests are not affected. |
23
+ | Instance variable is `nil` in a channel action | Channel objects do not live between calls | `state_attr_accessor` or `params` (<https://docs.anycable.io/rails/channels_state>). |
24
+ | `Connection#connect` side effects missing | JWT is on. AnyCable does not call `connect` with JWT. | Move the code to a controller or a job. |
25
+ | `disconnect`/`unsubscribed` not called, or called late | Disconnect calls are rate-limited and can be lost on shutdown. Restored sessions skip them. | Do not build state on these callbacks. Use presence. See `--disconnect_mode` in <https://docs.anycable.io/anycable-go/configuration>. |
26
+ | Client disconnects every hour with `token_expired` | JWT TTL (`jwt_ttl`, 1 hour) without a token refresher | Add `tokenRefresher` in the JS client (`realtime-features.md` §2). |
27
+ | Client reconnects in a loop, "stale connection" in the client log | Proxy or load balancer closes idle connections, or ping intervals differ | Proxy idle timeout. Server `--ping_interval` and client `pingInterval` must match. |
28
+ | `too many open files` | OS file descriptor limit | Raise `ulimit -n`. See <https://docs.anycable.io/anycable-go/os_tuning>. |
29
+ | Subscriptions time out under load | RPC is slow or the RPC pool is full | `rpc_pending_num` metric. Tune RPC concurrency (<https://docs.anycable.io/anycable-go/rpc>). |
30
+ | Many connections per user (`clients_uniq_num` ≪ `clients_num`) | A new cable per component or per Turbo visit | One cable module, imported everywhere. Not `@hotwired/turbo-rails` together with `@anycable/turbo-stream`. |
31
+ | Duplicate messages after a reconnect | At-least-once delivery with reliable streams | Make updates idempotent (stable DOM ids, `replace`). |
32
+
33
+ ## 2. Where to look: the AnyCable server
34
+
35
+ - Turn on debug logs: `ANYCABLE_DEBUG=true` (or `--debug`). Debug logs show each command per session (`sid=...`) and each broadcast.
36
+ - The boot log shows the version, the open file limit, the RPC mode, the broker and the broadcast endpoints. Read it first.
37
+ - `/health` returns 200 when the server runs.
38
+ - Metrics: `--metrics_http=/metrics` (Prometheus) or `--metrics_log` (periodic log line). Watch these:
39
+
40
+ | Metric | Meaning |
41
+ |---|---|
42
+ | `clients_num`, `clients_uniq_num` | Connections and unique identifiers |
43
+ | `rpc_pending_num` | RPC calls that wait. Growth means RPC is the bottleneck. |
44
+ | `rpc_error_total`, `rpc_timeouts_total` | RPC failures |
45
+ | `failed_auths_total` | Rejected connections |
46
+ | `broadcast_msg_total` | Broadcasts received from Rails |
47
+ | `disconnect_queue_size` | Pending disconnect calls. Spikes mean mass disconnects. |
48
+
49
+ - Session ids (`sid`) also appear in the Rails RPC log as `[AnyCable sid=...]`. Use them to connect the two logs.
50
+
51
+ Docs: <https://docs.anycable.io/anycable-go/instrumentation>, <https://docs.anycable.io/anycable-go/tracing>.
52
+
53
+ ## 3. Where to look: Rails
54
+
55
+ - RPC calls go to `Rails.logger`. Set `access_logs_disabled: false` to see `Started`/`Finished` lines for each RPC call.
56
+ - gRPC server debug: `ANYCABLE_DEBUG=1 bundle exec anycable`.
57
+ - Exceptions in channels go to `Rails.error.report` (Rails 7+). Custom handler: `AnyCable.capture_exception { |ex, method, message| ... }`.
58
+ - The gRPC server (`bundle exec anycable`) logs `Broadcasting HTTP url: ...` at start. In other modes, check the URL in a console (next item).
59
+ - The server logs where it accepts broadcasts: `Accept broadcast requests at http://...:8080/_broadcast (authorization required)`. Compare it with `http_broadcast_url`.
60
+ - Check the effective config in a console: `AnyCable.config.to_h.slice(:broadcast_adapter, :http_broadcast_url, :websocket_url)`.
61
+
62
+ Docs: <https://docs.anycable.io/ruby/logging>, <https://docs.anycable.io/ruby/exceptions>.
63
+
64
+ ## 4. Where to look: the browser
65
+
66
+ **DevTools → Network → WS filter:**
67
+
68
+ 1. Reload the page with DevTools open. DevTools records frames only while it is open.
69
+ 2. No WebSocket request: the client did not start. Check the JS entry point and the meta tag.
70
+ 3. Check the request URL. It must point to the AnyCable server. It must contain `jid=` when you use JWT in the URL.
71
+ 4. Check the status. 101 is good. A 404 means the request went to Rails.
72
+ 5. Check `Sec-WebSocket-Protocol`: `actioncable-v1-ext-json` for the extended protocol.
73
+ 6. Open **Messages**. Expect `welcome`, then `confirm_subscription` for each stream. Look for `reject_subscription` and `disconnect` with a `reason` (`unauthorized`, `token_expired`, `server_restart`).
74
+ 7. Pings arrive every 3 seconds. Type a message type (`confirm`, `reject`, `disconnect`) in the filter box to find the frames you need.
75
+
76
+ **AnyCable JS client debug mode:**
77
+
78
+ ```js
79
+ const cable = createCable({ logLevel: "debug" })
80
+
81
+ // Development only: inspect the cable from the console
82
+ if (process.env.NODE_ENV === "development") window.cable = cable
83
+ ```
84
+
85
+ - `cable.state` is `idle`, `connecting`, `connected`, `disconnected` or `closed`.
86
+ - `cable.on("disconnect", (ev) => console.log(ev.reason))` shows why the connection dropped.
87
+ - `channel.on("close", ...)` fires on rejection.
88
+
89
+ Docs: <https://github.com/anycable/anycable-client#readme>.
90
+
91
+ ## 5. Connection avalanches and deploys
92
+
93
+ An avalanche (aka _reconnect storm_) happens when many clients reconnect at the same time: after a deploy, a restart or an outage.
94
+ Each reconnect can call RPC (connect + subscribe for every stream). Rails can fall over.
95
+
96
+ Read: <https://evilmartians.com/chronicles/connection-avalanche-safety-tips-and-prepping-for-realtime-applications>.
97
+
98
+ **Reduce the cost of a reconnect:**
99
+
100
+ 1. Use JWT and signed streams. Then a reconnect does not call RPC.
101
+ 2. Use the extended protocol (`actioncable-v1-ext-json`) with the broker. Clients restore sessions after short drops without re-authentication.
102
+ 3. Keep the default JS reconnect strategy (exponential backoff with jitter). Do not write your own retry loop.
103
+ 4. Under heavy load, subscribe one at a time: `createCable({ concurrentSubscribes: false })`.
104
+
105
+ **Reduce the number of reconnects:**
106
+
107
+ 1. Run the WebSocket server separately from Rails. App deploys then restart only RPC. Clients stay connected.
108
+ 2. Restart WebSocket servers one at a time (rolling update with `maxUnavailable: 0`).
109
+ 3. Give the server time to drain: raise `--shutdown_timeout`. AnyCable Pro has slow drain (`ANYCABLE_SHUTDOWN_SLOWDRAIN=true`).
110
+ 4. Do not deploy the WebSocket server at peak time.
111
+
112
+ **Make RPC hold the spike:**
113
+
114
+ 1. gRPC: keep `--rpc_concurrency` (server) a bit lower than `rpc_pool_size` (Rails). Keep the database pool at least `rpc_pool_size`.
115
+ 2. Set `--rpc_request_timeout`.
116
+ 3. Watch `rpc_pending_num` and `disconnect_queue_size` during deploys.
117
+
118
+ Load testing: <https://docs.anycable.io/deployment/load_testing>.
119
+
120
+ ## 6. Hotwire caveats
121
+
122
+ - Use `@anycable/turbo-stream`, not `@hotwired/turbo-rails`. The `turbo-rails` package registers `<turbo-cable-stream-source>` and creates its own `@rails/actioncable` consumer. With both packages, the page opens two connections or uses the wrong one.
123
+ - Other imports of `@hotwired/turbo-rails` (for example, in a Stimulus controller or a gem's JS) bring the second consumer back. Search the JS for `turbo-rails`.
124
+ - Without `delayedUnsubscribe`, every navigation or morph can unsubscribe and subscribe again.
125
+ - Rejected Turbo subscriptions (server debug log: `subscription failed` with `verification failed`): the Turbo verifier key differs from the AnyCable secret. See the symptom table in §1.
126
+ - Broadcasts to others reach the author anyway: the broadcast runs in a `_later_` job, or the request has no `X-Socket-ID` header.
127
+
128
+ Setup, options and fixes: `hotwire.md`.
@@ -0,0 +1,51 @@
1
+ # Check a custom Action Cable channel: connect, subscribe, perform an action, receive a broadcast.
2
+ # Needs RPC (HTTP or gRPC): the AnyCable server calls Rails for every command.
3
+ #
4
+ # Env vars:
5
+ # CHANNEL (required) channel class name, for example "ChatChannel"
6
+ # PARAMS subscription params as JSON, for example '{"room_id":1}' (default '{}')
7
+ # ACTION channel action to perform after all clients subscribe (optional)
8
+ # DATA action payload as JSON (default '{}')
9
+ # EXPECT expected broadcast payload as JSON, partial match (optional; default: any message)
10
+ # JWT AnyCable JWT (sent as the `jid` query param)
11
+ # COOKIE raw Cookie header, copied as is from the browser
12
+ # ORIGIN Origin header
13
+ # TIMEOUT seconds to wait for a broadcast (default 30)
14
+ #
15
+ # Run:
16
+ # CHANNEL=ChatChannel PARAMS='{"room_id":1}' ACTION=speak DATA='{"text":"hi"}' EXPECT='{"text":"hi"}' \
17
+ # COOKIE='_app_session=...' wsdirector -f channel.yml -u ws://localhost:8080/cable -s 2
18
+ <% require "json" %>
19
+ <% channel = ENV.fetch("CHANNEL") %>
20
+ <% params = JSON.parse(ENV.fetch("PARAMS", "{}")) %>
21
+ <% identifier = params.merge("channel" => channel).to_json %>
22
+ <% headers = {"Cookie" => ENV["COOKIE"], "Origin" => ENV["ORIGIN"]}.compact %>
23
+ <% options = {} %>
24
+ <% options["query"] = {"jid" => ENV["JWT"]} if ENV["JWT"] %>
25
+ <% options["headers"] = headers if headers.any? %>
26
+ - client:
27
+ name: "member"
28
+ multiplier: ":scale"
29
+ protocol: "action_cable"
30
+ connection_options: <%= options.to_json %>
31
+ actions:
32
+ - subscribe:
33
+ channel: "<%= channel %>"
34
+ params: <%= params.to_json %>
35
+ # Wait until all clients subscribe
36
+ - wait_all
37
+ <% if ENV["ACTION"] %>
38
+ - perform:
39
+ channel: "<%= channel %>"
40
+ params: <%= params.to_json %>
41
+ action: "<%= ENV["ACTION"] %>"
42
+ data: <%= ENV.fetch("DATA", "{}") %>
43
+ <% end %>
44
+ - receive:
45
+ timeout: <%= ENV.fetch("TIMEOUT", "30").to_i %>
46
+ print: true
47
+ data>:
48
+ identifier: '<%= identifier %>'
49
+ <% if ENV["EXPECT"] %>
50
+ message: <%= ENV["EXPECT"] %>
51
+ <% end %>
@@ -0,0 +1,38 @@
1
+ # Check a signed stream subscription and broadcast delivery (Turbo Streams or $pubsub).
2
+ #
3
+ # Env vars:
4
+ # STREAM (required) signed stream name, for example from `signed-stream-name` in the page HTML
5
+ # CHANNEL "Turbo::StreamsChannel" (default) or "$pubsub"
6
+ # JWT AnyCable JWT (sent as the `jid` query param)
7
+ # COOKIE raw Cookie header, copied as is from the browser (for RPC + cookies auth)
8
+ # ORIGIN Origin header (when the server checks allowed origins)
9
+ # TIMEOUT seconds to wait for a broadcast (default 30); 0 = only check the subscription
10
+ #
11
+ # Run:
12
+ # STREAM=... JWT=... wsdirector -f signed-stream.yml -u ws://localhost:8080/cable
13
+ # Add `-s 10` to run 10 listeners.
14
+ <% channel = ENV.fetch("CHANNEL", "Turbo::StreamsChannel") %>
15
+ <% stream = ENV.fetch("STREAM") %>
16
+ <% timeout = ENV.fetch("TIMEOUT", "30").to_i %>
17
+ <% headers = {"Cookie" => ENV["COOKIE"], "Origin" => ENV["ORIGIN"]}.compact %>
18
+ <% options = {} %>
19
+ <% options["query"] = {"jid" => ENV["JWT"]} if ENV["JWT"] %>
20
+ <% options["headers"] = headers if headers.any? %>
21
+ - client:
22
+ name: "listener"
23
+ multiplier: ":scale"
24
+ protocol: "action_cable"
25
+ connection_options: <%= options.to_json %>
26
+ actions:
27
+ - subscribe:
28
+ channel: "<%= channel %>"
29
+ params:
30
+ signed_stream_name: "<%= stream %>"
31
+ <% if timeout > 0 %>
32
+ - receive:
33
+ timeout: <%= timeout %>
34
+ print: true
35
+ # Match only the identifier: Turbo payloads are HTML strings
36
+ data>:
37
+ identifier: '<%= {signed_stream_name: stream, channel: channel}.to_json %>'
38
+ <% end %>
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: anycable-rails-core
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.6.2
4
+ version: 1.6.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - palkan
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-04-02 00:00:00.000000000 Z
11
+ date: 2026-11-29 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: anycable-core
@@ -119,11 +119,24 @@ files:
119
119
  - lib/generators/anycable/setup/setup_generator.rb
120
120
  - lib/generators/anycable/setup/templates/Procfile.dev.tt
121
121
  - lib/generators/anycable/setup/templates/anycable.toml.tt
122
- - lib/generators/anycable/setup/templates/bin/anycable-go.tt
123
122
  - lib/generators/anycable/setup/templates/bin/dev
124
123
  - lib/generators/anycable/setup/templates/config/anycable.yml.tt
125
124
  - lib/generators/anycable/setup/templates/config/cable.yml.tt
126
125
  - lib/generators/anycable/with_os_helpers.rb
126
+ - lib/generators/anycable/with_release_helpers.rb
127
+ - lib/puma/plugin/anycable.rb
128
+ - skills/anycable-rails/SKILL.md
129
+ - skills/anycable-rails/references/deployment.md
130
+ - skills/anycable-rails/references/hotwire.md
131
+ - skills/anycable-rails/references/installation.md
132
+ - skills/anycable-rails/references/live-checks.md
133
+ - skills/anycable-rails/references/personalization.md
134
+ - skills/anycable-rails/references/presence.md
135
+ - skills/anycable-rails/references/realtime-features.md
136
+ - skills/anycable-rails/references/testing.md
137
+ - skills/anycable-rails/references/troubleshooting.md
138
+ - skills/anycable-rails/scenarios/channel.yml
139
+ - skills/anycable-rails/scenarios/signed-stream.yml
127
140
  homepage: http://github.com/anycable/anycable-rails
128
141
  licenses:
129
142
  - MIT
@@ -135,6 +148,8 @@ metadata:
135
148
  source_code_uri: http://github.com/anycable/anycable-rails
136
149
  funding_uri: https://github.com/sponsors/anycable
137
150
  rubygems_mfa_required: 'true'
151
+ hyperdrive_targets: actioncable
152
+ hyperdrive_artifacts: skill
138
153
  post_install_message:
139
154
  rdoc_options: []
140
155
  require_paths:
@@ -1,27 +0,0 @@
1
- #!/bin/bash
2
-
3
- cd $(dirname $0)/..
4
-
5
- # It's recommended to use the exact version of AnyCable here
6
- version="<%= anycable_go_version %>"
7
-
8
- if [ ! -f ./bin/dist/anycable-go ]; then
9
- echo "AnyCable server is not installed, downloading..."
10
- ./bin/rails g anycable:download --version=$version --bin-path=./bin/dist
11
- fi
12
-
13
- if [ -x ./bin/dist/anycable-go ]; then
14
- echo "Setting execution permission for AnyCable server"
15
- chmod +x ./bin/dist/anycable-go
16
- fi
17
-
18
- curVersion=$(./bin/dist/anycable-go -v)
19
-
20
- if [[ "$version" != "latest" ]]; then
21
- if [[ "$curVersion" != "$version"* ]]; then
22
- echo "AnyCable server version is not $version, downloading a new one..."
23
- ./bin/rails g anycable:download --version=$version --bin-path=./bin/dist
24
- fi
25
- fi
26
-
27
- ./bin/dist/anycable-go $@