quicsilver-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.
Files changed (47) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +31 -0
  3. data/LICENSE +21 -0
  4. data/README.md +167 -0
  5. data/app/javascript/quicsilver/action_cable.js +216 -0
  6. data/app/javascript/quicsilver/cable_boot.js +23 -0
  7. data/app/javascript/quicsilver/web_transport.js +120 -0
  8. data/config/importmap.rb +6 -0
  9. data/docs/action-cable.md +203 -0
  10. data/docs/local-certificates.md +119 -0
  11. data/docs/webtransport-endpoints.md +254 -0
  12. data/lib/generators/quicsilver/install/install_generator.rb +95 -0
  13. data/lib/generators/quicsilver/install/templates/Procfile.http3.dev.tt +8 -0
  14. data/lib/generators/quicsilver/install/templates/dev-http3.tt +15 -0
  15. data/lib/generators/quicsilver/install/templates/quicsilver.tt +5 -0
  16. data/lib/quicsilver/action_cable/cookie_bridge.rb +70 -0
  17. data/lib/quicsilver/action_cable/socket.rb +213 -0
  18. data/lib/quicsilver/action_cable.rb +83 -0
  19. data/lib/quicsilver/engine.rb +53 -0
  20. data/lib/quicsilver/middleware/alt_svc.rb +32 -0
  21. data/lib/quicsilver/rails/cable_credential_helper.rb +27 -0
  22. data/lib/quicsilver/rails/dev_web_transport_certificate.rb +155 -0
  23. data/lib/quicsilver/rails/meta_tags_helper.rb +47 -0
  24. data/lib/quicsilver/rails/port.rb +15 -0
  25. data/lib/quicsilver/rails/request_protocol.rb +16 -0
  26. data/lib/quicsilver/rails/server.rb +83 -0
  27. data/lib/quicsilver/rails/transport_logger.rb +62 -0
  28. data/lib/quicsilver/rails/version.rb +7 -0
  29. data/lib/quicsilver/rails/web_transport_certificate_helper.rb +20 -0
  30. data/lib/quicsilver/rails.rb +3 -0
  31. data/lib/quicsilver/routes.rb +27 -0
  32. data/lib/quicsilver/web_transport/channel/dispatcher.rb +76 -0
  33. data/lib/quicsilver/web_transport/channel.rb +69 -0
  34. data/lib/quicsilver/web_transport/codec.rb +43 -0
  35. data/lib/quicsilver/web_transport/datagram_endpoint.rb +40 -0
  36. data/lib/quicsilver/web_transport/endpoint.rb +137 -0
  37. data/lib/quicsilver/web_transport/framed_stream.rb +59 -0
  38. data/lib/quicsilver/web_transport/message_codec.rb +29 -0
  39. data/lib/quicsilver/web_transport/message_stream_endpoint.rb +54 -0
  40. data/lib/quicsilver/web_transport/rpc_endpoint.rb +53 -0
  41. data/lib/quicsilver/web_transport/server_streaming_endpoint.rb +72 -0
  42. data/lib/quicsilver/web_transport/stream_handler.rb +65 -0
  43. data/lib/quicsilver/web_transport/thread_runner.rb +18 -0
  44. data/lib/quicsilver/web_transport.rb +21 -0
  45. data/lib/quicsilver-rails.rb +17 -0
  46. data/lib/tasks/quicsilver.rake +16 -0
  47. metadata +161 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: bd7a13edf8ad3a84c4fee9eae3b2f77e7cbdd7c3a7e98c53d026073c49687b3a
