cabby-rails 0.1.0
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 +7 -0
- data/CHANGELOG.md +27 -0
- data/LICENSE +21 -0
- data/README.md +190 -0
- data/lib/action_cable/subscription_adapter/cabby.rb +29 -0
- data/lib/cabby/broadcast/http.rb +103 -0
- data/lib/cabby/broadcast/nats.rb +45 -0
- data/lib/cabby/broadcast/postgres.rb +52 -0
- data/lib/cabby/broadcast/redis.rb +25 -0
- data/lib/cabby/broadcast/redis_connection.rb +54 -0
- data/lib/cabby/broadcast/redisx.rb +25 -0
- data/lib/cabby/broadcast.rb +53 -0
- data/lib/cabby/config.rb +159 -0
- data/lib/cabby/errors.rb +16 -0
- data/lib/cabby/rails/helper.rb +10 -0
- data/lib/cabby/rails/identifiers.rb +47 -0
- data/lib/cabby/rails/railtie.rb +34 -0
- data/lib/cabby/rails/remote_connections.rb +34 -0
- data/lib/cabby/rails/rpc/channel_streams.rb +19 -0
- data/lib/cabby/rails/rpc/command.rb +122 -0
- data/lib/cabby/rails/rpc/compat.rb +25 -0
- data/lib/cabby/rails/rpc/connect.rb +30 -0
- data/lib/cabby/rails/rpc/disconnect.rb +41 -0
- data/lib/cabby/rails/rpc/handler.rb +71 -0
- data/lib/cabby/rails/rpc/log_tags.rb +27 -0
- data/lib/cabby/rails/rpc/metadata.rb +26 -0
- data/lib/cabby/rails/rpc/rack_env.rb +73 -0
- data/lib/cabby/rails/rpc/server.rb +79 -0
- data/lib/cabby/rails/rpc/socket.rb +37 -0
- data/lib/cabby/rails/rpc.rb +113 -0
- data/lib/cabby/rails/serializer.rb +58 -0
- data/lib/cabby/rails/state.rb +70 -0
- data/lib/cabby/rails/version.rb +5 -0
- data/lib/cabby/rails/wiring.rb +30 -0
- data/lib/cabby/rails.rb +30 -0
- data/lib/cabby/secrets.rb +18 -0
- data/lib/cabby/signed_streams.rb +48 -0
- data/lib/cabby-rails.rb +2 -0
- data/lib/cabby.rb +57 -0
- data/lib/generators/cabby/setup/setup_generator.rb +138 -0
- data/lib/generators/cabby/setup/templates/cabby.yml +24 -0
- data/lib/generators/cabby/setup/templates/cable.yml +10 -0
- metadata +165 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 67ab3ea624786770f246347bfe40ed1c09e3fc44e335bb4dcec999c1ede3d76e
|
|
4
|
+
data.tar.gz: 1dcd1accf9ba63537f017fc016afdf14f5fc91d9bb71c179357a57fa55e1b252
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 55637b592b25f09705c4a254e530aa49da3ab43c7911f336f61e27f1e03120011e3f06786b8d5580116c6564fcf0d1c2aca22db15565a73ddb482213b6e4926c
|
|
7
|
+
data.tar.gz: b0f822df2dc1bf848f6f5088e6f1edfb1b8458003a6a7cea8e3345d10e06c7ae44b4f2de09ca51224cc130698e62b04feabc97fb53bf55d289fcd1e223d6b821
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-11-28)
|
|
4
|
+
|
|
5
|
+
The first release: a Rails app runs on Cabby with its own connections and channels.
|
|
6
|
+
|
|
7
|
+
- The RPC endpoint, `mount Cabby::Rails::RPC => "/_cabby"`: Cabby calls it to run the app's
|
|
8
|
+
`ApplicationCable::Connection` and channels (connect, subscribe, perform, unsubscribe,
|
|
9
|
+
disconnect), inside the Rails executor, with cookies, the session, headers and params.
|
|
10
|
+
- Authentication with the secret shared with the server; without one, the endpoint answers only
|
|
11
|
+
in development and test.
|
|
12
|
+
- A rejected subscription starts no streams.
|
|
13
|
+
- `state_attr_accessor` on connections and channels, kept by the server between calls; records
|
|
14
|
+
as tagged GlobalIDs, strings always strings.
|
|
15
|
+
- Deterministic identifiers, so remote disconnects match the connection.
|
|
16
|
+
- `adapter: cabby` for Action Cable: `ActionCable.server.broadcast`, `broadcast_to`, Turbo's
|
|
17
|
+
broadcasts and `remote_connections.where(...).disconnect` reach the server.
|
|
18
|
+
- `Cabby.broadcast`, `Cabby.broadcast_batch` and `Cabby.disconnect`, with `exclude_socket:` and
|
|
19
|
+
`Cabby::Rails.current_sid`.
|
|
20
|
+
- Broadcasters: HTTP (default), PostgreSQL (sent only if the transaction commits), Redis
|
|
21
|
+
streams, Redis pub/sub and NATS.
|
|
22
|
+
- `config/cabby.yml` per environment, under `CABBY_*` variables and `Cabby.configure`, with the
|
|
23
|
+
server's own variable names and defaults; `url` for the browsers' WebSocket URL.
|
|
24
|
+
- Signed streams: `Cabby.sign_stream`, `Cabby.verify_stream` and `cabby_signed_stream_name`.
|
|
25
|
+
- Turbo: works with no setup; with a secret, Turbo gets the key the server's `--turbo_streams`
|
|
26
|
+
verifies with.
|
|
27
|
+
- `bin/rails g cabby:setup`.
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daniele Pestilli
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# cabby-rails
|
|
2
|
+
|
|
3
|
+
The Rails integration for [Cabby](https://cabbyhq.com), the real-time server. Cabby holds the
|
|
4
|
+
WebSocket connections; your app keeps its own `ApplicationCable::Connection` and channels, and
|
|
5
|
+
Cabby calls it over HTTP to run them. Pure Ruby, no native extensions.
|
|
6
|
+
|
|
7
|
+
Requirements: Ruby 3.2+, Rails 8.0 or 8.1, a `cabby` server.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```ruby
|
|
12
|
+
# Gemfile
|
|
13
|
+
gem "cabby-rails"
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
bundle install
|
|
18
|
+
bin/rails g cabby:setup
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The generator writes `config/cabby.yml`, sets `adapter: cabby` in `config/cable.yml` for
|
|
22
|
+
development and production (test is left alone), mounts the endpoint in `config/routes.rb`, and
|
|
23
|
+
prints the `cabby` command to run. Running it again changes nothing.
|
|
24
|
+
|
|
25
|
+
```ruby
|
|
26
|
+
# config/routes.rb (what the generator adds)
|
|
27
|
+
mount Cabby::Rails::RPC => "/_cabby"
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## How it works
|
|
31
|
+
|
|
32
|
+
1. Browsers connect to Cabby (`ws://localhost:8080/cable`) with the usual Action Cable client.
|
|
33
|
+
2. Cabby calls `POST /_cabby/connect`, `/command` and `/disconnect` on the app.
|
|
34
|
+
3. Each call builds your real connection and channel, runs your code, and answers with the
|
|
35
|
+
identifiers, streams and messages; Cabby keeps the subscriptions.
|
|
36
|
+
4. Broadcasts from the app (`ActionCable.server.broadcast`, `broadcast_to`, Turbo) go to Cabby
|
|
37
|
+
through `adapter: cabby`.
|
|
38
|
+
5. App and server share one secret: it authenticates the calls both ways.
|
|
39
|
+
|
|
40
|
+
## Run Cabby
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
export CABBY_SECRET=$(bin/rails secret) # or the credentials, see config/cabby.yml
|
|
44
|
+
cabby --rpc_host=http://localhost:3000/_cabby --secret=$CABBY_SECRET
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Add `--turbo_streams` when the app uses Turbo (see below). Cabby forwards the `Cookie` header to
|
|
48
|
+
`connect`; list any other header it reads: `--headers=cookie,x-tenant`.
|
|
49
|
+
|
|
50
|
+
Without a secret the endpoint answers only in development and test; outside development and
|
|
51
|
+
test it refuses every call (and says so in the log).
|
|
52
|
+
|
|
53
|
+
## Configuration
|
|
54
|
+
|
|
55
|
+
`config/cabby.yml` (per environment, ERB, a `default` block with an alias works), then `CABBY_*`
|
|
56
|
+
variables, then `Cabby.configure { |c| ... }` in an initializer, each over the one before. A key
|
|
57
|
+
the gem does not know in `config/cabby.yml` is an error. Where the server reads the same
|
|
58
|
+
variable, so does the gem, with the server's default.
|
|
59
|
+
|
|
60
|
+
| Setting | Variable | Default |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| `secret` | `CABBY_SECRET` | none |
|
|
63
|
+
| `http_rpc_secret` | `CABBY_HTTP_RPC_SECRET` | derived from `secret` |
|
|
64
|
+
| `url` | `CABBY_URL` | none (browsers' WebSocket URL; given to Action Cable when the app sets none) |
|
|
65
|
+
| `broadcast_adapter` | `CABBY_BROADCAST_ADAPTER` | `http` |
|
|
66
|
+
| `broadcast_url` | `CABBY_BROADCAST_URL` | `http://localhost:8080/_broadcast` with a secret or key, else `http://localhost:8090/_broadcast` |
|
|
67
|
+
| `broadcast_key` | `CABBY_BROADCAST_KEY` | derived from `secret` |
|
|
68
|
+
| `broadcast_open_timeout` | `CABBY_BROADCAST_OPEN_TIMEOUT` | `2` (seconds) |
|
|
69
|
+
| `broadcast_read_timeout` | `CABBY_BROADCAST_READ_TIMEOUT` | `5` (seconds) |
|
|
70
|
+
| `postgres_schema` | `CABBY_POSTGRES_SCHEMA` | `public` |
|
|
71
|
+
| `postgres_table_prefix` | `CABBY_POSTGRES_TABLE_PREFIX` | `cabby_` |
|
|
72
|
+
| `redis_url` | `CABBY_REDIS_URL`, `REDIS_URL` | `redis://localhost:6379` |
|
|
73
|
+
| `redisx_stream` | `CABBY_REDISX_STREAM` | the server's |
|
|
74
|
+
| `redis_channel` | `CABBY_REDIS_CHANNEL` | the server's |
|
|
75
|
+
| `nats_servers` | `CABBY_NATS_SERVERS` | `nats://127.0.0.1:4222` |
|
|
76
|
+
| `nats_channel` | `CABBY_NATS_CHANNEL` | the server's |
|
|
77
|
+
| `streams_secret` | `CABBY_STREAMS_SECRET` | `secret` |
|
|
78
|
+
| `turbo_streams_secret` | `CABBY_TURBO_STREAMS_SECRET` | `streams_secret`, then `secret` |
|
|
79
|
+
| `turbo_streams` | `CABBY_TURBO_STREAMS` | `true` (give Turbo the server's key) |
|
|
80
|
+
| `rpc_max_body_size` | `CABBY_RPC_MAX_BODY_SIZE` | 16 MiB |
|
|
81
|
+
|
|
82
|
+
A secret set to `none` counts as unset, as on the server.
|
|
83
|
+
|
|
84
|
+
## Broadcasting
|
|
85
|
+
|
|
86
|
+
With `adapter: cabby`, `ActionCable.server.broadcast`, `broadcast_to`, Turbo's broadcasts and
|
|
87
|
+
`ActionCable.server.remote_connections.where(...).disconnect` reach Cabby. `where` takes every
|
|
88
|
+
identifier the connection declares, `nil` included, as in Action Cable. From anywhere:
|
|
89
|
+
|
|
90
|
+
```ruby
|
|
91
|
+
Cabby.broadcast("chat_#{room.id}", { text: "hi" })
|
|
92
|
+
Cabby.broadcast("chat_#{room.id}", { text: "hi" }, exclude_socket: Cabby::Rails.current_sid) # not the sender
|
|
93
|
+
Cabby.broadcast_batch([{ stream: "a", data: { n: 1 } }, { stream: "b", data: "two" }])
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`Cabby::Rails.current_sid` is the session id of the RPC call being handled (nil outside one).
|
|
97
|
+
|
|
98
|
+
| `broadcast_adapter` | Run Cabby with | The app needs |
|
|
99
|
+
|---|---|---|
|
|
100
|
+
| `http` | `--broadcast_adapter=http` (default) | nothing |
|
|
101
|
+
| `postgres` | `--broadcast_adapter=postgres --postgres_url=...` | Active Record on PostgreSQL; a broadcast in a transaction is sent only if it commits |
|
|
102
|
+
| `redisx` | `--broadcast_adapter=redisx` | `redis-client` or `redis` |
|
|
103
|
+
| `redis` | `--broadcast_adapter=redis` (live only, no history) | `redis-client` or `redis` |
|
|
104
|
+
| `nats` | `--broadcast_adapter=nats` | `nats-pure` |
|
|
105
|
+
|
|
106
|
+
A refused or failed broadcast raises `Cabby::BroadcastError` (`#status` holds the HTTP status).
|
|
107
|
+
|
|
108
|
+
## Signed streams
|
|
109
|
+
|
|
110
|
+
Cabby subscribes a client to a signed stream name on its own, with no call to the app:
|
|
111
|
+
|
|
112
|
+
```ruby
|
|
113
|
+
Cabby.sign_stream("room-#{room.id}") # needs streams_secret or secret
|
|
114
|
+
Cabby.verify_stream(signed) # the name, or nil
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
```erb
|
|
118
|
+
<%= cabby_signed_stream_name("room-#{room.id}") %>
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The client subscribes with `{ channel: "$pubsub", signed_stream_name: "..." }`, and
|
|
122
|
+
`Cabby.broadcast("room-#{room.id}", ...)` reaches it.
|
|
123
|
+
|
|
124
|
+
## Turbo
|
|
125
|
+
|
|
126
|
+
`turbo_stream_from` and `Turbo::StreamsChannel.broadcast_*_to` (and `broadcasts_to` in models)
|
|
127
|
+
work with no setup: subscriptions go through your app's `Turbo::StreamsChannel`, broadcasts
|
|
128
|
+
through the adapter.
|
|
129
|
+
|
|
130
|
+
With a secret configured, the gem gives Turbo the key the server's `--turbo_streams` verifies
|
|
131
|
+
with (`turbo_streams_secret`, else `streams_secret`, else `secret`, as the server falls back).
|
|
132
|
+
Run Cabby with `--turbo_streams` and it confirms Turbo subscriptions itself, without calling the
|
|
133
|
+
app. Set `turbo_streams: false` to leave Turbo's key alone. A key the app sets itself
|
|
134
|
+
(`config.turbo.signed_stream_verifier_key`) is kept; then give Cabby that key with
|
|
135
|
+
`--turbo_streams_secret`, or run it without `--turbo_streams`: if the app sets
|
|
136
|
+
`Turbo.signed_stream_verifier_key` after boot, the server's key no longer matches and Cabby
|
|
137
|
+
rejects those subscriptions.
|
|
138
|
+
|
|
139
|
+
## Channels and state
|
|
140
|
+
|
|
141
|
+
Channels and connections run unchanged. A channel instance lives for one call, so values to
|
|
142
|
+
keep between calls are declared; Cabby holds them:
|
|
143
|
+
|
|
144
|
+
```ruby
|
|
145
|
+
class ChatChannel < ApplicationCable::Channel
|
|
146
|
+
state_attr_accessor :room
|
|
147
|
+
|
|
148
|
+
def subscribed
|
|
149
|
+
self.room = Room.find(params[:id])
|
|
150
|
+
stream_for room
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def speak(data)
|
|
154
|
+
room.messages.create!(text: data["text"])
|
|
155
|
+
end
|
|
156
|
+
end
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`state_attr_accessor` works on connections too. Values are JSON; records are stored as GlobalIDs
|
|
160
|
+
and loaded when read; a string always reads back as a string.
|
|
161
|
+
|
|
162
|
+
What does not run in this model: `periodically` timers (a channel lasts one call; the gem logs a
|
|
163
|
+
warning once per channel class). Use a job instead.
|
|
164
|
+
|
|
165
|
+
## Deploying
|
|
166
|
+
|
|
167
|
+
Run two processes: the app, and `cabby` next to it.
|
|
168
|
+
|
|
169
|
+
- Same `CABBY_SECRET` for both.
|
|
170
|
+
- `cabby --rpc_host=http://<app, internal address>/_cabby --secret=$CABBY_SECRET`, plus
|
|
171
|
+
`--turbo_streams` with Turbo and the `--broadcast_adapter` you use.
|
|
172
|
+
- `CABBY_URL=wss://<the public address of cabby>/cable` in the app, so pages point at Cabby.
|
|
173
|
+
- Cabby's health check is `GET /health`.
|
|
174
|
+
|
|
175
|
+
## Development
|
|
176
|
+
|
|
177
|
+
```sh
|
|
178
|
+
bundle exec rake # tests, then RuboCop
|
|
179
|
+
BUNDLE_GEMFILE=gemfiles/rails_8_0.gemfile bundle exec rake # Rails 8.0
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
The end-to-end tests run a real `cabby` binary: the one on your `PATH`, or the one `CABBY_BIN`
|
|
183
|
+
names (they are skipped without one). The broadcaster tests start their own `redis-server` and
|
|
184
|
+
`nats-server` on free ports (from the `PATH`, or `REDIS_SERVER_BIN` and `NATS_SERVER_BIN`), and
|
|
185
|
+
use a `cabby_rails_test` database on the local PostgreSQL (`CABBY_TEST_PGHOST`,
|
|
186
|
+
`CABBY_TEST_PGPORT`); each is skipped when missing.
|
|
187
|
+
|
|
188
|
+
## License
|
|
189
|
+
|
|
190
|
+
MIT
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
require "action_cable"
|
|
2
|
+
require "cabby-rails"
|
|
3
|
+
|
|
4
|
+
module ActionCable
|
|
5
|
+
module SubscriptionAdapter
|
|
6
|
+
# `adapter: cabby` in config/cable.yml. The Cabby server holds the WebSocket connections and
|
|
7
|
+
# their subscriptions, so this adapter only sends: broadcasts go to the server through the
|
|
8
|
+
# configured broadcaster, and nothing is subscribed in the app's process.
|
|
9
|
+
class Cabby < Base
|
|
10
|
+
def initialize(*)
|
|
11
|
+
super
|
|
12
|
+
::Cabby::Rails::RemoteConnections.install(server)
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# `payload` is already encoded by Action Cable, so it is sent as it is.
|
|
16
|
+
def broadcast(channel, payload)
|
|
17
|
+
::Cabby.broadcast(channel, payload)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def subscribe(_channel, _message_callback, success_callback = nil)
|
|
21
|
+
success_callback&.call
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def unsubscribe(_channel, _message_callback) = nil
|
|
25
|
+
|
|
26
|
+
def shutdown = nil
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
require "net/http"
|
|
2
|
+
require "openssl"
|
|
3
|
+
require "uri"
|
|
4
|
+
|
|
5
|
+
module Cabby
|
|
6
|
+
module Broadcast
|
|
7
|
+
# POSTs to the server's broadcast endpoint over a few kept-alive connections.
|
|
8
|
+
class HTTP
|
|
9
|
+
# A kept-alive connection the server closed: worth one more try on a fresh one.
|
|
10
|
+
STALE = [EOFError, IOError, Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED].freeze
|
|
11
|
+
TIMEOUTS = [Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout].freeze
|
|
12
|
+
MAX_IDLE = 4
|
|
13
|
+
EXCERPT = 200
|
|
14
|
+
|
|
15
|
+
attr_reader :url
|
|
16
|
+
|
|
17
|
+
def self.from_config(config)
|
|
18
|
+
new(url: config.broadcast_url, key: config.broadcast_bearer,
|
|
19
|
+
open_timeout: config.broadcast_open_timeout, read_timeout: config.broadcast_read_timeout)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def initialize(url:, key:, open_timeout:, read_timeout:)
|
|
23
|
+
@url = URI(url)
|
|
24
|
+
@key = key
|
|
25
|
+
@open_timeout = open_timeout
|
|
26
|
+
@read_timeout = read_timeout
|
|
27
|
+
@idle = []
|
|
28
|
+
@lock = Mutex.new
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def broadcast(json)
|
|
32
|
+
check(post(json))
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def shutdown
|
|
36
|
+
connections = @lock.synchronize { @idle.slice!(0..) }
|
|
37
|
+
connections.each { |http| finish(http) }
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
private
|
|
41
|
+
|
|
42
|
+
def post(json, attempt: 1)
|
|
43
|
+
http = checkout
|
|
44
|
+
response = http.request(request(json))
|
|
45
|
+
checkin(http)
|
|
46
|
+
response
|
|
47
|
+
rescue *TIMEOUTS => e
|
|
48
|
+
finish(http)
|
|
49
|
+
raise BroadcastError, "Cabby broadcast to #{shown_url} timed out (#{e.class})"
|
|
50
|
+
rescue *STALE => e
|
|
51
|
+
finish(http)
|
|
52
|
+
return post(json, attempt: attempt + 1) if attempt == 1
|
|
53
|
+
|
|
54
|
+
raise BroadcastError, "Cabby broadcast to #{shown_url} failed: the connection closed (#{e.class})"
|
|
55
|
+
rescue SystemCallError, SocketError, OpenSSL::SSL::SSLError => e
|
|
56
|
+
finish(http)
|
|
57
|
+
raise BroadcastError, "Cabby broadcast to #{shown_url} failed: #{e.message}"
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def request(json)
|
|
61
|
+
headers = { "Content-Type" => "application/json" }
|
|
62
|
+
headers["Authorization"] = "Bearer #{@key}" if @key
|
|
63
|
+
Net::HTTP::Post.new(@url.request_uri, headers).tap { |r| r.body = json }
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def check(response)
|
|
67
|
+
return if response.code.start_with?("2")
|
|
68
|
+
|
|
69
|
+
body = response.body.to_s.strip
|
|
70
|
+
body = "#{body[0, EXCERPT]}..." if body.size > EXCERPT
|
|
71
|
+
raise BroadcastError.new("Cabby refused the broadcast: HTTP #{response.code}: #{body}",
|
|
72
|
+
status: response.code.to_i)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def checkout
|
|
76
|
+
@lock.synchronize { @idle.pop } || connect
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def checkin(http)
|
|
80
|
+
keep = @lock.synchronize { @idle.size < MAX_IDLE && @idle.push(http) }
|
|
81
|
+
finish(http) unless keep
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def connect
|
|
85
|
+
http = Net::HTTP.new(@url.host, @url.port)
|
|
86
|
+
http.use_ssl = @url.scheme == "https"
|
|
87
|
+
http.open_timeout = @open_timeout
|
|
88
|
+
http.read_timeout = @read_timeout
|
|
89
|
+
http.write_timeout = @read_timeout
|
|
90
|
+
http.start
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def finish(http)
|
|
94
|
+
http&.finish if http&.started?
|
|
95
|
+
rescue IOError
|
|
96
|
+
nil
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# Error messages name the endpoint without any credentials.
|
|
100
|
+
def shown_url = "#{@url.scheme}://#{@url.host}:#{@url.port}#{@url.path}"
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Broadcast
|
|
3
|
+
# `--broadcast_adapter=nats`: PUBLISH on the server's NATS subject, flushed so a broadcast
|
|
4
|
+
# that did not reach NATS raises.
|
|
5
|
+
class NATS
|
|
6
|
+
attr_reader :servers, :subject
|
|
7
|
+
|
|
8
|
+
def self.from_config(config)
|
|
9
|
+
new(servers: config.nats_servers.split(",").map(&:strip), subject: config.nats_channel,
|
|
10
|
+
timeout: config.broadcast_read_timeout)
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def initialize(servers:, subject:, timeout:)
|
|
14
|
+
Broadcast.require_library("nats/client", "nats-pure", "nats")
|
|
15
|
+
@servers = servers
|
|
16
|
+
@subject = subject
|
|
17
|
+
@timeout = timeout
|
|
18
|
+
@lock = Mutex.new
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def broadcast(json)
|
|
22
|
+
nats = client
|
|
23
|
+
nats.publish(@subject, json)
|
|
24
|
+
nats.flush(@timeout)
|
|
25
|
+
nil
|
|
26
|
+
rescue ::NATS::IO::Error, SystemCallError => e
|
|
27
|
+
shutdown
|
|
28
|
+
raise BroadcastError, "Cabby broadcast through NATS failed: #{e.message.presence || e.class}"
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def shutdown
|
|
32
|
+
connection = @lock.synchronize { @client.tap { @client = nil } }
|
|
33
|
+
connection&.close
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
private
|
|
37
|
+
|
|
38
|
+
def client
|
|
39
|
+
@lock.synchronize do
|
|
40
|
+
@client ||= ::NATS.connect(servers: @servers, reconnect: false, connect_timeout: @timeout)
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Broadcast
|
|
3
|
+
# Inserts into the server's outbox table on the app's own Active Record connection, so a
|
|
4
|
+
# broadcast made inside a transaction reaches the server only if the transaction commits.
|
|
5
|
+
class Postgres
|
|
6
|
+
# The server's rule for the names it writes into SQL (postgres/mod.rs).
|
|
7
|
+
IDENTIFIER = /\A[A-Za-z_][A-Za-z0-9_]*\z/
|
|
8
|
+
MAX_IDENTIFIER = 63
|
|
9
|
+
# Room the server keeps for its longest table suffix (`pubsub_overflow_expires_at`).
|
|
10
|
+
MAX_PREFIX = MAX_IDENTIFIER - "pubsub_overflow_expires_at".size
|
|
11
|
+
|
|
12
|
+
attr_reader :table
|
|
13
|
+
|
|
14
|
+
def self.from_config(config)
|
|
15
|
+
new(schema: config.postgres_schema, table_prefix: config.postgres_table_prefix)
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def initialize(schema:, table_prefix:)
|
|
19
|
+
Broadcast.require_library("active_record", "activerecord", "postgres") unless defined?(::ActiveRecord::Base)
|
|
20
|
+
check_name("postgres_schema", schema, MAX_IDENTIFIER)
|
|
21
|
+
check_name("postgres_table_prefix", table_prefix, MAX_PREFIX) unless table_prefix.empty?
|
|
22
|
+
@table = %("#{schema}"."#{table_prefix}broadcasts")
|
|
23
|
+
@sql = "INSERT INTO #{@table} (payload) VALUES ($1)"
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def broadcast(json)
|
|
27
|
+
::ActiveRecord::Base.with_connection do |connection|
|
|
28
|
+
unless connection.adapter_name.match?(/postg/i)
|
|
29
|
+
raise ConfigurationError, "the postgres broadcaster needs a PostgreSQL connection, " \
|
|
30
|
+
"not #{connection.adapter_name}"
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
connection.exec_query(@sql, "Cabby broadcast", [json])
|
|
34
|
+
end
|
|
35
|
+
nil
|
|
36
|
+
rescue ::ActiveRecord::StatementInvalid => e
|
|
37
|
+
raise BroadcastError, "Cabby broadcast into #{@table} failed: #{e.message.lines.first&.strip}"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def shutdown = nil
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
def check_name(setting, value, max)
|
|
45
|
+
return if value.match?(IDENTIFIER) && value.bytesize <= max
|
|
46
|
+
|
|
47
|
+
raise ConfigurationError, "invalid #{setting} #{value.inspect}: it must match " \
|
|
48
|
+
"#{IDENTIFIER.source} and be at most #{max} bytes, as on the server"
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
require "cabby/broadcast/redis_connection"
|
|
2
|
+
|
|
3
|
+
module Cabby
|
|
4
|
+
module Broadcast
|
|
5
|
+
# `--broadcast_adapter=redis`: PUBLISH on the server's Redis channel. The server keeps this
|
|
6
|
+
# form for existing setups; it delivers live only (no history), so redisx is preferred.
|
|
7
|
+
class Redis
|
|
8
|
+
attr_reader :channel
|
|
9
|
+
|
|
10
|
+
def self.from_config(config) = new(url: config.redis_url, channel: config.redis_channel)
|
|
11
|
+
|
|
12
|
+
def initialize(url:, channel:, library: nil)
|
|
13
|
+
@channel = channel
|
|
14
|
+
@connection = RedisConnection.new(url, "redis", library: library)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def broadcast(json)
|
|
18
|
+
@connection.call("PUBLISH", @channel, json)
|
|
19
|
+
nil
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def shutdown = @connection.close
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Broadcast
|
|
3
|
+
# One connection to Redis through the client gem the app has: redis-client (which the redis
|
|
4
|
+
# gem 5 and later use), or the redis gem.
|
|
5
|
+
class RedisConnection
|
|
6
|
+
def initialize(url, broadcaster, library: nil)
|
|
7
|
+
@url = url
|
|
8
|
+
@library = library || detect(broadcaster)
|
|
9
|
+
@lock = Mutex.new
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
def call(*command)
|
|
13
|
+
@lock.synchronize { client.call(*command) }
|
|
14
|
+
rescue *errors => e
|
|
15
|
+
@lock.synchronize { reset }
|
|
16
|
+
raise BroadcastError, "Cabby broadcast through Redis failed: #{e.message}"
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def close = @lock.synchronize { reset }
|
|
20
|
+
|
|
21
|
+
private
|
|
22
|
+
|
|
23
|
+
def detect(broadcaster)
|
|
24
|
+
require "redis-client"
|
|
25
|
+
:redis_client
|
|
26
|
+
rescue LoadError
|
|
27
|
+
Broadcast.require_library("redis", "redis-client (or redis)", broadcaster)
|
|
28
|
+
:redis
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def client
|
|
32
|
+
@client ||=
|
|
33
|
+
if @library == :redis_client
|
|
34
|
+
::RedisClient.config(url: @url).new_client
|
|
35
|
+
else
|
|
36
|
+
require "redis"
|
|
37
|
+
::Redis.new(url: @url)
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def reset
|
|
42
|
+
@client&.close
|
|
43
|
+
@client = nil
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def errors
|
|
47
|
+
list = [SystemCallError, IOError]
|
|
48
|
+
list << ::RedisClient::Error if defined?(::RedisClient::Error)
|
|
49
|
+
list << ::Redis::BaseError if defined?(::Redis::BaseError)
|
|
50
|
+
list
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
end
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
require "cabby/broadcast/redis_connection"
|
|
2
|
+
|
|
3
|
+
module Cabby
|
|
4
|
+
module Broadcast
|
|
5
|
+
# `--broadcast_adapter=redisx`: an entry with the field `payload` on the server's Redis
|
|
6
|
+
# stream, read by the server's consumer group (the Redis form the server recommends).
|
|
7
|
+
class Redisx
|
|
8
|
+
attr_reader :stream
|
|
9
|
+
|
|
10
|
+
def self.from_config(config) = new(url: config.redis_url, stream: config.redisx_stream)
|
|
11
|
+
|
|
12
|
+
def initialize(url:, stream:, library: nil)
|
|
13
|
+
@stream = stream
|
|
14
|
+
@connection = RedisConnection.new(url, "redisx", library: library)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def broadcast(json)
|
|
18
|
+
@connection.call("XADD", @stream, "*", "payload", json)
|
|
19
|
+
nil
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def shutdown = @connection.close
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
require "active_support"
|
|
3
|
+
require "active_support/json"
|
|
4
|
+
|
|
5
|
+
module Cabby
|
|
6
|
+
# The JSON the server takes from every broadcaster: one message, an array of messages, or a
|
|
7
|
+
# remote command.
|
|
8
|
+
module Broadcast
|
|
9
|
+
ADAPTERS = {
|
|
10
|
+
"http" => "Cabby::Broadcast::HTTP",
|
|
11
|
+
"postgres" => "Cabby::Broadcast::Postgres",
|
|
12
|
+
"redisx" => "Cabby::Broadcast::Redisx",
|
|
13
|
+
"redis" => "Cabby::Broadcast::Redis",
|
|
14
|
+
"nats" => "Cabby::Broadcast::NATS"
|
|
15
|
+
}.freeze
|
|
16
|
+
|
|
17
|
+
module_function
|
|
18
|
+
|
|
19
|
+
# `data` reaches clients as the message: a String is sent as it is, anything else is
|
|
20
|
+
# encoded once, the way Action Cable encodes what it broadcasts.
|
|
21
|
+
def message(stream, data, exclude_socket: nil, transient: nil)
|
|
22
|
+
meta = {}
|
|
23
|
+
meta[:exclude_socket] = exclude_socket.to_s if exclude_socket
|
|
24
|
+
meta[:transient] = true if transient
|
|
25
|
+
message = { stream: stream.to_s, data: data.is_a?(String) ? data : ActiveSupport::JSON.encode(data) }
|
|
26
|
+
message[:meta] = meta unless meta.empty?
|
|
27
|
+
message
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def disconnect_command(identifier, reconnect:)
|
|
31
|
+
{ command: "disconnect", payload: { identifier: identifier, reconnect: reconnect ? true : false } }
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def build(config)
|
|
35
|
+
name = config.broadcast_adapter
|
|
36
|
+
class_name = ADAPTERS.fetch(name) do
|
|
37
|
+
raise ConfigurationError, "unknown broadcast_adapter #{name.inspect} (use one of #{ADAPTERS.keys.join(", ")})"
|
|
38
|
+
end
|
|
39
|
+
require "cabby/broadcast/#{name}"
|
|
40
|
+
Object.const_get(class_name).from_config(config)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Client libraries are the app's own: they are loaded only for the broadcaster in use.
|
|
44
|
+
def require_library(path, gem_name, broadcaster)
|
|
45
|
+
require path
|
|
46
|
+
rescue LoadError
|
|
47
|
+
raise ConfigurationError, "the #{broadcaster} broadcaster needs the #{gem_name} gem: add it to the Gemfile"
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# The default broadcaster needs nothing beyond the standard library.
|
|
53
|
+
require "cabby/broadcast/http"
|