cybertrain-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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e226020ff7b8510d5c3363fce5e572d96078f3e1d23186756e6a49722f261267
4
+ data.tar.gz: beae22b8b91509e4c8502521798f2de737497d809139e446a31a45d8e11cae54
5
+ SHA512:
6
+ metadata.gz: 3efb1e902e9bc9861345faf3d1b2ec96e4665154d503bca39bbf79172cc97708338d70ae84f637103056cfbe2682fe397f4199b6a398df563de9b88154c122b3
7
+ data.tar.gz: ef6a3fb038121c65d1074339824c9c447cf31125ce1ad7c3bcc9f67971900bd16cd0883b36ded50dab48ddcaff796c6d94eb5444faa9e0630ec97523065c0a76
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Saeki Mototsune
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,171 @@
1
+ # cybertrain-rails
2
+
3
+ Run part of a Rails application's requests in a cybertrain application.
4
+
5
+ cybertrain compiles an application into one native binary with its own HTTP
6
+ server: there is no Rack interface and nothing to load into a Ruby process.
7
+ So this gem keeps the cybertrain application beside the Rails one, in
8
+ `app/ctrain`, and lets `config/routes.rb` say which requests go there. A
9
+ route declared with `cybertrain` points at a small reverse proxy, which
10
+ forwards the request to the cybertrain server over loopback HTTP and streams
11
+ the response back. Everything else (sessions, assets, the rest of the
12
+ routes) stays Rails'.
13
+
14
+ ```
15
+ browser ──> Rails (Puma) ──┬── Rails controllers
16
+ └── cybertrain routes ──HTTP──> app/ctrain binary (127.0.0.1:3100)
17
+ ```
18
+
19
+ Status: first version (0.1.0), not released to rubygems.org. Use it from
20
+ GitHub: `gem "cybertrain-rails", github: "saeki-mototsune/cybertrain-rails"`.
21
+ The design record is D118 in [CyberTrain's docs/design.md](https://github.com/saeki-mototsune/CyberTrain/blob/main/docs/design.md).
22
+
23
+ ## Setup
24
+
25
+ Requirements: Rails 7.1 or newer, and the `cybertrain` command (`gem install
26
+ cybertrain`; the first command that needs Spinel installs it, `cybertrain
27
+ doctor` checks the toolchain).
28
+
29
+ ```ruby
30
+ # Gemfile
31
+ gem "cybertrain-rails", github: "saeki-mototsune/cybertrain-rails"
32
+ ```
33
+
34
+ ```sh
35
+ bundle install
36
+ bin/rails generate cybertrain:install # cybertrain new ctrain, in app/
37
+ ```
38
+
39
+ The generator creates the cybertrain application in `app/ctrain`, writes
40
+ `config/initializers/cybertrain.rb` and adds a commented-out route. Work in
41
+ `app/ctrain` with the cybertrain CLI as usual:
42
+
43
+ ```sh
44
+ cd app/ctrain
45
+ cybertrain generate scaffold article title:string body:text
46
+ cybertrain db migrate
47
+ ```
48
+
49
+ ## Routes
50
+
51
+ ```ruby
52
+ # config/routes.rb
53
+ Rails.application.routes.draw do
54
+ resources :users # Rails
55
+
56
+ # /articles and everything under it, every HTTP method
57
+ cybertrain "/articles"
58
+
59
+ # only these routes; Rails matches them, cybertrain answers
60
+ cybertrain do
61
+ get "/feed/:id", as: :feed
62
+ post "/ingest"
63
+ all "/reports" # the path and everything under it
64
+ end
65
+
66
+ # an API whose cybertrain routes are written without the prefix
67
+ cybertrain "/api/v2", strip_prefix: true
68
+ end
69
+ ```
70
+
71
+ Each one is an ordinary Rails route whose endpoint is the proxy, so it shows
72
+ in `bin/rails routes`, works inside `scope` and `constraints`, and has a path
73
+ helper (`articles_path`, `feed_path(3)`).
74
+
75
+ The path is forwarded as Rails received it: `/articles/1` reaches the
76
+ cybertrain application as `/articles/1`, so its `config/routes.rb` uses the
77
+ same paths (`resources :articles`). cybertrain has no mount point, so with
78
+ `strip_prefix: true` the links it writes lack the prefix; use that for APIs,
79
+ not for pages.
80
+
81
+ ## Development
82
+
83
+ `bin/rails server` is all there is to run. The first request to a
84
+ cybertrain route starts `cybertrain server 3100` in `app/ctrain` (the CRuby
85
+ preview answers at once, the compiled binary takes the port when its build
86
+ finishes) and the proxy waits for it, up to `boot_timeout`. The server is
87
+ stopped when Rails exits. `rails console` and rake tasks never start it.
88
+ If a cybertrain server is already listening on the port (you started it
89
+ yourself to watch its output), that one is used.
90
+
91
+ ## Production
92
+
93
+ Build the binary, then run it as a process of its own beside Rails:
94
+
95
+ ```sh
96
+ bin/rails ctrain:build # cybertrain build in app/ctrain -> app/ctrain/dist/ctrain
97
+ bin/rails ctrain:migrate # dist/ctrain migrate
98
+ bin/rails ctrain:server # exec dist/ctrain server on 127.0.0.1:3100
99
+ ```
100
+
101
+ For example in a Procfile:
102
+
103
+ ```
104
+ web: bin/rails server
105
+ ctrain: bin/rails ctrain:server
106
+ ```
107
+
108
+ `config.cybertrain.build_on_precompile = true` makes `assets:precompile`
109
+ build the binary too (the machine that precompiles then needs Spinel).
110
+ The binary reads its own settings from the environment
111
+ (`CYBERTRAIN_SECRET_KEY_BASE` and the rest, see cybertrain's configuration
112
+ guide); `config.cybertrain.env` adds variables to what `ctrain:server` and a
113
+ development server get.
114
+
115
+ ## Rake tasks
116
+
117
+ | Task | Runs, in app/ctrain |
118
+ | --- | --- |
119
+ | `ctrain:build` | `cybertrain build` |
120
+ | `ctrain:server` | `dist/NAME server` (`cybertrain server PORT` in development), in the foreground |
121
+ | `ctrain:migrate` | `dist/NAME migrate`, or `cybertrain db migrate` in development or before a build |
122
+ | `ctrain:test` | `cybertrain test` |
123
+
124
+ ## Configuration
125
+
126
+ In `config/initializers/cybertrain.rb` or `config/application.rb`:
127
+
128
+ | Setting | Default | |
129
+ | --- | --- | --- |
130
+ | `config.cybertrain.root` | `"app/ctrain"` | the cybertrain application |
131
+ | `config.cybertrain.host` | `"127.0.0.1"` | where its server listens |
132
+ | `config.cybertrain.port` | `CTRAIN_PORT`, else `3100` | |
133
+ | `config.cybertrain.spawn` | development only | start the server on the first request that needs it |
134
+ | `config.cybertrain.command` | see Rake tasks | the server command, as an Array |
135
+ | `config.cybertrain.cli` | `CTRAIN_CLI`, else `"cybertrain"` | the cybertrain executable |
136
+ | `config.cybertrain.env` | `{}` | extra environment for the server |
137
+ | `config.cybertrain.allowed_hosts` | the plain names in `config.hosts` | passed as `CYBERTRAIN_ALLOWED_HOSTS` |
138
+ | `config.cybertrain.preserve_host` | `true` | send the browser's `Host` upstream (else `host:port`) |
139
+ | `config.cybertrain.open_timeout` / `read_timeout` / `boot_timeout` | `5` / `60` / `120` | seconds |
140
+ | `config.cybertrain.build_on_precompile` | `false` | `assets:precompile` runs `ctrain:build` |
141
+
142
+ ## What the proxy does
143
+
144
+ - Sends the method, path, query string, headers and body; drops hop-by-hop
145
+ headers; adds `X-Forwarded-For`, `-Host`, `-Proto` and Rails' request id as
146
+ `X-Request-Id`. The server it starts gets `CYBERTRAIN_TRUSTED_PROXY=1`, so
147
+ `request.client_ip` is the browser's address.
148
+ - Passes the response through unchanged, compressed bodies and every
149
+ `Set-Cookie` included, and streams it chunk by chunk, so Server-Sent
150
+ Events and Turbo Streams over SSE work.
151
+ - Answers 502 when nothing listens on the port, 503 when a server it started
152
+ does not answer within `boot_timeout`.
153
+ - Keeps Zeitwerk out of `app/ctrain`: its Ruby is cybertrain's, not Rails'.
154
+
155
+ ## Not in this version
156
+
157
+ - WebSocket (the proxy does not hijack the connection); use SSE, or route
158
+ `/cable`-style paths to the cybertrain port in your front proxy.
159
+ - Sharing the Rails session or the signed-in user with cybertrain: the two
160
+ applications have their own cookies and secrets.
161
+ - Several cybertrain applications in one Rails application.
162
+
163
+ ## Tests
164
+
165
+ ```sh
166
+ bundle install
167
+ bundle exec rake test
168
+ ```
169
+
170
+ They need `railties`, `actionpack`, `rack` and `webrick`, and use a stand-in
171
+ server, not Spinel.
@@ -0,0 +1,150 @@
1
+ require "pathname"
2
+
3
+ module Cybertrain
4
+ module Rails
5
+ # Settings, read from `config.cybertrain` in config/application.rb or an
6
+ # initializer:
7
+ #
8
+ # config.cybertrain.root = "app/ctrain" # the cybertrain application
9
+ # config.cybertrain.port = 3100 # where its server listens
10
+ # config.cybertrain.spawn = true # start it on the first request
11
+ class Configuration
12
+ # The cybertrain application's directory, relative to Rails.root
13
+ # unless absolute. `cybertrain new ctrain` run in app/ makes it.
14
+ attr_accessor :root
15
+ # Where the cybertrain server listens. The proxy connects here, and a
16
+ # server this gem starts is told to listen here.
17
+ attr_accessor :host, :port
18
+ # Whether the proxy starts the server when nothing answers on
19
+ # host:port (development by default). In production run it as a
20
+ # process of its own: `bin/rails ctrain:server`.
21
+ attr_accessor :spawn
22
+ # The command that starts the server, as an Array, or nil for the
23
+ # default: `cybertrain server PORT` in development (the CRuby preview,
24
+ # then the compiled binary), `dist/NAME server` elsewhere.
25
+ attr_accessor :command
26
+ # The `cybertrain` executable the rake tasks and the default
27
+ # development command run.
28
+ attr_accessor :cli
29
+ # Extra environment variables for a server this gem starts.
30
+ attr_accessor :env
31
+ # Host names the server accepts besides localhost (cybertrain's
32
+ # CYBERTRAIN_ALLOWED_HOSTS). nil: the plain host names in
33
+ # Rails' config.hosts.
34
+ attr_accessor :allowed_hosts
35
+ # Seconds the proxy waits to connect, for a response, and for a server
36
+ # it started to answer.
37
+ attr_accessor :open_timeout, :read_timeout, :boot_timeout
38
+ # Send the browser's Host header upstream (true), or host:port (false).
39
+ # cybertrain builds absolute URLs from it.
40
+ attr_accessor :preserve_host
41
+ # Run ctrain:build before assets:precompile, so a deploy that
42
+ # precompiles assets also builds the binary. Needs Spinel on the
43
+ # machine that builds.
44
+ attr_accessor :build_on_precompile
45
+
46
+ def initialize
47
+ @root = "app/ctrain"
48
+ @host = "127.0.0.1"
49
+ @port = Integer(ENV.fetch("CTRAIN_PORT", "3100"))
50
+ @spawn = nil
51
+ @command = nil
52
+ @cli = ENV.fetch("CTRAIN_CLI", "cybertrain")
53
+ @env = {}
54
+ @allowed_hosts = nil
55
+ @open_timeout = 5
56
+ @read_timeout = 60
57
+ @boot_timeout = 120
58
+ @preserve_host = true
59
+ @build_on_precompile = false
60
+ end
61
+
62
+ # The application directory as an absolute Pathname.
63
+ def root_path
64
+ path = Pathname.new(root.to_s)
65
+ return path if path.absolute?
66
+
67
+ base = defined?(::Rails.root) && ::Rails.root ? ::Rails.root : Pathname.new(Dir.pwd)
68
+ base.join(path)
69
+ end
70
+
71
+ # The [package] name in the application's spin.toml: the binary's
72
+ # name under dist/.
73
+ def app_name
74
+ toml = root_path.join("spin.toml")
75
+ raise Error, "#{toml} is missing: is #{root} a cybertrain application?" unless toml.file?
76
+
77
+ in_package = false
78
+ toml.each_line do |line|
79
+ stripped = line.strip
80
+ if stripped.start_with?("[")
81
+ in_package = stripped == "[package]"
82
+ elsif in_package && (m = stripped.match(/\Aname\s*=\s*"([^"]+)"/))
83
+ return m[1]
84
+ end
85
+ end
86
+ raise Error, "#{toml} has no [package] name"
87
+ end
88
+
89
+ def binary_path
90
+ root_path.join("dist", app_name)
91
+ end
92
+
93
+ def development?
94
+ rails_env == "development"
95
+ end
96
+
97
+ def spawn?
98
+ spawn.nil? ? development? : spawn
99
+ end
100
+
101
+ # The command a server this gem (or ctrain:server) starts runs, in
102
+ # root_path.
103
+ def server_command
104
+ return Array(command) if command
105
+ return [cli, "server", port.to_s] if development?
106
+
107
+ [binary_path.to_s, "server"]
108
+ end
109
+
110
+ # The directory server_command runs in: the application in
111
+ # development, dist/ for the built binary (it finds public/, storage/
112
+ # and tmp/ beside it, as `cd dist && ./NAME` does).
113
+ def server_dir
114
+ return root_path if command || development?
115
+
116
+ root_path.join("dist")
117
+ end
118
+
119
+ # The environment of that command: the port and address, the host
120
+ # names, and trusting this process's X-Forwarded-For.
121
+ def server_env
122
+ result = {
123
+ "PORT" => port.to_s,
124
+ "CYBERTRAIN_HOST" => host.to_s,
125
+ "CYBERTRAIN_TRUSTED_PROXY" => "1"
126
+ }
127
+ hosts = resolved_allowed_hosts
128
+ result["CYBERTRAIN_ALLOWED_HOSTS"] = hosts.join(",") unless hosts.empty?
129
+ result.merge(env.to_h { |k, v| [k.to_s, v.to_s] })
130
+ end
131
+
132
+ def resolved_allowed_hosts
133
+ return Array(allowed_hosts).map(&:to_s) if allowed_hosts
134
+
135
+ rails_hosts = defined?(::Rails.application) && ::Rails.application ? ::Rails.application.config.hosts : []
136
+ # cybertrain takes exact names only: skip regexps, IP ranges and
137
+ # ".example.com" (subdomain) entries.
138
+ Array(rails_hosts).grep(String).reject { |h| h.start_with?(".") || h.empty? }.uniq
139
+ end
140
+
141
+ def rails_env
142
+ if defined?(::Rails.env) && ::Rails.respond_to?(:env)
143
+ ::Rails.env.to_s
144
+ else
145
+ ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
146
+ end
147
+ end
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,221 @@
1
+ require "net/http"
2
+ require "rack"
3
+
4
+ module Cybertrain
5
+ module Rails
6
+ # The Rack endpoint a `cybertrain` route points at: forwards the request
7
+ # to the cybertrain server over HTTP and streams its response back.
8
+ #
9
+ # The path is sent as Rails received it (PATH_INFO), so the cybertrain
10
+ # application's routes are written with the same paths as the Rails
11
+ # routes that lead to them. `strip_prefix:` removes a leading prefix
12
+ # first; cybertrain has no mount point, so the links it writes then lack
13
+ # the prefix (use it for APIs, not pages).
14
+ class Proxy
15
+ # Hop-by-hop headers (RFC 9110 7.6.1), never forwarded either way.
16
+ HOP_BY_HOP = %w[
17
+ connection keep-alive proxy-authenticate proxy-authorization proxy-connection
18
+ te trailer transfer-encoding upgrade
19
+ ].freeze
20
+
21
+ METHODS = {
22
+ "GET" => Net::HTTP::Get, "HEAD" => Net::HTTP::Head, "POST" => Net::HTTP::Post,
23
+ "PUT" => Net::HTTP::Put, "PATCH" => Net::HTTP::Patch, "DELETE" => Net::HTTP::Delete,
24
+ "OPTIONS" => Net::HTTP::Options
25
+ }.freeze
26
+
27
+ # How many body chunks may wait between the upstream reader and the
28
+ # Rack server writing them to the client.
29
+ QUEUE_DEPTH = 16
30
+
31
+ attr_reader :strip_prefix
32
+
33
+ def initialize(config:, supervisor: nil, strip_prefix: nil)
34
+ @config = config
35
+ @supervisor = supervisor
36
+ @strip_prefix = normalize_prefix(strip_prefix)
37
+ end
38
+
39
+ def call(env)
40
+ request_class = METHODS[env["REQUEST_METHOD"]]
41
+ return error(405, "cybertrain-rails does not forward #{env["REQUEST_METHOD"]}") unless request_class
42
+
43
+ begin
44
+ @supervisor&.ensure_running
45
+ rescue Error => e
46
+ return error(503, e.message)
47
+ end
48
+
49
+ forward(env, request_class)
50
+ end
51
+
52
+ # The path the cybertrain server receives, with the query string.
53
+ def upstream_path(env)
54
+ path = env["PATH_INFO"].to_s
55
+ path = "/" if path.empty?
56
+ if @strip_prefix && (path == @strip_prefix || path.start_with?("#{@strip_prefix}/"))
57
+ path = path.delete_prefix(@strip_prefix)
58
+ path = "/#{path}" unless path.start_with?("/")
59
+ end
60
+ query = env["QUERY_STRING"].to_s
61
+ query.empty? ? path : "#{path}?#{query}"
62
+ end
63
+
64
+ # The request headers sent upstream, as {name => value}.
65
+ def upstream_headers(env)
66
+ headers = {}
67
+ env.each do |key, value|
68
+ next unless key.start_with?("HTTP_") && value.is_a?(String)
69
+ next if key == "HTTP_VERSION"
70
+
71
+ name = key.delete_prefix("HTTP_").downcase.tr("_", "-")
72
+ headers[name] = value
73
+ end
74
+ headers["content-type"] = env["CONTENT_TYPE"] if present?(env["CONTENT_TYPE"])
75
+ headers["content-length"] = env["CONTENT_LENGTH"] if present?(env["CONTENT_LENGTH"])
76
+ drop_hop_by_hop(headers)
77
+
78
+ original_host = headers["host"] || "#{env["SERVER_NAME"]}:#{env["SERVER_PORT"]}"
79
+ headers["host"] = @config.preserve_host ? original_host : "#{@config.host}:#{@config.port}"
80
+ headers["x-forwarded-host"] ||= original_host
81
+ headers["x-forwarded-proto"] ||= env["rack.url_scheme"].to_s
82
+ client = env["REMOTE_ADDR"]
83
+ if present?(client)
84
+ previous = headers["x-forwarded-for"]
85
+ headers["x-forwarded-for"] = present?(previous) ? "#{previous}, #{client}" : client
86
+ end
87
+ request_id = env["action_dispatch.request_id"]
88
+ headers["x-request-id"] ||= request_id if present?(request_id)
89
+ headers
90
+ end
91
+
92
+ private
93
+
94
+ def forward(env, request_class)
95
+ headers = upstream_headers(env)
96
+ # With no Accept-Encoding of its own, Net::HTTP asks for gzip and
97
+ # inflates the body itself, while the client would still be sent
98
+ # the upstream's Content-Encoding: pass the client's choice through.
99
+ headers["accept-encoding"] ||= "identity"
100
+ request = request_class.new(upstream_path(env), "accept-encoding" => headers["accept-encoding"])
101
+ headers.each { |name, value| request[name] = value }
102
+ attach_body(request, env)
103
+
104
+ queue = SizedQueue.new(QUEUE_DEPTH)
105
+ thread = Thread.new { run_upstream(request, queue) }
106
+ thread.report_on_exception = false
107
+ kind, value = queue.pop
108
+ case kind
109
+ when :response
110
+ [value.code.to_i, response_headers(value), Body.new(queue, thread)]
111
+ when :error
112
+ thread.join
113
+ error(502, "cybertrain is not answering on #{@config.host}:#{@config.port}: #{value.class}: #{value.message}")
114
+ else
115
+ error(502, "cybertrain closed the connection without a response")
116
+ end
117
+ end
118
+
119
+ def run_upstream(request, queue)
120
+ http = Net::HTTP.new(@config.host, @config.port)
121
+ http.open_timeout = @config.open_timeout
122
+ http.read_timeout = @config.read_timeout
123
+ http.start do
124
+ http.request(request) do |response|
125
+ queue << [:response, response]
126
+ response.read_body { |chunk| queue << [:chunk, chunk] }
127
+ end
128
+ end
129
+ queue << [:done, nil]
130
+ rescue StandardError => e
131
+ queue << [:error, e]
132
+ end
133
+
134
+ def attach_body(request, env)
135
+ return unless request.request_body_permitted?
136
+
137
+ input = env["rack.input"]
138
+ return unless input
139
+
140
+ input.rewind if input.respond_to?(:rewind)
141
+ length = env["CONTENT_LENGTH"]
142
+ if present?(length)
143
+ request.body_stream = input
144
+ else
145
+ body = input.read
146
+ request.body = body if body && !body.empty?
147
+ request["content-length"] = body.to_s.bytesize.to_s if body && !body.empty?
148
+ end
149
+ end
150
+
151
+ def response_headers(response)
152
+ headers = {}
153
+ response.each_capitalized_name do |name|
154
+ key = name.downcase
155
+ next if HOP_BY_HOP.include?(key)
156
+
157
+ values = response.get_fields(name)
158
+ headers[key] = if key == "set-cookie" && Proxy.rack3?
159
+ values
160
+ else
161
+ values.join(key == "set-cookie" ? "\n" : ", ")
162
+ end
163
+ end
164
+ # The body is re-chunked by the Rack server; a length the upstream
165
+ # sent still matches, since the bytes are passed through unchanged.
166
+ headers
167
+ end
168
+
169
+ def drop_hop_by_hop(headers)
170
+ listed = headers["connection"].to_s.split(",").map { |n| n.strip.downcase }
171
+ (HOP_BY_HOP + listed).each { |name| headers.delete(name) }
172
+ end
173
+
174
+ def error(status, message)
175
+ [status, { "content-type" => "text/plain; charset=utf-8" }, ["#{message}\n"]]
176
+ end
177
+
178
+ def present?(value)
179
+ !value.nil? && !value.to_s.empty?
180
+ end
181
+
182
+ def normalize_prefix(prefix)
183
+ return nil if prefix.nil? || prefix == false
184
+
185
+ text = "/#{Routing.trim_slashes(prefix.to_s)}"
186
+ text == "/" ? nil : text
187
+ end
188
+
189
+ def self.rack3?
190
+ Gem::Version.new(Rack.release) >= Gem::Version.new("3")
191
+ end
192
+
193
+ # The response body: chunks the upstream thread reads, handed to the
194
+ # Rack server as they arrive (Server-Sent Events and Turbo Streams
195
+ # flow through). close stops the upstream read when the client goes
196
+ # away first.
197
+ class Body
198
+ def initialize(queue, thread)
199
+ @queue = queue
200
+ @thread = thread
201
+ end
202
+
203
+ def each
204
+ loop do
205
+ kind, value = @queue.pop
206
+ case kind
207
+ when :chunk then yield value
208
+ when :error then raise value
209
+ else break
210
+ end
211
+ end
212
+ end
213
+
214
+ def close
215
+ @thread.kill if @thread.alive?
216
+ @thread.join
217
+ end
218
+ end
219
+ end
220
+ end
221
+ end
@@ -0,0 +1,25 @@
1
+ require "rails/railtie"
2
+
3
+ module Cybertrain
4
+ module Rails
5
+ class Railtie < ::Rails::Railtie
6
+ config.cybertrain = Cybertrain::Rails.config
7
+
8
+ # app/ctrain sits under app/, whose subdirectories Rails autoloads and
9
+ # eager loads; its Ruby is cybertrain's (Spinel's subset, its own
10
+ # constants), never Rails'. Keep Zeitwerk out of it.
11
+ initializer "cybertrain.ignore_application" do
12
+ root = Cybertrain::Rails.config.root_path.to_s
13
+ ::Rails.autoloaders.each { |loader| loader.ignore(root) }
14
+ end
15
+
16
+ rake_tasks do
17
+ load File.expand_path("tasks.rake", __dir__)
18
+ end
19
+
20
+ generators do
21
+ require "generators/cybertrain/install/install_generator"
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,126 @@
1
+ module Cybertrain
2
+ module Rails
3
+ # The `cybertrain` method of config/routes.rb.
4
+ #
5
+ # Rails.application.routes.draw do
6
+ # # /reports and everything under it, every method
7
+ # cybertrain "/reports"
8
+ #
9
+ # # only these routes; Rails matches them, cybertrain answers
10
+ # cybertrain do
11
+ # get "/feed/:id"
12
+ # post "/ingest", as: :ingest
13
+ # end
14
+ #
15
+ # # an API whose cybertrain routes are written without the prefix
16
+ # cybertrain "/api/v2", strip_prefix: true
17
+ # end
18
+ #
19
+ # Each route is an ordinary Rails route whose endpoint is the proxy, so
20
+ # it takes part in `bin/rails routes`, `scope`, `constraints` and the
21
+ # path helpers (`reports_path`) like any other.
22
+ module Routing
23
+ def cybertrain(path = nil, via: :all, strip_prefix: false, as: nil, **options, &block)
24
+ prefix = strip_prefix ? Routing.join_paths(@scope[:path].to_s, path.to_s) : nil
25
+ proxy = Cybertrain::Rails.proxy(strip_prefix: prefix)
26
+
27
+ if block
28
+ dsl = DSL.new(self, proxy)
29
+ if path
30
+ scope(path) { dsl.instance_exec(&block) }
31
+ else
32
+ dsl.instance_exec(&block)
33
+ end
34
+ return
35
+ end
36
+
37
+ raise ArgumentError, "cybertrain needs a path, or a block of routes" if path.nil?
38
+
39
+ normalized = Routing.chomp_slashes(path.to_s)
40
+ as = cybertrain_route_name(normalized) if as.nil?
41
+ if normalized.empty?
42
+ match "/", to: proxy, via: via, format: false, as: as, **options
43
+ match "*ctrain_path", to: proxy, via: via, format: false, as: nil, **options
44
+ else
45
+ match normalized, to: proxy, via: via, format: false, as: as, **options
46
+ match "#{normalized}/*ctrain_path", to: proxy, via: via, format: false, as: nil, **options
47
+ end
48
+ end
49
+
50
+ private
51
+
52
+ # Rails names a route to a Rack endpoint only when told to: name the
53
+ # prefix route after its path ("/admin/reports" -> admin_reports) as
54
+ # Rails does for `get "admin/reports"`, unless the path has dynamic
55
+ # segments or the name is taken.
56
+ def cybertrain_route_name(path)
57
+ segments = path.split("/").reject(&:empty?)
58
+ return nil if segments.empty?
59
+
60
+ candidate = segments.join("_").tr("-.", "__")
61
+ return nil unless candidate.match?(/\A[a-z_][a-z0-9_]*\z/i)
62
+
63
+ full = respond_to?(:name_for_action, true) ? name_for_action(candidate, nil) : candidate
64
+ return nil if full.nil? || @set.named_routes.key?(full)
65
+
66
+ candidate
67
+ rescue ArgumentError, NoMethodError
68
+ nil
69
+ end
70
+
71
+ public
72
+
73
+ # path without its trailing slashes ("/a//" -> "/a", "///" -> "").
74
+ # A loop, not /\/+\z/, which backtracks quadratically on many slashes.
75
+ def self.chomp_slashes(path)
76
+ text = path.dup
77
+ text.chop! while text.end_with?("/")
78
+ text
79
+ end
80
+
81
+ # path without its leading and trailing slashes.
82
+ def self.trim_slashes(path)
83
+ text = chomp_slashes(path)
84
+ text = text[1..] while text.start_with?("/")
85
+ text
86
+ end
87
+
88
+ def self.join_paths(scope_path, path)
89
+ "/#{[scope_path, path].join("/").split("/").reject(&:empty?).join("/")}"
90
+ end
91
+
92
+ # The block form: each verb draws a route to the proxy.
93
+ class DSL
94
+ def initialize(mapper, proxy)
95
+ @mapper = mapper
96
+ @proxy = proxy
97
+ end
98
+
99
+ %i[get post put patch delete options].each do |verb|
100
+ define_method(verb) do |path, **options|
101
+ @mapper.match(path, to: @proxy, via: verb, format: false, **options)
102
+ end
103
+ end
104
+
105
+ def match(path, via: :all, **options)
106
+ @mapper.match(path, to: @proxy, via: via, format: false, **options)
107
+ end
108
+
109
+ # Everything under path (path itself included).
110
+ def all(path, **options)
111
+ normalized = Routing.chomp_slashes(path.to_s)
112
+ @mapper.match(normalized.empty? ? "/" : normalized, to: @proxy, via: :all, format: false, **options)
113
+ @mapper.match("#{normalized}/*ctrain_path", to: @proxy, via: :all, format: false)
114
+ end
115
+
116
+ def scope(*args, &block)
117
+ @mapper.scope(*args) { instance_exec(&block) }
118
+ end
119
+
120
+ def constraints(*args, &block)
121
+ @mapper.constraints(*args) { instance_exec(&block) }
122
+ end
123
+ end
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,132 @@
1
+ require "socket"
2
+
3
+ module Cybertrain
4
+ module Rails
5
+ # Starts the cybertrain server when the proxy finds nothing listening on
6
+ # the configured port, and stops it when this process exits. Used in
7
+ # development (Configuration#spawn?); in production the server is a
8
+ # process of its own (`bin/rails ctrain:server`).
9
+ #
10
+ # The server is started on the first request that needs it, not when
11
+ # Rails boots, so `rails console`, rake tasks and the asset pipeline do
12
+ # not start one. Several Rails processes (Puma workers) may race to
13
+ # start it: the loser's server fails to bind and exits, and the loser
14
+ # then waits for the winner's port like anyone else.
15
+ class Supervisor
16
+ attr_reader :pid
17
+
18
+ def initialize(config, logger: nil)
19
+ @config = config
20
+ @logger = logger
21
+ @mutex = Mutex.new
22
+ @pid = nil
23
+ @at_exit = false
24
+ end
25
+
26
+ # Returns once something answers on host:port, starting the server
27
+ # first when nothing does and spawning is on. Raises Unavailable when
28
+ # it does not answer within boot_timeout.
29
+ def ensure_running
30
+ return if reachable?
31
+ return unless @config.spawn?
32
+
33
+ @mutex.synchronize do
34
+ return if reachable?
35
+
36
+ start unless alive?
37
+ wait_until_reachable
38
+ end
39
+ end
40
+
41
+ def reachable?
42
+ Socket.tcp(@config.host, @config.port, connect_timeout: 0.5).close
43
+ true
44
+ rescue SystemCallError, SocketError, IOError
45
+ false
46
+ end
47
+
48
+ def alive?
49
+ return false unless @pid
50
+
51
+ Process.waitpid(@pid, Process::WNOHANG).nil?
52
+ rescue Errno::ECHILD
53
+ false
54
+ end
55
+
56
+ def start
57
+ root = @config.root_path
58
+ raise Error, "#{root} is missing: create it with `bin/rails generate cybertrain:install`" unless root.directory?
59
+
60
+ command = @config.server_command
61
+ log("starting #{command.join(" ")} in #{@config.server_dir} (port #{@config.port})")
62
+ # A process group of its own, so stop reaches what it starts (the
63
+ # development server runs the preview and the compiled binary as
64
+ # children).
65
+ @pid = Process.spawn(@config.server_env, *command, chdir: @config.server_dir.to_s, pgroup: true)
66
+ install_at_exit
67
+ @pid
68
+ end
69
+
70
+ def stop(timeout: 5)
71
+ pid = @pid
72
+ return unless pid
73
+
74
+ @pid = nil
75
+ signal_group("TERM", pid)
76
+ deadline = monotonic + timeout
77
+ while monotonic < deadline
78
+ return if Process.waitpid(pid, Process::WNOHANG)
79
+
80
+ sleep 0.05
81
+ end
82
+ signal_group("KILL", pid)
83
+ Process.waitpid(pid)
84
+ rescue Errno::ECHILD, Errno::ESRCH
85
+ nil
86
+ end
87
+
88
+ private
89
+
90
+ def wait_until_reachable
91
+ deadline = monotonic + @config.boot_timeout
92
+ until reachable?
93
+ if monotonic > deadline
94
+ raise Unavailable, "cybertrain did not answer on #{@config.host}:#{@config.port} " \
95
+ "within #{@config.boot_timeout}s"
96
+ end
97
+ sleep 0.1
98
+ end
99
+ end
100
+
101
+ def signal_group(signal, pid)
102
+ Process.kill(signal, -pid)
103
+ rescue Errno::ESRCH, Errno::EPERM
104
+ begin
105
+ Process.kill(signal, pid)
106
+ rescue Errno::ESRCH
107
+ nil
108
+ end
109
+ end
110
+
111
+ def install_at_exit
112
+ return if @at_exit
113
+
114
+ @at_exit = true
115
+ owner = Process.pid
116
+ at_exit { stop if Process.pid == owner }
117
+ end
118
+
119
+ def log(message)
120
+ if @logger
121
+ @logger.info("[cybertrain] #{message}")
122
+ else
123
+ warn "[cybertrain] #{message}"
124
+ end
125
+ end
126
+
127
+ def monotonic
128
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
129
+ end
130
+ end
131
+ end
132
+ end
@@ -0,0 +1,35 @@
1
+ # Rake tasks of cybertrain-rails. Each runs in the cybertrain application's
2
+ # directory (config.cybertrain.root, app/ctrain by default).
3
+ require "cybertrain/rails/tasks"
4
+
5
+ namespace :ctrain do
6
+ desc "Build the cybertrain application into a native binary (cybertrain build)"
7
+ task build: :environment do
8
+ Cybertrain::Rails::Tasks.cli("build")
9
+ end
10
+
11
+ desc "Run the cybertrain server in the foreground (dist binary; cybertrain server in development)"
12
+ task server: :environment do
13
+ Cybertrain::Rails::Tasks.server
14
+ end
15
+
16
+ desc "Apply the cybertrain application's pending migrations"
17
+ task migrate: :environment do
18
+ Cybertrain::Rails::Tasks.migrate
19
+ end
20
+
21
+ desc "Run the cybertrain application's tests (cybertrain test)"
22
+ task test: :environment do
23
+ Cybertrain::Rails::Tasks.cli("test")
24
+ end
25
+
26
+ # assets:precompile runs this; it builds only when
27
+ # config.cybertrain.build_on_precompile is true.
28
+ task build_on_precompile: :environment do
29
+ Rake::Task["ctrain:build"].invoke if Cybertrain::Rails.config.build_on_precompile
30
+ end
31
+ end
32
+
33
+ # Declared as a prerequisite whether or not the asset pipeline's railtie
34
+ # has defined the task yet (railties load their tasks in any order).
35
+ task "assets:precompile" => "ctrain:build_on_precompile"
@@ -0,0 +1,54 @@
1
+ module Cybertrain
2
+ module Rails
3
+ # What the ctrain:* rake tasks run.
4
+ module Tasks
5
+ module_function
6
+
7
+ def config
8
+ Cybertrain::Rails.config
9
+ end
10
+
11
+ # Runs the cybertrain CLI with args in the application's directory;
12
+ # aborts the rake run when it fails.
13
+ def cli(*args)
14
+ run([config.cli, *args])
15
+ end
16
+
17
+ def server
18
+ require_root
19
+ command = config.server_command
20
+ if !config.development? && !config.command && !File.executable?(command.first)
21
+ abort "#{command.first} is missing: run bin/rails ctrain:build first"
22
+ end
23
+ dir = config.server_dir
24
+ puts "[cybertrain] #{command.join(" ")} in #{dir} (port #{config.port})"
25
+ Kernel.exec(config.server_env, *command, chdir: dir.to_s)
26
+ end
27
+
28
+ def migrate
29
+ if config.development? || !File.executable?(config.binary_path.to_s)
30
+ cli("db", "migrate")
31
+ else
32
+ run([config.binary_path.to_s, "migrate"], env: config.server_env, dir: config.server_dir)
33
+ end
34
+ end
35
+
36
+ def run(command, env: {}, dir: nil)
37
+ dir ||= require_root
38
+ puts "[cybertrain] #{command.join(" ")} in #{dir}"
39
+ ok = system(env, *command, chdir: dir.to_s)
40
+ return if ok
41
+
42
+ status = ok.nil? ? "could not be started (is #{command.first} installed?)" : "failed"
43
+ abort "[cybertrain] #{command.first} #{status}"
44
+ end
45
+
46
+ def require_root
47
+ root = config.root_path
48
+ return root if root.directory?
49
+
50
+ abort "#{root} is missing: create it with `bin/rails generate cybertrain:install`"
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,5 @@
1
+ module Cybertrain
2
+ module Rails
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,56 @@
1
+ require "cybertrain/rails/version"
2
+ require "cybertrain/rails/configuration"
3
+ require "cybertrain/rails/supervisor"
4
+ require "cybertrain/rails/proxy"
5
+ require "cybertrain/rails/routing"
6
+
7
+ module Cybertrain
8
+ # Runs part of a Rails application's requests in a cybertrain application
9
+ # (app/ctrain by default). See README.md.
10
+ module Rails
11
+ class Error < StandardError; end
12
+ # The server did not answer in time.
13
+ class Unavailable < Error; end
14
+
15
+ class << self
16
+ attr_writer :config
17
+
18
+ def config
19
+ @config ||= Configuration.new
20
+ end
21
+
22
+ def configure
23
+ yield config
24
+ end
25
+
26
+ # The one supervisor of this process: every proxy shares it, so one
27
+ # server is started however many routes lead to it.
28
+ def supervisor
29
+ @supervisor ||= Supervisor.new(config, logger: logger)
30
+ end
31
+
32
+ def proxy(strip_prefix: nil)
33
+ Proxy.new(config: config, supervisor: supervisor, strip_prefix: strip_prefix)
34
+ end
35
+
36
+ # Forget the configuration and stop a server this process started
37
+ # (tests).
38
+ def reset!
39
+ @supervisor&.stop
40
+ @supervisor = nil
41
+ @config = nil
42
+ end
43
+
44
+ private
45
+
46
+ def logger
47
+ ::Rails.logger if defined?(::Rails.logger)
48
+ end
49
+ end
50
+ end
51
+ end
52
+
53
+ require "action_dispatch"
54
+ ActionDispatch::Routing::Mapper.include(Cybertrain::Rails::Routing)
55
+
56
+ require "cybertrain/rails/railtie" if defined?(::Rails::Railtie)
@@ -0,0 +1 @@
1
+ require "cybertrain/rails"
@@ -0,0 +1,70 @@
1
+ require "rails/generators"
2
+
3
+ module Cybertrain
4
+ module Generators
5
+ # bin/rails generate cybertrain:install
6
+ #
7
+ # Creates the cybertrain application in app/ctrain (`cybertrain new
8
+ # ctrain`, run in app/), writes config/initializers/cybertrain.rb and
9
+ # adds an example route.
10
+ class InstallGenerator < ::Rails::Generators::Base
11
+ source_root File.expand_path("templates", __dir__)
12
+
13
+ class_option :skip_new, type: :boolean, default: false,
14
+ desc: "Do not run `cybertrain new` (app/ctrain exists or is made by hand)"
15
+ class_option :new_options, type: :string, default: "",
16
+ desc: "Options for `cybertrain new`, such as \"--path ~/src/CyberTrain\""
17
+
18
+ def create_application
19
+ root = Cybertrain::Rails.config.root_path
20
+ if options[:skip_new] || root.directory?
21
+ say_status :exist, relative(root), :blue
22
+ return
23
+ end
24
+
25
+ parent = root.dirname
26
+ FileUtils.mkdir_p(parent)
27
+ cli = Cybertrain::Rails.config.cli
28
+ command = [cli, "new", root.basename.to_s, *options[:new_options].split]
29
+ say_status :run, "#{command.join(" ")} (in #{relative(parent)})"
30
+ return if system(*command, chdir: parent.to_s)
31
+
32
+ raise ::Thor::Error, "`#{command.join(" ")}` failed: is the cybertrain gem installed? " \
33
+ "(gem install cybertrain; `cybertrain doctor` checks the toolchain)"
34
+ end
35
+
36
+ def create_initializer
37
+ template "cybertrain.rb", "config/initializers/cybertrain.rb"
38
+ end
39
+
40
+ def add_route
41
+ route <<~RUBY.chomp
42
+ # Requests under /ctrain are answered by the cybertrain application in app/ctrain.
43
+ # cybertrain "/ctrain"
44
+ RUBY
45
+ end
46
+
47
+ def show_next_steps
48
+ say <<~TEXT
49
+
50
+ Next:
51
+ 1. Uncomment the cybertrain route in config/routes.rb (or write your own),
52
+ and give the cybertrain application a route with the same path
53
+ (app/ctrain/config/routes.rb).
54
+ 2. bin/rails server: the first request to that path starts
55
+ `cybertrain server #{Cybertrain::Rails.config.port}` in app/ctrain.
56
+ 3. For production: bin/rails ctrain:build, then run bin/rails ctrain:server
57
+ beside the Rails server (Procfile, systemd, Kamal accessory...).
58
+ TEXT
59
+ end
60
+
61
+ private
62
+
63
+ def relative(path)
64
+ path.relative_path_from(::Rails.root).to_s
65
+ rescue ArgumentError
66
+ path.to_s
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,20 @@
1
+ # cybertrain-rails: the cybertrain application in app/ctrain answers the
2
+ # routes declared with `cybertrain` in config/routes.rb.
3
+ Rails.application.configure do
4
+ # The cybertrain application's directory.
5
+ # config.cybertrain.root = "app/ctrain"
6
+
7
+ # Where its server listens (CTRAIN_PORT, else 3100). The proxy connects here.
8
+ # config.cybertrain.host = "127.0.0.1"
9
+ # config.cybertrain.port = 3100
10
+
11
+ # Start the server on the first request that needs it (development by
12
+ # default). In production run `bin/rails ctrain:server` as its own process.
13
+ # config.cybertrain.spawn = Rails.env.development?
14
+
15
+ # Build the binary when assets:precompile runs (needs Spinel there).
16
+ # config.cybertrain.build_on_precompile = true
17
+
18
+ # Extra environment for the server, such as its secret.
19
+ # config.cybertrain.env = { "CYBERTRAIN_SECRET_KEY_BASE" => ENV["CYBERTRAIN_SECRET_KEY_BASE"] }
20
+ end
metadata ADDED
@@ -0,0 +1,94 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cybertrain-rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Saeki Mototsune
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: railties
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ -
17
+ - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: "7.1"
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ -
25
+ - ">="
26
+ - !ruby/object:Gem::Version
27
+ version: "7.1"
28
+ - !ruby/object:Gem::Dependency
29
+ name: actionpack
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ -
33
+ - ">="
34
+ - !ruby/object:Gem::Version
35
+ version: "7.1"
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ -
41
+ - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: "7.1"
44
+ description: |
45
+ Declare routes in config/routes.rb that Rails hands to a cybertrain
46
+ application kept in app/ctrain. The gem adds the `cybertrain` routing
47
+ DSL, a reverse proxy that forwards the matched requests to the compiled
48
+ binary, rake tasks that build and run it (`bin/rails ctrain:build`),
49
+ and, in development, starts `cybertrain server` on the first request
50
+ that needs it.
51
+ executables: []
52
+ extensions: []
53
+ extra_rdoc_files: []
54
+ files:
55
+ - LICENSE
56
+ - README.md
57
+ - lib/cybertrain-rails.rb
58
+ - lib/cybertrain/rails.rb
59
+ - lib/cybertrain/rails/configuration.rb
60
+ - lib/cybertrain/rails/proxy.rb
61
+ - lib/cybertrain/rails/railtie.rb
62
+ - lib/cybertrain/rails/routing.rb
63
+ - lib/cybertrain/rails/supervisor.rb
64
+ - lib/cybertrain/rails/tasks.rake
65
+ - lib/cybertrain/rails/tasks.rb
66
+ - lib/cybertrain/rails/version.rb
67
+ - lib/generators/cybertrain/install/install_generator.rb
68
+ - lib/generators/cybertrain/install/templates/cybertrain.rb.tt
69
+ homepage: "https://github.com/saeki-mototsune/cybertrain-rails"
70
+ licenses:
71
+ - MIT
72
+ metadata:
73
+ source_code_uri: "https://github.com/saeki-mototsune/cybertrain-rails"
74
+ rubygems_mfa_required: "true"
75
+ rdoc_options: []
76
+ require_paths:
77
+ - lib
78
+ required_ruby_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ -
81
+ - ">="
82
+ - !ruby/object:Gem::Version
83
+ version: "3.2"
84
+ required_rubygems_version: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ -
87
+ - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: "0"
90
+ requirements: []
91
+ rubygems_version: 4.1.1
92
+ specification_version: 4
93
+ summary: Route part of a Rails application to a cybertrain binary
94
+ test_files: []