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,129 @@
|
|
|
1
|
+
# Live checks from the command line
|
|
2
|
+
|
|
3
|
+
Summary: use wsdirector to connect, subscribe and wait for a broadcast without a browser.
|
|
4
|
+
The skill ships two scenarios: `scenarios/signed-stream.yml` and `scenarios/channel.yml`.
|
|
5
|
+
Run them against a local server or a live one. A failed step tells you which hop is broken.
|
|
6
|
+
|
|
7
|
+
wsdirector: <https://github.com/palkan/wsdirector>.
|
|
8
|
+
|
|
9
|
+
## 1. Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
gem install wsdirector-cli
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Do not add it to the app's Gemfile. It is a standalone tool.
|
|
16
|
+
|
|
17
|
+
## 2. Collect the inputs
|
|
18
|
+
|
|
19
|
+
| Input | How to get it |
|
|
20
|
+
|---|---|
|
|
21
|
+
| WebSocket URL | The `action-cable-url` meta tag content without the query, or `AnyCable.config.websocket_url`. Local default: `ws://localhost:8080/cable`. |
|
|
22
|
+
| JWT | The `jid` value from the `action-cable-url` meta tag, the `cable-token` meta tag, or `bin/rails runner 'puts AnyCable::JWT.encode({user: User.first})'`. The keys must match `identified_by`. |
|
|
23
|
+
| Signed stream name | The `signed-stream-name` attribute of `<turbo-cable-stream-source>` in the page HTML, or `bin/rails runner 'puts Turbo::StreamsChannel.signed_stream_name([Chat.first, :messages])'`. For `$pubsub` streams: `AnyCable::Rails.signed_stream_name(...)`. |
|
|
24
|
+
| Cookie (RPC + cookie auth) | DevTools → Network → the `/cable` request → Request Headers → `Cookie`. Copy the whole value. |
|
|
25
|
+
| Origin | The app URL, for example `https://app.example.com`. Needed when the server checks `allowed_origins`. |
|
|
26
|
+
|
|
27
|
+
Pass the cookie through `COOKIE` as a raw header. Do not use wsdirector's `cookies:` option for Rails session cookies: it URL-encodes the value again, and Rails cannot read the session.
|
|
28
|
+
|
|
29
|
+
A JWT expires after `jwt_ttl` (1 hour by default). A check with an old token fails with `Auth Failed` or `Action failed: #receive`. Make a new token for each check.
|
|
30
|
+
|
|
31
|
+
A token and a cookie are credentials. Do not paste them into files that go to git. Pass them as env vars.
|
|
32
|
+
|
|
33
|
+
## 3. Check a signed stream (Turbo Streams, `$pubsub`)
|
|
34
|
+
|
|
35
|
+
The commands assume the skill is installed in `.claude/skills/anycable-rails`. Change the path if it is installed elsewhere.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
STREAM="<signed name>" JWT="<token>" \
|
|
39
|
+
wsdirector -f .claude/skills/anycable-rails/scenarios/signed-stream.yml -u ws://localhost:8080/cable
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
In a second shell, trigger a broadcast:
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
bin/rails runner 'Turbo::StreamsChannel.broadcast_append_to([Chat.first, :messages], target: "messages", html: "<p>ping</p>"); AnyCable.broadcast_adapter.shutdown'
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`AnyCable.broadcast_adapter.shutdown` makes the `http` adapter send the queued message before the process exits. Without it, the broadcast can be lost.
|
|
49
|
+
|
|
50
|
+
Options (env vars):
|
|
51
|
+
|
|
52
|
+
- `CHANNEL='$pubsub'` for `$pubsub` streams. Default: `Turbo::StreamsChannel`.
|
|
53
|
+
- `TIMEOUT=0` checks only the connection and the subscription.
|
|
54
|
+
- `COOKIE`, `ORIGIN` add headers.
|
|
55
|
+
- `-s 10` runs 10 clients at the same time.
|
|
56
|
+
|
|
57
|
+
## 4. Check a custom channel (RPC)
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
CHANNEL=ChatChannel PARAMS='{"room_id":1}' \
|
|
61
|
+
ACTION=speak DATA='{"text":"hi"}' EXPECT='{"text":"hi"}' \
|
|
62
|
+
COOKIE='_app_session=...' \
|
|
63
|
+
wsdirector -f .claude/skills/anycable-rails/scenarios/channel.yml -u ws://localhost:8080/cable -s 2
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
- Each client subscribes, waits for all clients (`wait_all`), performs `ACTION`, and waits for a message on the subscription.
|
|
67
|
+
- `EXPECT` is a partial match on the message payload. Without it, any message passes.
|
|
68
|
+
- Without `ACTION`, the clients only wait. Trigger the broadcast from another shell.
|
|
69
|
+
- Use `JWT` instead of `COOKIE` for JWT authentication.
|
|
70
|
+
|
|
71
|
+
## 5. Read the result
|
|
72
|
+
|
|
73
|
+
Success: `N clients, 0 failures`. With `print: true`, wsdirector also prints each received message.
|
|
74
|
+
|
|
75
|
+
| Output | Meaning | Next step |
|
|
76
|
+
|---|---|---|
|
|
77
|
+
| `WebSocket::Error::Handshake::InvalidStatusCode` | The HTTP upgrade failed: wrong URL or path, the origin is not allowed, or a proxy blocks WebSockets | `curl -i <http-url>/health`. Check `ANYCABLE_ALLOWED_ORIGINS` and add `ORIGIN`. |
|
|
78
|
+
| `got: Auth Failed` | The server rejected the connection: no token, an invalid or expired token, or `connect` rejected it | Check the token and the secret. With `none` RPC, every client needs a token. |
|
|
79
|
+
| `got: Auth Error` | The RPC call failed: Rails is down, wrong `rpc_host`, or an exception in `connect` | Check the Rails log and the RPC settings. |
|
|
80
|
+
| `Subscription rejected to {...}` | The signature is invalid, turbo streams are off, or the channel called `reject` | Signed streams: the verifier key and the secret. Channels: the `subscribed` code and the params. |
|
|
81
|
+
| `Expected to receive ... but nothing has been received` | The subscription works, but no broadcast arrived | Check the broadcast hop (`troubleshooting.md` §1). Watch the server debug log for the incoming broadcast. |
|
|
82
|
+
| `expected: ... ++ got: ...` with another payload | A message arrived but does not match `EXPECT` | Compare the payloads. |
|
|
83
|
+
|
|
84
|
+
Add `-vv` for a per-client log of every frame.
|
|
85
|
+
|
|
86
|
+
## 6. Write your own scenario
|
|
87
|
+
|
|
88
|
+
Start from the shipped files. Main building blocks for `protocol: "action_cable"`:
|
|
89
|
+
|
|
90
|
+
```yaml
|
|
91
|
+
- client:
|
|
92
|
+
name: "watcher"
|
|
93
|
+
multiplier: ":scale" # -s N controls the number of clients
|
|
94
|
+
protocol: "action_cable" # handles welcome and pings
|
|
95
|
+
connection_options:
|
|
96
|
+
query: { jid: "<%= ENV["JWT"] %>" }
|
|
97
|
+
headers: { "Origin": "https://app.example.com" }
|
|
98
|
+
actions:
|
|
99
|
+
- subscribe:
|
|
100
|
+
channel: "PresenceChannel"
|
|
101
|
+
params: { room_id: 1 }
|
|
102
|
+
- wait_all # sync all clients
|
|
103
|
+
- perform:
|
|
104
|
+
channel: "PresenceChannel"
|
|
105
|
+
params: { room_id: 1 }
|
|
106
|
+
action: "ping"
|
|
107
|
+
data: { text: "hi" }
|
|
108
|
+
- receive:
|
|
109
|
+
channel: "PresenceChannel"
|
|
110
|
+
params: { room_id: 1 }
|
|
111
|
+
data>: { type: "joined" } # partial match on a JSON payload
|
|
112
|
+
- sleep: { time: 1, shift: 0.5 }
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Rules:
|
|
116
|
+
|
|
117
|
+
- Scenarios are ERB templates. Use `ENV` for secrets and dynamic values.
|
|
118
|
+
- `receive` with `channel:` matches the payload. A Turbo payload is an HTML string, so a partial `data>:` match on it fails. Match the raw `identifier` instead, as `signed-stream.yml` does.
|
|
119
|
+
- wsdirector builds the identifier as params first, then `channel`. A raw `identifier` string must use the same key order.
|
|
120
|
+
- Without `protocol: "action_cable"`, wsdirector does not skip pings. Raw `receive` steps then get pings first.
|
|
121
|
+
- Whispers: send a raw `{"command":"whisper","identifier":"...","data":{...}}` frame with `send`. See `examples/cursors.yml` in the wsdirector repository.
|
|
122
|
+
|
|
123
|
+
## 7. Check a live (production) server
|
|
124
|
+
|
|
125
|
+
1. Get a token for a test user. Do not use a real customer's token.
|
|
126
|
+
2. Use `wss://` and the production host.
|
|
127
|
+
3. Start with `TIMEOUT=0` and one client. This checks TLS, the proxy, auth and signatures.
|
|
128
|
+
4. Then check delivery with a broadcast to a test-only stream.
|
|
129
|
+
5. Do not run large `-s` values against production. That is a load test. Read <https://docs.anycable.io/deployment/load_testing> and agree on it with the user first.
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# Personalized broadcasts
|
|
2
|
+
|
|
3
|
+
Summary: a broadcast has no `current_user`. Send the same, context-free payload to all subscribers.
|
|
4
|
+
Personalize on the client with data attributes, CSS and small JS controllers.
|
|
5
|
+
|
|
6
|
+
Source: "The pitfalls of realtime-ification" (RailsConf 2022), <https://evilmartians.com/events/the-pitfalls-of-realtime-ification>.
|
|
7
|
+
Slides: <https://noti.st/palkan/MeBUVe/the-pitfalls-of-realtime-ification>.
|
|
8
|
+
|
|
9
|
+
## 1. The problem
|
|
10
|
+
|
|
11
|
+
A broadcast renders a partial once, outside of a request. Anything in the partial that depends on the viewer is wrong for someone:
|
|
12
|
+
|
|
13
|
+
- "mine" or "theirs" (message alignment, an "Edit" button for the author);
|
|
14
|
+
- permissions (admin-only controls);
|
|
15
|
+
- locale, time zone, date format;
|
|
16
|
+
- read/unread state, user-specific counters.
|
|
17
|
+
|
|
18
|
+
Signs of the problem in code:
|
|
19
|
+
|
|
20
|
+
- `current_user` or `Current.user` in a partial that is also used by `broadcast_*`;
|
|
21
|
+
- a broadcast partial that gets `current_user: nil` or a fake user;
|
|
22
|
+
- `helpers.` calls in a model callback that need a request.
|
|
23
|
+
|
|
24
|
+
## 2. Anti-patterns
|
|
25
|
+
|
|
26
|
+
| Anti-pattern | Why it fails |
|
|
27
|
+
|---|---|
|
|
28
|
+
| Render for the author in the HTTP response and broadcast a generic version to others | Other tabs of the author get the generic version. The response and the broadcast race. |
|
|
29
|
+
| Loop over users and broadcast to the personal stream of each user | N renders and N messages for each change. Most users are not online. The publisher must know the receivers, which defeats pub/sub. |
|
|
30
|
+
| "Signal and fetch": broadcast "something changed", every client requests fresh HTML | One change causes one request per open page. A popular page can overload the app (a self-inflicted DDoS). |
|
|
31
|
+
| Render per subscriber in a channel (`stream_from` with a block) | Expensive. AnyCable does not support it. |
|
|
32
|
+
|
|
33
|
+
## 3. Recommended: context-free broadcasts + client-side enhancements
|
|
34
|
+
|
|
35
|
+
1. Render the broadcast partial without viewer context. Put the facts into data attributes:
|
|
36
|
+
|
|
37
|
+
```erb
|
|
38
|
+
<%# app/views/messages/_message.html.erb %>
|
|
39
|
+
<div id="<%= dom_id(message) %>"
|
|
40
|
+
class="message"
|
|
41
|
+
data-controller="message"
|
|
42
|
+
data-author-id="<%= message.user_id %>">
|
|
43
|
+
<p><%= message.body %></p>
|
|
44
|
+
<time datetime="<%= message.created_at.iso8601 %>" data-message-target="time"></time>
|
|
45
|
+
<button class="message-edit" hidden>Edit</button>
|
|
46
|
+
</div>
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
2. Put the viewer context into the layout once:
|
|
50
|
+
|
|
51
|
+
```erb
|
|
52
|
+
<meta name="current-user-id" content="<%= current_user&.id %>">
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
3. Personalize on the client. A Stimulus controller runs for the page render and for every broadcast element:
|
|
56
|
+
|
|
57
|
+
```js
|
|
58
|
+
// app/javascript/controllers/message_controller.js
|
|
59
|
+
import { Controller } from "@hotwired/stimulus"
|
|
60
|
+
|
|
61
|
+
export default class extends Controller {
|
|
62
|
+
static targets = ["time"]
|
|
63
|
+
|
|
64
|
+
connect() {
|
|
65
|
+
const currentUserId = document.querySelector('meta[name="current-user-id"]')?.content
|
|
66
|
+
const mine = this.element.dataset.authorId === currentUserId
|
|
67
|
+
|
|
68
|
+
this.element.classList.toggle("mine", mine)
|
|
69
|
+
this.element.querySelector(".message-edit").hidden = !mine
|
|
70
|
+
|
|
71
|
+
// Local time zone and locale
|
|
72
|
+
const time = new Date(this.timeTarget.getAttribute("datetime"))
|
|
73
|
+
this.timeTarget.textContent = time.toLocaleTimeString()
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
4. Use CSS when you can. No JS is needed for simple cases. Render a rule for the current user in the layout:
|
|
79
|
+
|
|
80
|
+
```erb
|
|
81
|
+
<style>
|
|
82
|
+
.message[data-author-id="<%= current_user.id %>"] { margin-left: auto; }
|
|
83
|
+
</style>
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
5. Keep authorization on the server. Hidden controls are UX only. The controller action still checks permissions.
|
|
87
|
+
|
|
88
|
+
## 4. When the payload really differs by group
|
|
89
|
+
|
|
90
|
+
Use one stream per group when the number of groups is small and fixed:
|
|
91
|
+
|
|
92
|
+
- per locale: `turbo_stream_from @chat, I18n.locale`, then broadcast once per locale;
|
|
93
|
+
- per role: `turbo_stream_from @board, current_user.role`.
|
|
94
|
+
|
|
95
|
+
The cost is one render per group, not per user.
|
|
96
|
+
|
|
97
|
+
Use a per-user stream only for truly personal data: notifications, the progress of the user's own operation.
|
|
98
|
+
|
|
99
|
+
## 5. Page refreshes with morphing
|
|
100
|
+
|
|
101
|
+
Turbo 8 refreshes (`broadcasts_refreshes`, `broadcast_refresh_later_to`) avoid the problem: each client re-renders the page with its own `current_user`. Use them when:
|
|
102
|
+
|
|
103
|
+
- the page has few concurrent viewers;
|
|
104
|
+
- updates are rare, or debounced.
|
|
105
|
+
|
|
106
|
+
Avoid them for busy pages: each broadcast causes a request from every open page.
|
|
107
|
+
To skip the author, send the refresh with the request id of the change (Turbo does this for `broadcasts_refreshes` from a request) or use broadcasts to others (`realtime-features.md` §5).
|
|
108
|
+
|
|
109
|
+
## 6. Consistency checklist
|
|
110
|
+
|
|
111
|
+
- The database is the source of truth. The broadcast is a notification of a change, not the change.
|
|
112
|
+
- Close the page-load gap with the history timestamp meta tag (`realtime-features.md` §6).
|
|
113
|
+
- Make every update idempotent (stable DOM ids).
|
|
114
|
+
- Keep broadcast order: batch broadcasts of one change (`realtime-features.md` §5).
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
# Presence tracking
|
|
2
|
+
|
|
3
|
+
Summary: AnyCable presence keeps the set of users that are online on a stream. Do not store online state in the database.
|
|
4
|
+
Pick the integration by the stream type: signed streams (JS only), channels (server-side join), or Hotwire (the presence element). Read the set from Rails with the REST API.
|
|
5
|
+
|
|
6
|
+
Docs: <https://docs.anycable.io/anycable-go/presence>, <https://docs.anycable.io/rails/extensions#presence-tracking>.
|
|
7
|
+
|
|
8
|
+
## 1. Choose an integration
|
|
9
|
+
|
|
10
|
+
| The app has | Use | RPC | Section |
|
|
11
|
+
|---|---|---|---|
|
|
12
|
+
| Hotwire views, a list of users on the page | `<turbo-cable-presence-source>` | No | `hotwire.md` §7 |
|
|
13
|
+
| Custom JS with signed streams | `channel.presence.join` on a `streamFromSigned` channel | No | §4 |
|
|
14
|
+
| Action Cable channels | `join_presence` in the channel | Yes | §5 |
|
|
15
|
+
| Server code that needs the list (jobs, controllers, APIs) | REST API | No | §6 |
|
|
16
|
+
|
|
17
|
+
Rule: if other users must trust the presence id or info, join from the server (§5). With signed streams, the client sends any id and info it wants.
|
|
18
|
+
|
|
19
|
+
## 2. Requirements
|
|
20
|
+
|
|
21
|
+
- AnyCable server 1.6 or later with the broker: `presets = ["broker"]` (the generator default) or `--broker=memory`.
|
|
22
|
+
- The AnyCable JS client (`@anycable/web`) with `protocol: "actioncable-v1-ext-json"`. The `@rails/actioncable` client has no presence API.
|
|
23
|
+
- Several server nodes: the Redis broker (AnyCable Pro, Redis 7.4+ or Valkey 9.0+). The memory broker keeps presence per node—**not suitable for multi-node setups**.
|
|
24
|
+
- Signed streams: presence is on by default (`--streams_presence`). Source: `streams/config.go` in anycable-go.
|
|
25
|
+
|
|
26
|
+
Settings:
|
|
27
|
+
|
|
28
|
+
| Setting | Default | Meaning |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| `--presence_ttl` (`ANYCABLE_PRESENCE_TTL`) | 15 s | How long a disconnected client stays in the set |
|
|
31
|
+
|
|
32
|
+
## 3. Lifecycle
|
|
33
|
+
|
|
34
|
+
- A presence record has an **id** and an **info** object. Use the user id as the presence id.
|
|
35
|
+
- Several sessions with the same id are one record. `join` fires for the first session. `leave` fires after the last session leaves.
|
|
36
|
+
- A client leaves when it calls `leave`, unsubscribes, or disconnects.
|
|
37
|
+
- After a disconnect, the record stays for `presence_ttl`. A page reload or a short network loss causes no `leave`/`join` pair.
|
|
38
|
+
- The client re-joins after reconnects automatically. Call `join` once.
|
|
39
|
+
|
|
40
|
+
Do not:
|
|
41
|
+
|
|
42
|
+
- update an `online` column from `subscribed`, `unsubscribed` or `disconnect`. AnyCable can skip or delay these calls (`troubleshooting.md`);
|
|
43
|
+
- put large or secret data in the info. Every subscriber of the stream gets it.
|
|
44
|
+
|
|
45
|
+
## 4. Signed streams (JS only)
|
|
46
|
+
|
|
47
|
+
Render the signed stream name for users who may see the presence:
|
|
48
|
+
|
|
49
|
+
```erb
|
|
50
|
+
<div data-controller="room-presence"
|
|
51
|
+
data-room-presence-stream-value="<%= signed_stream_name([@room, :presence]) %>"
|
|
52
|
+
data-room-presence-user-id-value="<%= current_user.id %>"
|
|
53
|
+
data-room-presence-user-name-value="<%= current_user.name %>">
|
|
54
|
+
<ul data-room-presence-target="list"></ul>
|
|
55
|
+
</div>
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
```js
|
|
59
|
+
// app/javascript/controllers/room_presence_controller.js
|
|
60
|
+
import { Controller } from "@hotwired/stimulus"
|
|
61
|
+
import cable from "../cable"
|
|
62
|
+
|
|
63
|
+
export default class extends Controller {
|
|
64
|
+
static targets = ["list"]
|
|
65
|
+
static values = { stream: String, userId: String, userName: String }
|
|
66
|
+
|
|
67
|
+
async connect() {
|
|
68
|
+
this.channel = cable.streamFromSigned(this.streamValue)
|
|
69
|
+
this.unbind = this.channel.on("presence", () => this.render())
|
|
70
|
+
|
|
71
|
+
this.channel.presence.join(this.userIdValue, { name: this.userNameValue })
|
|
72
|
+
this.render()
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
disconnect() {
|
|
76
|
+
this.unbind()
|
|
77
|
+
// Unsubscribe also leaves the presence set
|
|
78
|
+
this.channel.disconnect()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async render() {
|
|
82
|
+
// { "<id>": { name: "..." } }; the client keeps it up to date from join/leave events
|
|
83
|
+
const users = await this.channel.presence.info()
|
|
84
|
+
|
|
85
|
+
this.listTarget.replaceChildren(...Object.values(users).map(({ name }) => {
|
|
86
|
+
const li = document.createElement("li")
|
|
87
|
+
li.textContent = name
|
|
88
|
+
return li
|
|
89
|
+
}))
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
- `channel.on("presence", ({ type, id, info }) => ...)`: `type` is `join`, `leave`, `info` or `error`. A `leave` event has no info.
|
|
95
|
+
- `presence.info()` works without `join`. Use it for read-only views, for example an admin page.
|
|
96
|
+
- The stream can be the same stream that carries the page updates. A separate `:presence` stream keeps presence events away from other subscribers.
|
|
97
|
+
|
|
98
|
+
## 5. Channels (server-side join)
|
|
99
|
+
|
|
100
|
+
Use a channel when the server must set the id and the info. Include the module in the base channel and set the defaults:
|
|
101
|
+
|
|
102
|
+
```ruby
|
|
103
|
+
class ApplicationCable::Channel < ActionCable::Channel::Base
|
|
104
|
+
include AnyCable::Rails::Channel::Presence
|
|
105
|
+
|
|
106
|
+
private
|
|
107
|
+
|
|
108
|
+
def user_presence_id
|
|
109
|
+
current_user.id
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def user_presence_info
|
|
113
|
+
{name: current_user.name}
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Join in `subscribed`:
|
|
119
|
+
|
|
120
|
+
```ruby
|
|
121
|
+
class RoomChannel < ApplicationCable::Channel
|
|
122
|
+
def subscribed
|
|
123
|
+
room = Room.find(params[:id])
|
|
124
|
+
return reject unless current_user.can_read?(room)
|
|
125
|
+
|
|
126
|
+
stream_for room
|
|
127
|
+
join_presence # uses the first stream of this action
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# Optional: hide the user without an unsubscribe, for example "invisible mode"
|
|
131
|
+
def hide
|
|
132
|
+
leave_presence
|
|
133
|
+
end
|
|
134
|
+
end
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
API (source: `lib/anycable/rails/channel/presence.rb`):
|
|
138
|
+
|
|
139
|
+
| Method | Meaning |
|
|
140
|
+
|---|---|
|
|
141
|
+
| `join_presence(stream = nil, id: user_presence_id, info: user_presence_info)` | Join the presence set of `stream`. Without `stream`, it uses the first stream of the current action. If the action has no streams, it raises `ArgumentError`. |
|
|
142
|
+
| `leave_presence(id = user_presence_id)` | Leave the presence set. |
|
|
143
|
+
| `user_presence_id` | Default id: the connection identifier. Override it. |
|
|
144
|
+
| `user_presence_info` | Default info: none. Override it. |
|
|
145
|
+
|
|
146
|
+
- Both methods do nothing under the Action Cable server. Tests with the `test` adapter do not see presence.
|
|
147
|
+
- The default id is the full connection identifier. Override `user_presence_id`, so that the id is short and stable.
|
|
148
|
+
|
|
149
|
+
Read the presence on the client with the AnyCable client:
|
|
150
|
+
|
|
151
|
+
```js
|
|
152
|
+
import cable from "./cable"
|
|
153
|
+
|
|
154
|
+
const channel = cable.subscribeTo("RoomChannel", { id: roomId })
|
|
155
|
+
|
|
156
|
+
channel.on("presence", ({ type, id, info }) => { /* update the list */ })
|
|
157
|
+
const users = await channel.presence.info()
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Do not call `channel.presence.join` from the client for a channel. The server must join first. Before that, the client gets an error.
|
|
161
|
+
|
|
162
|
+
## 6. REST API (read the set from Rails)
|
|
163
|
+
|
|
164
|
+
The AnyCable server returns the presence set of a stream over HTTP. Needs AnyCable server 1.6.9 or later. Source: <https://docs.anycable.io/anycable-go/api>.
|
|
165
|
+
|
|
166
|
+
```text
|
|
167
|
+
GET <server>/api/presence/<url-encoded stream>/users
|
|
168
|
+
Authorization: Bearer <api secret>
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Response:
|
|
172
|
+
|
|
173
|
+
```json
|
|
174
|
+
{"type": "info", "total": 2, "records": [{"id": "1", "info": {"name": "Alice"}}, {"id": "2", "info": {"name": "Bob"}}]}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
An empty set returns `{"total": 0}` with no `records`.
|
|
178
|
+
|
|
179
|
+
The stream is the **unsigned** stream name:
|
|
180
|
+
|
|
181
|
+
| Presence joined with | Stream name in Ruby |
|
|
182
|
+
|---|---|
|
|
183
|
+
| `signed_stream_name([room, :presence])` or `Turbo::StreamsChannel.signed_stream_name([room, :presence])` | `AnyCable::Rails.stream_name_from([room, :presence])` |
|
|
184
|
+
| `stream_for room` + `join_presence` in `RoomChannel` | `RoomChannel.broadcasting_for(room)` |
|
|
185
|
+
| `stream_from "room_1"` + `join_presence` | `"room_1"` |
|
|
186
|
+
|
|
187
|
+
Ruby client:
|
|
188
|
+
|
|
189
|
+
```ruby
|
|
190
|
+
# app/models/room_presence.rb
|
|
191
|
+
require "net/http"
|
|
192
|
+
|
|
193
|
+
class RoomPresence
|
|
194
|
+
# The API secret derives from the AnyCable secret, unless the server has --api_secret
|
|
195
|
+
API_SECRET = -> { OpenSSL::HMAC.hexdigest("SHA256", AnyCable.config.secret, "api-cable") }
|
|
196
|
+
|
|
197
|
+
def self.users(room)
|
|
198
|
+
stream = AnyCable::Rails.stream_name_from([room, :presence])
|
|
199
|
+
uri = URI("#{ENV.fetch("ANYCABLE_API_URL")}/presence/#{ERB::Util.url_encode(stream)}/users")
|
|
200
|
+
|
|
201
|
+
response = Net::HTTP.get_response(uri, {"Authorization" => "Bearer #{API_SECRET.call}"})
|
|
202
|
+
raise "AnyCable API error: #{response.code}" unless response.is_a?(Net::HTTPSuccess)
|
|
203
|
+
|
|
204
|
+
JSON.parse(response.body).fetch("records", [])
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
- `ANYCABLE_API_URL` is the server address plus `/api`, for example `http://anycable:8080/api` or `http://localhost:8080/api`.
|
|
210
|
+
- The API listens on the main server port by default. `--api_port` and `--api_path` change that.
|
|
211
|
+
- The server log shows `Handle API requests at ...` at start. No such line means the API is off. The API needs a secret, a separate `--api_port`, or public mode.
|
|
212
|
+
- Call the API from the private network when you can. A proxy in front of the server must route `/api` to it.
|
|
213
|
+
- Each call is an HTTP request to the server. Do not call it for every page render of a busy page. Cache the result for a few seconds, or render the list on the client.
|
|
214
|
+
|
|
215
|
+
Quick check from the terminal:
|
|
216
|
+
|
|
217
|
+
```sh
|
|
218
|
+
API_SECRET=$(echo -n 'api-cable' | openssl dgst -sha256 -hmac "$ANYCABLE_SECRET" | awk '{print $2}')
|
|
219
|
+
curl -H "Authorization: Bearer $API_SECRET" "http://localhost:8080/api/presence/$(ruby -rerb -e 'print ERB::Util.url_encode(ARGV[0])' 'room_1')/users"
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## 7. Hotwire
|
|
223
|
+
|
|
224
|
+
Use `<turbo-cable-presence-source>`. It needs no JS code and no RPC. See `hotwire.md` §7.
|
|
225
|
+
|
|
226
|
+
## 8. Troubleshooting
|
|
227
|
+
|
|
228
|
+
| Symptom | Cause | Fix |
|
|
229
|
+
|---|---|---|
|
|
230
|
+
| `presence.info()` rejects with `failed to retrieve presence`, or an `error` presence event | No broker on the server | `presets = ["broker"]` |
|
|
231
|
+
| No presence events, nothing in DevTools | The client uses the base protocol or `@rails/actioncable` | `createCable({ protocol: "actioncable-v1-ext-json" })` |
|
|
232
|
+
| Users stay in the list after they leave | `presence_ttl` (15 s) after a disconnect | Expected. Lower `--presence_ttl` if needed. |
|
|
233
|
+
| Different lists on different users | Several server nodes with the memory broker | Redis broker (AnyCable Pro), or one node |
|
|
234
|
+
| One user shows twice | Different presence ids for the same user (for example, a session id) | Use the user id |
|
|
235
|
+
| `join_presence` raises `ArgumentError` | No stream in the current action | Call `stream_from`/`stream_for` first, or pass the stream |
|
|
236
|
+
| REST API returns `401` | Wrong API secret | Derive it from the same `ANYCABLE_SECRET`, or use `--api_secret` |
|
|
237
|
+
| REST API returns `501` | No broker on the server | `presets = ["broker"]` |
|
|
238
|
+
| REST API returns an empty set, but users are online | Wrong stream name (signed name, or a different suffix) | Use the unsigned name from the table in §6 |
|
|
239
|
+
|
|
240
|
+
In the browser, look for `presence` frames in DevTools → Network → WS → Messages. Turn on the client debug log: `createCable({ logLevel: "debug" })`.
|