4
+ data.tar.gz: '0542908a10eef060dc1e1bfa3c48a690f21463301ca31cf21d384e1b5fbac6f8'
5
+ SHA512:
6
+ metadata.gz: 967ac7794d5e7703de63ab417ad87cb4143e6db9465c192209f7534d9cdf3ea93de00a1c802e5ee26224ff0486451a2861b6ab01affaebe456e0d83479adcf2c
7
+ data.tar.gz: f189f811a0f7440aa4acfbc4c2036f629953cbf2283e7ffeb8f766069752df39b2a7ce740e8f3f82a233149a1a54f207d268b2f84cb6918f86ef33698a522e0f
data/CHANGELOG.md ADDED
@@ -0,0 +1,31 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0] - 2026-11-27
11
+
12
+ First release. Requires Ruby 3.4+, Rails 8.0+ and Quicsilver 0.6.
13
+
14
+ ### Added
15
+
16
+ - `bin/rails generate quicsilver:install` sets an app up, and `bin/dev-http3` runs it in development: HTTPS on TCP and HTTP/3 on UDP, on the same port.
17
+ - Serve a Rails app over HTTP/3, next to its usual HTTPS server, with `Quicsilver::Rails::Server.start`.
18
+ - Browsers find the HTTP/3 server on their own: an `Alt-Svc` header advertises it whenever `QUICSILVER_PORT` is set.
19
+ - `request.http3?` tells a controller or view whether the request arrived over HTTP/3.
20
+ - A local development certificate that browsers trust, shared by the HTTPS and HTTP/3 servers, created by `bin/rails quicsilver:certificate`.
21
+ - Action Cable and Turbo Streams over WebTransport, with no changes to your channels. Browsers that can't use WebTransport stay on WebSockets.
22
+ - WebTransport cables sign in with the page's cookies, so `ApplicationCable::Connection` doesn't change. Apps using the Rails session or Rails' authentication generator need no configuration.
23
+ - `quicsilver_meta_tags`, one helper for everything a page's `<head>` needs.
24
+ - WebTransport endpoints for realtime features beyond Action Cable: channels, request/response, server streaming, message streams and datagrams, mounted with a `webtransport` route.
25
+ - Errors raised in WebTransport handlers go to `Rails.error`; the client gets a generic error.
26
+ - Browser JavaScript helpers, pinned in your importmap automatically.
27
+ - Quicsilver's logs, and the HTTP/3 server's errors, appear in the Rails log.
28
+ - Settings through environment variables: `QUICSILVER_PORT`, `QUICSILVER_HOST`, `QUICSILVER_DEV_HOSTS`, `QUICSILVER_DEBUG` and `QUICSILVER_SHUTDOWN_TIMEOUT`.
29
+
30
+ [Unreleased]: https://github.com/hahmed/quicsilver-rails/compare/v0.1.0...main
31
+ [0.1.0]: https://github.com/hahmed/quicsilver-rails/releases/tag/v0.1.0
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Haroon Ahmed
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,167 @@
1
+ # quicsilver-rails
2
+
3
+ Warning: early experiment.
4
+
5
+ Rails integration for [Quicsilver](https://github.com/hahmed/quicsilver), a Ruby QUIC and HTTP/3 server.
6
+
7
+ It serves an existing Rails app over HTTP/3 beside its usual HTTPS server, and can move Action Cable (and so Turbo Streams) onto WebTransport. Controllers, views, assets, cookies and sessions work unchanged.
8
+
9
+ ## What works today
10
+
11
+ - Advertise HTTP/3 from an existing HTTPS Rails app with `Alt-Svc`.
12
+ - Serve the same Rails app over HTTP/3 with Quicsilver, on the same host and port number as TCP HTTPS.
13
+ - Normal Rails controllers, middleware, views, assets, cookies and sessions over HTTP/3.
14
+ - Action Cable and Turbo Streams over WebTransport, falling back to WebSocket when a client can't use it.
15
+ - Experimental WebTransport endpoints for browser realtime streams.
16
+
17
+ ## Requirements
18
+
19
+ - Ruby 3.4 or newer, the oldest Ruby Quicsilver ships a binary for.
20
+ - Rails 8.0 or newer. CI runs Rails 8.0, 8.1 and main.
21
+ - Quicsilver 0.6.
22
+
23
+ ## Installation
24
+
25
+ ```ruby
26
+ gem "quicsilver-rails"
27
+ ```
28
+
29
+ ```bash
30
+ bundle install
31
+ bin/rails generate quicsilver:install
32
+ mkcert -install # once per machine, so browsers trust the development certificate
33
+ bin/dev-http3
34
+ ```
35
+
36
+ Then open `https://localhost:3443`. The first page arrives over HTTPS, and the next ones over HTTP/3.
37
+
38
+ The generator writes files you can read and edit, and running it again changes nothing that's already in place:
39
+
40
+ - **`bin/quicsilver`** starts the HTTP/3 server with `Quicsilver::Rails::Server.start`.
41
+ - **`bin/dev-http3`** and **`Procfile.http3.dev`** run Puma on TCP and Quicsilver on UDP, on the same port, the shape production takes. They keep the other processes from your `Procfile.dev`, such as asset watchers.
42
+ - **`<%= quicsilver_meta_tags %>`** goes into your layout's `<head>`, and **`import "quicsilver/cable_boot"`** goes at the top of `app/javascript/application.js`, for [Action Cable over WebTransport](#action-cable-and-turbo-streams-over-webtransport).
43
+
44
+ ### The certificate
45
+
46
+ Browsers check the HTTP/3 server against the certificate they saw over TCP, so Puma and Quicsilver serve the same one. `bin/dev-http3` creates it before either server starts, with `bin/rails quicsilver:certificate`, in `tmp/quicsilver/webtransport/`. It's signed by mkcert's local CA; without mkcert it signs itself, browsers reject it, and the task says so. Set `QUICSILVER_DEV_HOSTS` to add hostnames. See [`docs/local-certificates.md`](docs/local-certificates.md).
47
+
48
+ ### The server
49
+
50
+ `Server.start` loads the development certificate, tunes the transport for browsers, and writes the transport log through `Rails.logger` (tagged `[quicsilver]`, in `log/<env>.log`), including errors the Rack adapter logs, which would otherwise go to stderr. In development it also logs to the terminal, because this process doesn't go through `rails server`. It takes `port:`, `address:`, `certificate:` and `shutdown_timeout:` keywords, which default to the environment variables below.
51
+
52
+ ### Alt-Svc
53
+
54
+ Browsers find the HTTP/3 server through an `Alt-Svc` header on the HTTPS responses. It's on whenever `QUICSILVER_PORT` is set, which `bin/dev-http3` does, and advertises that port. A plain `bin/dev` sends none. Turn it off with `config.quicsilver.alt_svc = false`, or pass options, such as a shorter cache time in development:
55
+
56
+ ```ruby
57
+ config.quicsilver.alt_svc = { max_age: 60 } # browsers stop trying a stopped HTTP/3 server sooner
58
+ ```
59
+
60
+ In production, use port 443: it's the UDP port networks are most likely to let through.
61
+
62
+ Check it from the terminal:
63
+
64
+ ```bash
65
+ curl -sk -o /dev/null -D - https://localhost:3443/ | grep -i alt-svc # alt-svc: h3=":3443"; ma=86400
66
+ curl -sk --http3-only -o /dev/null -w "%{http_version}\n" https://localhost:3443/ # 3
67
+ ```
68
+
69
+ ## Environment variables
70
+
71
+ | Variable | Default | Effect |
72
+ |---|---|---|
73
+ | `QUICSILVER_PORT` | `3443` | UDP port for HTTP/3, and the port Alt-Svc advertises |
74
+ | `QUICSILVER_HOST` | `0.0.0.0` | Address to bind. `0.0.0.0` is IPv4 only; see Quicsilver's notes on IPv6 |
75
+ | `QUICSILVER_DEV_HOSTS` | `localhost,127.0.0.1,::1` | Hostnames in the generated development certificate |
76
+ | `QUICSILVER_SHUTDOWN_TIMEOUT` | Quicsilver's 30s | Seconds a graceful shutdown on INT or TERM may take. A second signal stops at once |
77
+ | `QUICSILVER_DEBUG` | off | Transport detail at DEBUG: a line per request and per response stream. **It includes request headers, cookies among them, so don't share the output** |
78
+
79
+ ## Action Cable and Turbo Streams over WebTransport
80
+
81
+ Browsers don't expose WebSockets over HTTP/3 to JavaScript, so WebTransport is how a browser gets realtime over QUIC. The adapter carries Action Cable over one WebTransport stream; channels, subscriptions and `turbo_stream_from` are unchanged.
82
+
83
+ The install generator adds the two pieces it needs. By hand, for an app it couldn't edit: import the boot module **before** Turbo, which captures the WebSocket class as it loads, and render the tags in the layout:
84
+
85
+ ```js
86
+ // app/javascript/application.js
87
+ import "quicsilver/cable_boot"
88
+ import "@hotwired/turbo-rails"
89
+ ```
90
+
91
+ ```erb
92
+ <%# layout <head> %>
93
+ <%= quicsilver_meta_tags %>
94
+ ```
95
+
96
+ Browsers send no cookies on a WebTransport CONNECT. The page carries them, encrypted, and the cable restores them before `connect` runs, so `ApplicationCable::Connection` needs no change: its usual `cookies` lookup works over both transports. By default that's the Rails session cookie and `session_id`, which is what Devise, `session[:user_id]` and Rails' authentication generator sign in with. If your connection reads another cookie, name it:
97
+
98
+ ```ruby
99
+ # config/application.rb
100
+ config.quicsilver.cable_cookies = %i[session_token]
101
+ ```
102
+
103
+ Only those cookies travel. Logging out revokes the cable if your sessions are database rows; a cookie-store session keeps working until the token expires (a day), as a copied cookie would. See [`docs/action-cable.md`](docs/action-cable.md#authentication).
104
+
105
+ The importmap pins for `quicsilver/*` are added by the engine.
106
+
107
+ The cable follows the page:
108
+
109
+ - A page served over HTTP/3 gets the tags, and the cable uses WebTransport.
110
+ - A page served over TCP gets none (`request.http3?` is false), and the cable uses WebSocket.
111
+ - A WebTransport session that fails to open falls back to WebSocket for the rest of the page, with one console warning.
112
+
113
+ See [`docs/action-cable.md`](docs/action-cable.md) for how it fits together, verification and limits.
114
+
115
+ ## Running Chrome against it locally
116
+
117
+ ```bash
118
+ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
119
+ --user-data-dir=/tmp/quicsilver-chrome-$(date +%s) \
120
+ --origin-to-force-quic-on=localhost:3443 \
121
+ https://localhost:3443/
122
+ ```
123
+
124
+ - Chrome only applies command-line flags to a new browser process. The fresh `--user-data-dir` guarantees one.
125
+ - In our testing Chrome didn't switch to HTTP/3 from `Alt-Svc` alone with a locally trusted certificate. `--origin-to-force-quic-on` forces it, but it also skips `Alt-Svc` discovery, so check `Alt-Svc` with `curl`.
126
+ - In DevTools, enable the Network panel's Protocol column. Pages and assets should show `h3`.
127
+
128
+ ## Telling which transport you're on
129
+
130
+ - `request.http3?` is true for requests that arrived over HTTP/3.
131
+ - Action Cable labels every cable `[WebSocket]`, whatever the transport, because the adapter presents WebSocket's interface. The request method tells them apart:
132
+ - `Started CONNECT "/cable"` with `REQUEST_METHOD: CONNECT` is WebTransport.
133
+ - `Started GET "/cable"` with `HTTP_UPGRADE: websocket` is a TCP WebSocket.
134
+
135
+ ## Experimental WebTransport endpoints
136
+
137
+ Apps mount the endpoints they want:
138
+
139
+ ```ruby
140
+ # config/routes.rb
141
+ Rails.application.routes.draw do
142
+ webtransport "/transports/echo", to: EchoTransport
143
+ end
144
+ ```
145
+
146
+ See [`docs/webtransport-endpoints.md`](docs/webtransport-endpoints.md) for endpoint classes, browser helpers, and examples for message streams, RPC, server streaming and datagrams.
147
+
148
+ ## Demo app
149
+
150
+ [`quicsilver-playground`](https://github.com/hahmed/quicsilver-playground) is a full local Rails demo: TCP HTTPS and UDP HTTP/3 on the same port, pages and assets over HTTP/3, `Alt-Svc` verification and a WebTransport echo.
151
+
152
+ ## More documentation
153
+
154
+ - [`docs/action-cable.md`](docs/action-cable.md): Action Cable over WebTransport, verification and limits.
155
+ - [`docs/webtransport-endpoints.md`](docs/webtransport-endpoints.md): routes, endpoint classes, browser helpers and examples.
156
+ - [`docs/local-certificates.md`](docs/local-certificates.md): local HTTPS, HTTP/3 and WebTransport certificates, and browser behaviour.
157
+
158
+ ## Development
159
+
160
+ ```bash
161
+ bin/setup
162
+ bundle exec rake test
163
+ ```
164
+
165
+ ## Status
166
+
167
+ Experimental.
@@ -0,0 +1,216 @@
1
+ // Action Cable over WebTransport.
2
+ //
3
+ // Action Cable's Connection only touches a handful of WebSocket members, and picks its transport up
4
+ // from `adapters.WebSocket`, so a class with that surface is enough to move the cable protocol onto
5
+ // an HTTP/3 stream. Channel multiplexing, subscriptions and the JSON protocol are untouched above
6
+ // this; only the bytes move differently.
7
+ //
8
+ // Browsers do not expose WebSocket-over-HTTP/3 to JavaScript, so WebTransport is the only way a
9
+ // browser gets realtime over QUIC.
10
+
11
+ import { connect, readFrames, writeFrame } from "quicsilver/web_transport"
12
+
13
+ // Captured before cable_boot swaps the global, so the fallback always reaches the real class.
14
+ let NativeWebSocket = globalThis.WebSocket
15
+
16
+ // Set when a WebTransport session fails to open. The page asked for HTTP/3, but this client cannot
17
+ // reach the listener right now (UDP blocked, listener down), and the browser has already moved its
18
+ // own requests to TCP. The cable follows it: every later socket on this page is a WebSocket.
19
+ let webTransportUnavailable = false
20
+
21
+ function fallBackToWebSocket(error) {
22
+ if (webTransportUnavailable) return
23
+
24
+ webTransportUnavailable = true
25
+ console.warn("[quicsilver] WebTransport failed to open; the cable is reconnecting over WebSocket.", error)
26
+ }
27
+
28
+ // Tests only: forget a previous fallback and choose the class it falls back to.
29
+ export function resetTransportFallback({ WebSocket = globalThis.WebSocket } = {}) {
30
+ NativeWebSocket = WebSocket
31
+ webTransportUnavailable = false
32
+ }
33
+
34
+ // Connection#getState reads these off the constructor with `for (let state in adapters.WebSocket)`,
35
+ // so they must be enumerable own properties, and the names must lowercase to the states it checks
36
+ // ("open", "connecting"). Static class fields satisfy both.
37
+ export class WebTransportSocket {
38
+ static CONNECTING = 0
39
+ static OPEN = 1
40
+ static CLOSING = 2
41
+ static CLOSED = 3
42
+
43
+ constructor(url, protocols = []) {
44
+ // Returning another object from a constructor replaces the instance, so Action Cable holds a
45
+ // real WebSocket without knowing it asked for this class.
46
+ if (webTransportUnavailable && NativeWebSocket) return new NativeWebSocket(url, protocols)
47
+
48
+ this.url = url
49
+ this.readyState = WebTransportSocket.CONNECTING
50
+
51
+ // Reported to Connection#isProtocolSupported, which rejects the connection outright when it does
52
+ // not recognise the value. There is no subprotocol negotiation over WebTransport, so both sides
53
+ // assert the same protocol instead: the Ruby adapter's #protocol does the same.
54
+ this.protocol = [].concat(protocols)[0] || "actioncable-v1-json"
55
+
56
+ this.onopen = null
57
+ this.onclose = null
58
+ this.onerror = null
59
+ this.onmessage = null
60
+
61
+ this.#open()
62
+ }
63
+
64
+ send(data) {
65
+ // A WebSocket throws InvalidStateError here. Connection#send guards on isOpen(), but the monitor
66
+ // can race it, and a throw would escape into the reconnect loop. Report it and drop the frame.
67
+ if (this.readyState !== WebTransportSocket.OPEN) {
68
+ this.onerror?.({ error: new Error(`send on a socket that is ${this.#stateName()}`), target: this })
69
+ return
70
+ }
71
+
72
+ // Deliberately not awaited: Connection#send is synchronous and discards the return value. Write
73
+ // failures surface through the transport's closed promise instead.
74
+ writeFrame(this.#writer, data).catch(error => this.#fail(error))
75
+ }
76
+
77
+ // Asks the transport to close. onclose fires when it has, from the closed promise, so the code
78
+ // and wasClean reflect what the transport reported rather than what was requested.
79
+ close() {
80
+ if (this.readyState === WebTransportSocket.CLOSING || this.readyState === WebTransportSocket.CLOSED) return
81
+
82
+ this.readyState = WebTransportSocket.CLOSING
83
+ if (this.#transport) {
84
+ this.#transport.close()
85
+ } else {
86
+ this.#closed(1000, "")
87
+ }
88
+ }
89
+
90
+ #transport = null
91
+ #writer = null
92
+ #opened = false
93
+
94
+ async #open() {
95
+ try {
96
+ this.#transport = await connect(httpUrl(this.url))
97
+ // Attached as soon as the transport exists, before the stream opens: close() in that window
98
+ // asks the transport to close and relies on this to report it.
99
+ this.#transport.closed.then(() => this.#closed(1000, "")).catch(error => this.#fail(error))
100
+
101
+ const stream = await this.#transport.createBidirectionalStream()
102
+ this.#writer = stream.writable.getWriter()
103
+
104
+ // Always the first frame, so the server can tell it apart from Action Cable traffic. Browsers
105
+ // send no cookies on a WebTransport CONNECT, so this is the only way the connection's #connect
106
+ // learns who is asking. Read on every open rather than once: a reconnect should carry the
107
+ // credential the current page rendered, not the one from page load.
108
+ await writeFrame(this.#writer, JSON.stringify(handshake()))
109
+
110
+ this.readyState = WebTransportSocket.OPEN
111
+ this.#opened = true
112
+ this.onopen?.({ target: this })
113
+
114
+ await this.#receive(stream.readable.getReader())
115
+ } catch (error) {
116
+ this.#fail(error)
117
+ }
118
+ }
119
+
120
+ async #receive(reader) {
121
+ const decoder = new TextDecoder()
122
+
123
+ for await (const frame of readFrames(reader)) {
124
+ // Action Cable expects the WebSocket event shape, and parses event.data itself.
125
+ this.onmessage?.({ data: decoder.decode(frame), target: this })
126
+ }
127
+
128
+ this.#closed(1000, "")
129
+ }
130
+
131
+ #fail(error) {
132
+ // Only a session that never opened says WebTransport is unreachable. One that opened and then
133
+ // dropped is an ordinary disconnect, and reconnects over WebTransport.
134
+ // A socket the page closed while it was opening is not evidence either.
135
+ if (!this.#opened && this.readyState === WebTransportSocket.CONNECTING) fallBackToWebSocket(error)
136
+
137
+ this.onerror?.({ error, target: this })
138
+ this.#closed(1006, String(error?.message || error))
139
+ }
140
+
141
+ #stateName() {
142
+ return Object.keys(WebTransportSocket).find(k => WebTransportSocket[k] === this.readyState)?.toLowerCase()
143
+ }
144
+
145
+ #closed(code, reason) {
146
+ if (this.readyState === WebTransportSocket.CLOSED) return
147
+
148
+ this.readyState = WebTransportSocket.CLOSED
149
+ this.onclose?.({ code, reason, wasClean: code === 1000, target: this })
150
+ }
151
+ }
152
+
153
+ // The handshake frame. The key matches HANDSHAKE_KEY in the Ruby socket. `cookies` is the encrypted
154
+ // token quicsilver_meta_tags rendered, which the server turns back into the page's cookies;
155
+ // `credential` is the optional separate credential.
156
+ export function handshake() {
157
+ return { quicsilver_handshake: { cookies: metaContent("quicsilver-cable-cookies"), credential: metaContent("quicsilver-cable-credential") } }
158
+ }
159
+
160
+ function metaContent(name) {
161
+ const meta = typeof document !== "undefined" && document.querySelector(`meta[name="${name}"]`)
162
+ return meta ? meta.content : null
163
+ }
164
+
165
+ // Action Cable builds ws:// and wss:// URLs; WebTransport takes the https:// origin the HTTP/3
166
+ // listener answers on.
167
+ export function httpUrl(url) {
168
+ return String(url).replace(/^ws/, "http")
169
+ }
170
+
171
+ // WebTransport needs an HTTP/3 listener, which not every deployment of an app runs. Callers that
172
+ // want the cable to fall back to WebSockets rather than fail closed should check this first.
173
+ export function supported() {
174
+ return typeof WebTransport !== "undefined"
175
+ }
176
+
177
+ // Point an Action Cable module at WebTransport. Pass the ActionCable module itself — the copy whose
178
+ // consumer you are about to create, since each bundled copy has its own adapters object.
179
+ //
180
+ // import * as ActionCable from "@rails/actioncable"
181
+ // import { installWebTransportCable } from "quicsilver/action_cable"
182
+ //
183
+ // installWebTransportCable({ ActionCable })
184
+ export function installWebTransportCable({ ActionCable, force = false } = {}) {
185
+ if (!ActionCable) throw new Error("installWebTransportCable needs the ActionCable module")
186
+ if (!supported() && !force) return false
187
+
188
+ ActionCable.adapters.WebSocket = WebTransportSocket
189
+ return true
190
+ }
191
+
192
+ // Install the socket globally, for bundles that capture their transport at module-eval time.
193
+ //
194
+ // Turbo inlines its own copy of Action Cable, and that copy reads the adapter once when it is
195
+ // evaluated: `WebSocket: typeof WebSocket !== "undefined" ? WebSocket : undefined`. Evaluating Turbo
196
+ // also defines turbo-cable-stream-source, which synchronously upgrades the elements already in the
197
+ // parsed DOM and opens a consumer — so by the time any later module can call setConsumer, the
198
+ // WebSocket is already connected and subscribed. Patching the module's adapters afterwards is too
199
+ // late, and importing Turbo to reach it is what makes it too late.
200
+ //
201
+ // Swapping the global first lets Turbo's copy capture this class as its own adapter. The native
202
+ // class is restored immediately: Turbo has already taken its reference, and nothing else should
203
+ // inherit a WebTransport socket by surprise.
204
+ //
205
+ // Import this BEFORE "@hotwired/turbo-rails", and before anything else that reaches Turbo:
206
+ //
207
+ // import "quicsilver/cable_boot"
208
+ // import "@hotwired/turbo-rails"
209
+ export function captureGlobalWebSocket() {
210
+ if (!supported()) return false
211
+
212
+ const native = globalThis.WebSocket
213
+ globalThis.WebSocket = WebTransportSocket
214
+
215
+ return () => { globalThis.WebSocket = native }
216
+ }
@@ -0,0 +1,23 @@
1
+ // Side-effecting entry point: makes WebTransport the transport Turbo's inlined Action Cable copy
2
+ // captures. See captureGlobalWebSocket for why this has to happen before Turbo is evaluated.
3
+ //
4
+ // import "quicsilver/cable_boot" // must come first
5
+ // import "@hotwired/turbo-rails"
6
+ //
7
+ // The cable follows the page. The tags render only when the page itself arrived over HTTP/3, so a
8
+ // page served over TCP keeps Action Cable's own WebSocket. If WebTransport then fails to open,
9
+ // the socket falls back to WebSocket for the rest of the page.
10
+
11
+ import { captureGlobalWebSocket } from "quicsilver/action_cable"
12
+
13
+ // Rendered by quicsilver_meta_tags, or the cable helpers on their own, only on pages served over
14
+ // HTTP/3. The certificate hash alone is not a signal: a page can carry it for WebTransport endpoints
15
+ // without asking for its cable to move.
16
+ const cableOverWebTransport = document.querySelector(
17
+ 'meta[name="quicsilver-cable"], meta[name="quicsilver-cable-cookies"], meta[name="quicsilver-cable-credential"]'
18
+ )
19
+
20
+ if (cableOverWebTransport) {
21
+ const restore = captureGlobalWebSocket()
22
+ if (restore) queueMicrotask(restore)
23
+ }
@@ -0,0 +1,120 @@
1
+ const textEncoder = new TextEncoder()
2
+ const textDecoder = new TextDecoder()
3
+
4
+ export async function connect(url, options = {}) {
5
+ const transport = new WebTransport(url, {
6
+ ...certificateOptionsFromMeta(),
7
+ ...options,
8
+ })
9
+ await transport.ready
10
+ return transport
11
+ }
12
+
13
+ function certificateOptionsFromMeta() {
14
+ const meta = document.querySelector('meta[name="quicsilver-webtransport-certificate-sha256"]')
15
+ if (!meta) return {}
16
+
17
+ return {
18
+ serverCertificateHashes: [{
19
+ algorithm: "sha-256",
20
+ value: Uint8Array.from(atob(meta.content), character => character.charCodeAt(0)),
21
+ }],
22
+ }
23
+ }
24
+
25
+ export async function writeFrame(writer, payload) {
26
+ const bytes = toBytes(payload)
27
+ const frame = new Uint8Array(4 + bytes.length)
28
+ new DataView(frame.buffer).setUint32(0, bytes.length)
29
+ frame.set(bytes, 4)
30
+ await writer.write(frame)
31
+ }
32
+
33
+ export async function* readFrames(reader) {
34
+ let buffer = new Uint8Array(0)
35
+
36
+ while (true) {
37
+ const { value, done } = await reader.read()
38
+ if (done) return
39
+ if (!value || value.length === 0) continue
40
+
41
+ buffer = concat(buffer, value)
42
+
43
+ while (buffer.length >= 4) {
44
+ const length = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength).getUint32(0)
45
+ if (buffer.length < 4 + length) break
46
+
47
+ yield buffer.slice(4, 4 + length)
48
+ buffer = buffer.slice(4 + length)
49
+ }
50
+ }
51
+ }
52
+
53
+ export async function writeJson(writer, value) {
54
+ await writeFrame(writer, JSON.stringify(value))
55
+ }
56
+
57
+ export async function* readJson(reader) {
58
+ for await (const frame of readFrames(reader)) {
59
+ yield JSON.parse(textDecoder.decode(frame))
60
+ }
61
+ }
62
+
63
+ export async function rpc(transport, request) {
64
+ const stream = await transport.createBidirectionalStream()
65
+ const writer = stream.writable.getWriter()
66
+ const reader = stream.readable.getReader()
67
+
68
+ await writeJson(writer, request)
69
+ await writer.close()
70
+
71
+ for await (const response of readJson(reader)) {
72
+ return response
73
+ }
74
+
75
+ return null
76
+ }
77
+
78
+ export async function* serverStream(transport, request) {
79
+ const stream = await transport.createBidirectionalStream()
80
+ const writer = stream.writable.getWriter()
81
+ const reader = stream.readable.getReader()
82
+
83
+ await writeJson(writer, request)
84
+ await writer.close()
85
+
86
+ yield* readJson(reader)
87
+ }
88
+
89
+ export async function openMessageStream(transport) {
90
+ const stream = await transport.createBidirectionalStream()
91
+ const writer = stream.writable.getWriter()
92
+ const reader = stream.readable.getReader()
93
+
94
+ return {
95
+ send(message) {
96
+ return writeJson(writer, message)
97
+ },
98
+
99
+ responses() {
100
+ return readJson(reader)
101
+ },
102
+
103
+ close() {
104
+ return writer.close()
105
+ },
106
+ }
107
+ }
108
+
109
+ function toBytes(payload) {
110
+ if (payload instanceof Uint8Array) return payload
111
+ if (payload instanceof ArrayBuffer) return new Uint8Array(payload)
112
+ return textEncoder.encode(String(payload))
113
+ }
114
+
115
+ function concat(left, right) {
116
+ const bytes = new Uint8Array(left.length + right.length)
117
+ bytes.set(left)
118
+ bytes.set(right, left.length)
119
+ return bytes
120
+ }
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Pins for the engine's app/javascript, merged into the host app's importmap.
4
+ pin "quicsilver/action_cable", to: "quicsilver/action_cable.js"
5
+ pin "quicsilver/cable_boot", to: "quicsilver/cable_boot.js"
6
+ pin "quicsilver/web_transport", to: "quicsilver/web_transport.js"