universal_renderer 0.7.0 → 0.8.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 +4 -4
- data/README.md +73 -26
- data/lib/generators/universal_renderer/install_generator.rb +49 -7
- data/lib/generators/universal_renderer/templates/ssr.rake +2 -2
- data/lib/generators/universal_renderer/templates/vite.config.ssr.mts +3 -1
- data/lib/puma/plugin/universal_renderer.rb +98 -0
- data/lib/universal_renderer/supervisor.rb +243 -0
- data/lib/universal_renderer/version.rb +1 -1
- metadata +3 -2
- data/lib/generators/universal_renderer/templates/web +0 -94
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 806cb4f94b4215af907b2be2da00e9d9ab6a72aa61b986256229fb36d246569a
|
|
4
|
+
data.tar.gz: 49da2ebd268114662bb3e0653600720cd414b34cc91f69312b5114bb9b2b51d9
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: b314a8160b9208d26471378a1f36108585315048e74241124d8eadd4fbab352872fd4d1205b78fad0a8d98aa7be9d22f59d34b3601f0c4eeabf04b7750067c11
|
|
7
|
+
data.tar.gz: 5bc09a8c688f369b3b362f5ca281df48b2ab72ce574a180e9addf6b138fa73d56c5b7b75df34c2011bc727105b3baff58659043e5db7b3cf1f47ac73798e932c
|
data/README.md
CHANGED
|
@@ -22,10 +22,11 @@ instrumentation exists so "silently" does not mean "invisibly".
|
|
|
22
22
|
|
|
23
23
|
The two packages share a wire format, so upgrade them together.
|
|
24
24
|
|
|
25
|
-
| Gem | NPM package | Notes
|
|
26
|
-
| ------- | ----------- |
|
|
27
|
-
| `0.
|
|
28
|
-
| `0.
|
|
25
|
+
| Gem | NPM package | Notes |
|
|
26
|
+
| ------- | ----------- | --------------------------------------------------------------------- |
|
|
27
|
+
| `0.8.x` | `0.8.x` | Puma plugin replaces `bin/web`; self-contained, production SSR builds |
|
|
28
|
+
| `0.7.x` | `0.7.x` | `payload`, conditional `enable_ssr`, `concurrency`, `prepare` |
|
|
29
|
+
| `0.5.x` | `0.6.x` | |
|
|
29
30
|
|
|
30
31
|
## Installation
|
|
31
32
|
|
|
@@ -41,7 +42,8 @@ bin/rails generate universal_renderer:install
|
|
|
41
42
|
```
|
|
42
43
|
|
|
43
44
|
The generator writes the initializer, the two renderer entry points, the SSR Vite
|
|
44
|
-
build, the `assets:precompile` hook, and `
|
|
45
|
+
build, and the `assets:precompile` hook, and adds `plugin :universal_renderer` to
|
|
46
|
+
`config/puma.rb` to run the renderer in production. Pass
|
|
45
47
|
`--frontend-dir=app/client` if your JavaScript is not in `app/frontend`.
|
|
46
48
|
|
|
47
49
|
## Rendering from a controller
|
|
@@ -256,8 +258,8 @@ Renders are **serialized by default**. An app retrofitted with SSR keeps
|
|
|
256
258
|
request-scoped state in module-level singletons — a store, a query client, a
|
|
257
259
|
mutable feature-flag object, a CSS-in-JS registry — and two renders interleaving
|
|
258
260
|
through those is not a slow page, it is one visitor's data in another visitor's
|
|
259
|
-
HTML. Scale out with more renderer processes;
|
|
260
|
-
|
|
261
|
+
HTML. Scale out with more renderer processes; the Puma plugin starts one per
|
|
262
|
+
web server, so SSR capacity tracks your web dyno count.
|
|
261
263
|
|
|
262
264
|
Raise `concurrency` (or pass `"unbounded"`) only once you have verified the render
|
|
263
265
|
touches no shared mutable state.
|
|
@@ -294,9 +296,8 @@ default is also roughly where Heroku's router and most ALB defaults have already
|
|
|
294
296
|
abandoned the request.
|
|
295
297
|
|
|
296
298
|
Nothing inside the process can clear a stuck render, so the health signal is the
|
|
297
|
-
point: the
|
|
298
|
-
|
|
299
|
-
or turn it off with `SSR_WATCHDOG=0`.
|
|
299
|
+
point: the Puma plugin polls it and restarts the renderer without touching the
|
|
300
|
+
app server.
|
|
300
301
|
|
|
301
302
|
Development sets both to `false` — a breakpoint in the render outlasts any
|
|
302
303
|
production budget, and a `504` or a restart there is noise.
|
|
@@ -375,15 +376,32 @@ export default defineSsrConfig({
|
|
|
375
376
|
});
|
|
376
377
|
```
|
|
377
378
|
|
|
378
|
-
`defineSsrConfig` exists because a Rails SSR build has
|
|
379
|
+
`defineSsrConfig` exists because a Rails SSR build has six settings that are each
|
|
379
380
|
wrong by default and each fail *silently* — you get a bundle, it just renders the
|
|
380
381
|
wrong thing. Note in particular what is **absent**: `vite-plugin-rails`, which is
|
|
381
382
|
built for the client manifest pipeline and overrides entrypoints and outDir. List
|
|
382
383
|
only the plugins the render itself needs; your client build keeps using
|
|
383
|
-
`vite.config.mts` unchanged. See the function's docs for the
|
|
384
|
+
`vite.config.mts` unchanged. See the function's docs for the others.
|
|
384
385
|
|
|
385
386
|
The bundle lands at `ssr-build/server.mjs`, deliberately outside `public/` — it is
|
|
386
|
-
server code and must not be web-servable.
|
|
387
|
+
server code and must not be web-servable. It is self-contained: dependencies are
|
|
388
|
+
bundled (`ssr.noExternal: true`), so it runs from a slug whose `node_modules` was
|
|
389
|
+
pruned after the build, and `process.env.NODE_ENV` is replaced at build time, as
|
|
390
|
+
Vite does for client builds (the `NODE_ENV` the build runs with, or
|
|
391
|
+
`"production"`), so React does not run its development build on a host that never
|
|
392
|
+
sets `NODE_ENV`. If the renderer does start on a development build, `startServer`
|
|
393
|
+
logs a warning saying so.
|
|
394
|
+
Keep client-only packages that cannot be bundled, such as anything with a native
|
|
395
|
+
module, out with `ssr.external`:
|
|
396
|
+
|
|
397
|
+
```ts
|
|
398
|
+
export default defineSsrConfig({
|
|
399
|
+
entry: "app/frontend/ssr/server.ts",
|
|
400
|
+
plugins: [react()],
|
|
401
|
+
// Lazy, client-only, and its `canvas` dependency is native.
|
|
402
|
+
ssr: { external: ["react-pdf", "pdfjs-dist"] },
|
|
403
|
+
});
|
|
404
|
+
```
|
|
387
405
|
|
|
388
406
|
### Running it
|
|
389
407
|
|
|
@@ -394,23 +412,52 @@ vite: bin/vite dev
|
|
|
394
412
|
ssr: bun app/frontend/ssr/dev.ts
|
|
395
413
|
```
|
|
396
414
|
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
415
|
+
In production the renderer runs beside your app server on the same host rather
|
|
416
|
+
than as a separate process type, because PaaS process types get no routable
|
|
417
|
+
address for each other. If the renderer dies, requests fall back to client
|
|
418
|
+
rendering; that is a degraded page, not an outage, so it must not take the app
|
|
419
|
+
server down. Something still has to bring the renderer back.
|
|
420
|
+
|
|
421
|
+
#### With Puma
|
|
422
|
+
|
|
423
|
+
```ruby
|
|
424
|
+
# config/puma.rb
|
|
425
|
+
if ENV.fetch("RAILS_ENV", "development") == "production"
|
|
426
|
+
plugin :universal_renderer
|
|
427
|
+
universal_renderer port: 3001 # optional, after the plugin line
|
|
428
|
+
end
|
|
400
429
|
```
|
|
401
430
|
|
|
402
|
-
`
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
431
|
+
Your Procfile stays `web: bundle exec puma -C config/puma.rb`. Keep the plugin to
|
|
432
|
+
production: in development, `Procfile.dev` runs the development renderer on the
|
|
433
|
+
same port.
|
|
434
|
+
|
|
435
|
+
Puma runs plugins in its master process, so a clustered Puma gets one renderer
|
|
436
|
+
per server, not one per worker. The plugin:
|
|
437
|
+
|
|
438
|
+
- starts the renderer in its own process group, so a wrapper script cannot leave
|
|
439
|
+
a child holding the port;
|
|
440
|
+
- restarts it when it exits, waiting 1, 2, 4, up to 30 seconds while it keeps
|
|
441
|
+
dying at boot, and 1 second again once it has run for a minute;
|
|
442
|
+
- restarts it when `/health` fails three checks in a row, 10 seconds apart (a
|
|
443
|
+
stalled render, a blocked event loop);
|
|
444
|
+
- stops it with Puma, and replaces it on a hot (`USR2`) or phased (`USR1`)
|
|
445
|
+
restart, so a phased restart also picks up a new bundle;
|
|
446
|
+
- skips it, with a log line, when the bundle has not been built.
|
|
447
|
+
|
|
448
|
+
Each start, exit and restart is logged with a `[universal_renderer]` prefix. Each
|
|
449
|
+
option falls back to an environment variable, then to the default:
|
|
450
|
+
|
|
451
|
+
| Option | Variable | Default | Purpose |
|
|
452
|
+
| --------- | ------------- | ---------------------- | ------------------------------------- |
|
|
453
|
+
| `runtime` | `SSR_RUNTIME` | `bun` | Set to `node` if not Bun. |
|
|
454
|
+
| `bundle` | `SSR_BUNDLE` | `ssr-build/server.mjs` | Built renderer entry. |
|
|
455
|
+
| `port` | `SSR_PORT` | `3001` | Passed to the renderer as `SSR_PORT`. |
|
|
406
456
|
|
|
407
|
-
|
|
457
|
+
#### Other app servers
|
|
408
458
|
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
| `SSR_RUNTIME` | `bun` | Set to `node` if not Bun. |
|
|
412
|
-
| `WEB_CMD` | `bundle exec puma -C config/puma.rb` | App server command line. |
|
|
413
|
-
| `SSR_BUNDLE` | `ssr-build/server.mjs` | Built renderer entry. |
|
|
459
|
+
Run `bun ssr-build/server.mjs` beside the app server under your own process
|
|
460
|
+
supervisor, and restart it when it exits or `GET /health` stops returning `200`.
|
|
414
461
|
|
|
415
462
|
### Sorbet
|
|
416
463
|
|
|
@@ -2,11 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
module UniversalRenderer
|
|
4
4
|
# Scaffolds a working SSR setup: the initializer, the two renderer entry points,
|
|
5
|
-
# the SSR Vite build, the precompile hook, and the
|
|
6
|
-
# encodes something that is wrong by default
|
|
5
|
+
# the SSR Vite build, the precompile hook, and the Puma plugin that runs the
|
|
6
|
+
# renderer in production. Each one encodes something that is wrong by default
|
|
7
|
+
# and fails silently.
|
|
7
8
|
class InstallGenerator < Rails::Generators::Base
|
|
8
9
|
source_root File.expand_path("templates", __dir__)
|
|
9
10
|
|
|
11
|
+
PUMA_CONFIG = "config/puma.rb"
|
|
12
|
+
PUMA_PLUGIN_LINE = 'plugin :universal_renderer if ENV.fetch("RAILS_ENV", "development") == "production"'
|
|
13
|
+
|
|
10
14
|
class_option :frontend_dir,
|
|
11
15
|
type: :string,
|
|
12
16
|
default: "app/frontend",
|
|
@@ -20,7 +24,7 @@ module UniversalRenderer
|
|
|
20
24
|
class_option :skip_deploy,
|
|
21
25
|
type: :boolean,
|
|
22
26
|
default: false,
|
|
23
|
-
desc: "Skip
|
|
27
|
+
desc: "Skip the Puma plugin and the assets:precompile hook"
|
|
24
28
|
|
|
25
29
|
def copy_initializer
|
|
26
30
|
template "initializer.rb", "config/initializers/universal_renderer.rb"
|
|
@@ -40,8 +44,7 @@ module UniversalRenderer
|
|
|
40
44
|
return if options[:skip_deploy] || options[:skip_frontend]
|
|
41
45
|
|
|
42
46
|
template "ssr.rake", "lib/tasks/ssr.rake"
|
|
43
|
-
|
|
44
|
-
chmod "bin/web", 0o755
|
|
47
|
+
add_puma_plugin if puma_setup == :add
|
|
45
48
|
end
|
|
46
49
|
|
|
47
50
|
def show_installation_notes
|
|
@@ -64,8 +67,20 @@ module UniversalRenderer
|
|
|
64
67
|
say_status "", " 5. Opt a controller in with `enable_ssr` or `render_ssr`"
|
|
65
68
|
return if options[:skip_deploy]
|
|
66
69
|
|
|
67
|
-
|
|
68
|
-
|
|
70
|
+
case puma_setup
|
|
71
|
+
when :add
|
|
72
|
+
say_status "", " 6. Puma now starts the renderer in production (`plugin"
|
|
73
|
+
say_status "", " :universal_renderer` in config/puma.rb). Keep Procfile's web"
|
|
74
|
+
say_status "", " process as it is"
|
|
75
|
+
when :bin_web
|
|
76
|
+
say_status "", " 6. bin/web is no longer generated. Point Procfile's web process"
|
|
77
|
+
say_status "", " at Puma, delete bin/web, and add to config/puma.rb:"
|
|
78
|
+
say_status "", " #{PUMA_PLUGIN_LINE}"
|
|
79
|
+
when :no_config
|
|
80
|
+
say_status "", " 6. Start the renderer with your app server. With Puma, add to"
|
|
81
|
+
say_status "", " its config:"
|
|
82
|
+
say_status "", " #{PUMA_PLUGIN_LINE}"
|
|
83
|
+
end
|
|
69
84
|
end
|
|
70
85
|
|
|
71
86
|
private
|
|
@@ -73,5 +88,32 @@ module UniversalRenderer
|
|
|
73
88
|
def frontend_dir
|
|
74
89
|
options[:frontend_dir].delete_suffix("/")
|
|
75
90
|
end
|
|
91
|
+
|
|
92
|
+
# Decided once, before any file is written. An app that still runs the
|
|
93
|
+
# bin/web from an earlier version is left alone: adding the plugin as well
|
|
94
|
+
# would start a second renderer on the same port.
|
|
95
|
+
def puma_setup
|
|
96
|
+
@puma_setup ||=
|
|
97
|
+
if File.exist?(File.join(destination_root, "bin/web"))
|
|
98
|
+
:bin_web
|
|
99
|
+
elsif File.exist?(File.join(destination_root, PUMA_CONFIG))
|
|
100
|
+
:add
|
|
101
|
+
else
|
|
102
|
+
:no_config
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
def add_puma_plugin
|
|
107
|
+
return if File.read(File.join(destination_root, PUMA_CONFIG)).match?(/^\s*plugin :universal_renderer\b/)
|
|
108
|
+
|
|
109
|
+
append_to_file PUMA_CONFIG, <<~RUBY
|
|
110
|
+
|
|
111
|
+
# Runs the SSR renderer beside Puma, and restarts it when it exits or
|
|
112
|
+
# stops answering /health. Production only: in development, Procfile.dev
|
|
113
|
+
# runs the development renderer on the same port.
|
|
114
|
+
# Options: `universal_renderer runtime: "bun", bundle: "ssr-build/server.mjs", port: 3001`.
|
|
115
|
+
#{PUMA_PLUGIN_LINE}
|
|
116
|
+
RUBY
|
|
117
|
+
end
|
|
76
118
|
end
|
|
77
119
|
end
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
# credentials, a database that is not up yet.
|
|
6
6
|
# rubocop:disable Rails/RakeEnvironment
|
|
7
7
|
namespace :ssr do
|
|
8
|
-
desc "Build the standalone SSR bundle that
|
|
8
|
+
desc "Build the standalone SSR bundle that the Puma plugin runs (ssr-build/)"
|
|
9
9
|
task :build do
|
|
10
10
|
# Goes through the package script rather than invoking `vite` directly:
|
|
11
11
|
# node_modules/.bin is not on PATH during a deploy build, so a bare `vite`
|
|
@@ -16,7 +16,7 @@ namespace :ssr do
|
|
|
16
16
|
end
|
|
17
17
|
# rubocop:enable Rails/RakeEnvironment
|
|
18
18
|
|
|
19
|
-
#
|
|
19
|
+
# The Puma plugin runs the compiled bundle, so it has to exist by the time a release
|
|
20
20
|
# boots. Build it with the rest of the assets.
|
|
21
21
|
if Rake::Task.task_defined?("assets:precompile")
|
|
22
22
|
Rake::Task["assets:precompile"].enhance(["ssr:build"])
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import react from "@vitejs/plugin-react";
|
|
2
2
|
import { defineSsrConfig } from "universal-renderer/vite";
|
|
3
3
|
|
|
4
|
-
// Standalone SSR build. defineSsrConfig handles the
|
|
4
|
+
// Standalone SSR build. defineSsrConfig handles the six settings that are wrong
|
|
5
5
|
// by default for a Rails SSR build; read its docs before overriding them.
|
|
6
6
|
//
|
|
7
7
|
// Note what is absent: vite-plugin-rails, which targets the client manifest
|
|
@@ -10,4 +10,6 @@ import { defineSsrConfig } from "universal-renderer/vite";
|
|
|
10
10
|
export default defineSsrConfig({
|
|
11
11
|
entry: "<%= frontend_dir %>/ssr/server.ts",
|
|
12
12
|
plugins: [react()],
|
|
13
|
+
// Dependencies are bundled. List client-only packages that cannot be (native
|
|
14
|
+
// modules) here: ssr: { external: ["react-pdf"] },
|
|
13
15
|
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "puma/dsl"
|
|
4
|
+
require "puma/plugin"
|
|
5
|
+
require_relative "../../universal_renderer/supervisor"
|
|
6
|
+
|
|
7
|
+
module UniversalRenderer
|
|
8
|
+
# Starts and supervises the SSR renderer from Puma.
|
|
9
|
+
#
|
|
10
|
+
# # config/puma.rb
|
|
11
|
+
# plugin :universal_renderer
|
|
12
|
+
# universal_renderer port: 3001 # optional, after `plugin`
|
|
13
|
+
#
|
|
14
|
+
# Puma runs plugins in its master process, so a clustered server gets one
|
|
15
|
+
# renderer, not one per worker.
|
|
16
|
+
module PumaPlugin
|
|
17
|
+
LOG_PREFIX = Supervisor::LOG_PREFIX
|
|
18
|
+
|
|
19
|
+
# Each option falls back to an environment variable, then to the default.
|
|
20
|
+
OPTION_DEFAULTS = {
|
|
21
|
+
runtime: ["SSR_RUNTIME", "bun"],
|
|
22
|
+
bundle: ["SSR_BUNDLE", "ssr-build/server.mjs"],
|
|
23
|
+
port: ["SSR_PORT", "3001"]
|
|
24
|
+
}.freeze
|
|
25
|
+
|
|
26
|
+
# Puma DSL methods. `plugin :universal_renderer` loads this file, so call
|
|
27
|
+
# `universal_renderer` after that line.
|
|
28
|
+
module DSL
|
|
29
|
+
# @option options [String] :runtime (`SSR_RUNTIME`, `"bun"`)
|
|
30
|
+
# @option options [String] :bundle (`SSR_BUNDLE`, `"ssr-build/server.mjs"`)
|
|
31
|
+
# When it does not exist, the renderer is not started and pages render
|
|
32
|
+
# on the client.
|
|
33
|
+
# @option options [Integer] :port (`SSR_PORT`, 3001)
|
|
34
|
+
def universal_renderer(**options)
|
|
35
|
+
@options[:universal_renderer] = options
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def self.resolve(options, env: ENV)
|
|
40
|
+
unknown = options.keys - OPTION_DEFAULTS.keys
|
|
41
|
+
raise ArgumentError, "unknown universal_renderer option(s): #{unknown.join(', ')}" if unknown.any?
|
|
42
|
+
|
|
43
|
+
resolved =
|
|
44
|
+
OPTION_DEFAULTS.to_h do |key, (variable, default)|
|
|
45
|
+
[key, options.fetch(key) { env.fetch(variable, default) }]
|
|
46
|
+
end
|
|
47
|
+
resolved[:port] = Integer(resolved[:port])
|
|
48
|
+
resolved
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def self.start(launcher)
|
|
52
|
+
log_writer = launcher.log_writer
|
|
53
|
+
log = ->(message) { log_writer.log(message) }
|
|
54
|
+
options = resolve(launcher.options[:universal_renderer] || {})
|
|
55
|
+
|
|
56
|
+
unless File.exist?(options[:bundle])
|
|
57
|
+
return log.call("#{LOG_PREFIX} #{options[:bundle]} missing, serving client-rendered pages only")
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
command = [options[:runtime], options[:bundle]]
|
|
61
|
+
supervise(launcher, Supervisor.new(command: command, port: options[:port], logger: log))
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def self.supervise(launcher, supervisor)
|
|
65
|
+
supervisor.start
|
|
66
|
+
on(launcher.events, :after_stopped, :on_stopped) { supervisor.stop }
|
|
67
|
+
|
|
68
|
+
# Fires for hot and phased restarts alike, and a plugin cannot tell which.
|
|
69
|
+
# A hot restart execs right after, so the supervisor's next renderer (one
|
|
70
|
+
# second later) never starts and the new master boots its own. A phased
|
|
71
|
+
# restart keeps this master, so the supervisor starts a renderer with the
|
|
72
|
+
# new bundle. Either way the old one must release the port first.
|
|
73
|
+
on(launcher.events, :before_restart, :on_restart) { supervisor.restart(reason: "Puma restart") }
|
|
74
|
+
|
|
75
|
+
# `after_stopped` does not run when the master dies some other way, and the
|
|
76
|
+
# renderer is in its own process group, so nothing else would stop it.
|
|
77
|
+
# Workers inherit this hook when they fork, hence the pid check.
|
|
78
|
+
master_pid = Process.pid
|
|
79
|
+
at_exit { supervisor.stop if Process.pid == master_pid && !supervisor.stopping? }
|
|
80
|
+
supervisor
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Puma 7 renamed its lifecycle hooks (`on_stopped` became `after_stopped`).
|
|
84
|
+
# Old Pumas without either still stop the renderer through `at_exit`.
|
|
85
|
+
def self.on(events, *names, &)
|
|
86
|
+
name = names.find { |candidate| events.respond_to?(candidate) }
|
|
87
|
+
events.public_send(name, &) if name
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
Puma::DSL.include(UniversalRenderer::PumaPlugin::DSL)
|
|
93
|
+
|
|
94
|
+
Puma::Plugin.create do
|
|
95
|
+
def start(launcher) # rubocop:disable Rails/Delegate -- the Puma master may not have loaded ActiveSupport
|
|
96
|
+
UniversalRenderer::PumaPlugin.start(launcher)
|
|
97
|
+
end
|
|
98
|
+
end
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
|
|
5
|
+
module UniversalRenderer
|
|
6
|
+
# Runs the SSR renderer as a child process and keeps it running. Used by the
|
|
7
|
+
# Puma plugin; not public API.
|
|
8
|
+
#
|
|
9
|
+
# The renderer must not take the app server down with it: when it is gone,
|
|
10
|
+
# Rails falls back to client rendering, a degraded page rather than an outage.
|
|
11
|
+
# Nothing else notices that either, so this restarts it when it exits, and
|
|
12
|
+
# when it is alive but stops answering its health endpoint (a render that never
|
|
13
|
+
# settles holds its concurrency slot forever, see "Render timeout and health").
|
|
14
|
+
#
|
|
15
|
+
# Plain Ruby with no Rails dependency: the Puma plugin runs it in the Puma
|
|
16
|
+
# master, which may not have loaded the app.
|
|
17
|
+
class Supervisor # rubocop:disable Metrics/ClassLength -- one process lifecycle; the threads share its state
|
|
18
|
+
LOG_PREFIX = "[universal_renderer]"
|
|
19
|
+
HEALTH_PATH = "/health"
|
|
20
|
+
EXIT_POLL_INTERVAL = 0.2
|
|
21
|
+
# A renderer that keeps dying waits 1, 2, 4 ... up to this many seconds.
|
|
22
|
+
MAX_BACKOFF = 30
|
|
23
|
+
# A renderer that ran this long was healthy, so its next restart waits 1s again.
|
|
24
|
+
HEALTHY_AFTER = 60
|
|
25
|
+
|
|
26
|
+
attr_reader :pid
|
|
27
|
+
|
|
28
|
+
# @param command [Array<String>] Renderer command line, run without a shell.
|
|
29
|
+
# @param port [Integer] Passed to the renderer as `SSR_PORT`, and used for health checks.
|
|
30
|
+
# @param health_interval [Numeric, nil] Seconds between health checks; `nil` turns them off.
|
|
31
|
+
# @param health_failures [Integer] Failed checks in a row before a restart.
|
|
32
|
+
# @param stop_timeout [Numeric] Seconds to wait after `TERM` before `KILL`.
|
|
33
|
+
def initialize(command:, port:, # rubocop:disable Metrics/ParameterLists -- the timings exist for tests
|
|
34
|
+
env: {}, health_interval: 10, health_failures: 3, stop_timeout: 10,
|
|
35
|
+
logger: ->(message) { warn(message) })
|
|
36
|
+
@command = command
|
|
37
|
+
@port = Integer(port)
|
|
38
|
+
@env = env.merge("SSR_PORT" => @port.to_s)
|
|
39
|
+
@health_interval = health_interval
|
|
40
|
+
@health_failures = health_failures
|
|
41
|
+
@stop_timeout = stop_timeout
|
|
42
|
+
@logger = logger
|
|
43
|
+
|
|
44
|
+
@mutex = Mutex.new
|
|
45
|
+
@exited = ConditionVariable.new
|
|
46
|
+
# Closing it wakes every interruptible sleep at once, for `stop`.
|
|
47
|
+
@wakeup = Queue.new
|
|
48
|
+
@stopping = false
|
|
49
|
+
@planned_exits = Set.new
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def start
|
|
53
|
+
@supervisor_thread = Thread.new { supervise }
|
|
54
|
+
@health_thread = Thread.new { watch_health } if @health_interval
|
|
55
|
+
self
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# Replaces the running renderer. Waits for it to exit, so its port is free
|
|
59
|
+
# when this returns; the supervisor starts the next one after one second.
|
|
60
|
+
def restart(reason:)
|
|
61
|
+
outside_trap { terminate(pid, reason) }
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Stops the renderer for good and waits for it to exit.
|
|
65
|
+
def stop
|
|
66
|
+
outside_trap do
|
|
67
|
+
# No renderer starts after this, so the one terminated below is the last.
|
|
68
|
+
@mutex.synchronize { @stopping = true }
|
|
69
|
+
@wakeup.close
|
|
70
|
+
terminate(pid, "stopping")
|
|
71
|
+
@supervisor_thread&.join(@stop_timeout)
|
|
72
|
+
@health_thread&.join(1)
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def stopping?
|
|
77
|
+
@mutex.synchronize { @stopping }
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
private
|
|
81
|
+
|
|
82
|
+
def supervise
|
|
83
|
+
backoff = 1
|
|
84
|
+
|
|
85
|
+
until stopping?
|
|
86
|
+
started_at = monotonic_now
|
|
87
|
+
pid = spawn_renderer
|
|
88
|
+
status = pid && wait_for_renderer(pid)
|
|
89
|
+
planned =
|
|
90
|
+
@mutex.synchronize do
|
|
91
|
+
@pid = nil
|
|
92
|
+
@exited.broadcast
|
|
93
|
+
@planned_exits.delete?(pid)
|
|
94
|
+
end
|
|
95
|
+
break if stopping?
|
|
96
|
+
|
|
97
|
+
# Backing off is for a renderer that keeps dying, not one we replaced.
|
|
98
|
+
backoff = 1 if planned || monotonic_now - started_at >= HEALTHY_AFTER
|
|
99
|
+
log("#{describe_exit(pid, status)}, restarting in #{backoff}s")
|
|
100
|
+
sleep_unless_stopped(backoff)
|
|
101
|
+
backoff = [backoff * 2, MAX_BACKOFF].min
|
|
102
|
+
end
|
|
103
|
+
rescue StandardError => e
|
|
104
|
+
log("supervisor stopped unexpectedly: #{e.class}: #{e.message}")
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Spawns under the lock that `stop` takes, so a renderer cannot start after
|
|
108
|
+
# `stop` has looked for the one to terminate.
|
|
109
|
+
def spawn_renderer
|
|
110
|
+
pid =
|
|
111
|
+
@mutex.synchronize do
|
|
112
|
+
next if @stopping
|
|
113
|
+
|
|
114
|
+
@pid = Process.spawn(@env, *@command, pgroup: true)
|
|
115
|
+
end
|
|
116
|
+
log("renderer started (pid=#{pid}, port=#{@port})") if pid
|
|
117
|
+
pid
|
|
118
|
+
rescue SystemCallError => e
|
|
119
|
+
log("could not start #{@command.first}: #{e.message}")
|
|
120
|
+
nil
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# Polls instead of blocking in `wait2`: a clustered Puma master reaps every
|
|
124
|
+
# child with `Process.wait2(-1)`, so it may collect the renderer's status first.
|
|
125
|
+
def wait_for_renderer(target)
|
|
126
|
+
loop do
|
|
127
|
+
_, status = Process.wait2(target, Process::WNOHANG)
|
|
128
|
+
return status if status
|
|
129
|
+
|
|
130
|
+
sleep(EXIT_POLL_INTERVAL)
|
|
131
|
+
end
|
|
132
|
+
rescue Errno::ECHILD
|
|
133
|
+
nil
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def describe_exit(target, status)
|
|
137
|
+
return "renderer failed to start" unless target
|
|
138
|
+
return "renderer pid=#{target} exited (reaped by the app server)" unless status
|
|
139
|
+
|
|
140
|
+
"renderer pid=#{target} exited (#{status})"
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# A renderer can be alive and still useless: a wedged render, a blocked event
|
|
144
|
+
# loop. Waiting for it to exit would wait forever, so replace it.
|
|
145
|
+
def watch_health
|
|
146
|
+
strikes = 0
|
|
147
|
+
watched_pid = nil
|
|
148
|
+
|
|
149
|
+
until stopping?
|
|
150
|
+
sleep_unless_stopped(@health_interval)
|
|
151
|
+
current_pid = pid
|
|
152
|
+
if current_pid != watched_pid
|
|
153
|
+
watched_pid = current_pid
|
|
154
|
+
strikes = 0
|
|
155
|
+
end
|
|
156
|
+
next if current_pid.nil?
|
|
157
|
+
|
|
158
|
+
if healthy?
|
|
159
|
+
strikes = 0
|
|
160
|
+
next
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
strikes += 1
|
|
164
|
+
next if strikes < @health_failures
|
|
165
|
+
|
|
166
|
+
# A failure, not a planned restart: a renderer that keeps wedging backs off.
|
|
167
|
+
terminate(current_pid, "failed #{strikes} health checks", planned: false)
|
|
168
|
+
strikes = 0
|
|
169
|
+
end
|
|
170
|
+
rescue StandardError => e
|
|
171
|
+
log("health checks stopped unexpectedly: #{e.class}: #{e.message}")
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
def healthy?
|
|
175
|
+
Net::HTTP.start("127.0.0.1", @port, open_timeout: 1, read_timeout: 5) do |http|
|
|
176
|
+
http.get(HEALTH_PATH).is_a?(Net::HTTPSuccess)
|
|
177
|
+
end
|
|
178
|
+
rescue StandardError
|
|
179
|
+
false
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# Acts only while `target` is still the running renderer: a health check can
|
|
183
|
+
# take seconds, and the renderer it judged may have been replaced meanwhile.
|
|
184
|
+
# A planned exit restarts after one second instead of continuing the backoff.
|
|
185
|
+
def terminate(target, reason, planned: true)
|
|
186
|
+
current =
|
|
187
|
+
@mutex.synchronize do
|
|
188
|
+
next false unless target && @pid == target
|
|
189
|
+
|
|
190
|
+
@planned_exits << target if planned
|
|
191
|
+
true
|
|
192
|
+
end
|
|
193
|
+
return unless current
|
|
194
|
+
|
|
195
|
+
log("stopping renderer pid=#{target} (#{reason})")
|
|
196
|
+
signal(target, "TERM")
|
|
197
|
+
return if wait_for_exit(target, @stop_timeout)
|
|
198
|
+
|
|
199
|
+
log("renderer pid=#{target} did not exit within #{@stop_timeout}s, killing it")
|
|
200
|
+
signal(target, "KILL")
|
|
201
|
+
wait_for_exit(target, 2)
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
# The renderer runs in its own process group, so this also reaches anything
|
|
205
|
+
# it started (a wrapper script, a `node` behind `npx`).
|
|
206
|
+
def signal(target, name)
|
|
207
|
+
Process.kill(name, -target)
|
|
208
|
+
rescue Errno::ESRCH, Errno::EPERM
|
|
209
|
+
nil
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def wait_for_exit(target, timeout)
|
|
213
|
+
deadline = monotonic_now + timeout
|
|
214
|
+
@mutex.synchronize do
|
|
215
|
+
while @pid == target
|
|
216
|
+
remaining = deadline - monotonic_now
|
|
217
|
+
return false if remaining <= 0
|
|
218
|
+
|
|
219
|
+
@exited.wait(@mutex, remaining)
|
|
220
|
+
end
|
|
221
|
+
end
|
|
222
|
+
true
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
# Puma runs some lifecycle hooks inside its signal handlers, where
|
|
226
|
+
# `Mutex#synchronize` raises ThreadError. A new thread is not in trap context.
|
|
227
|
+
def outside_trap(&)
|
|
228
|
+
Thread.new(&).join
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
def sleep_unless_stopped(seconds)
|
|
232
|
+
@wakeup.pop(timeout: seconds)
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
def log(message)
|
|
236
|
+
@logger.call("#{LOG_PREFIX} #{message}")
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
def monotonic_now
|
|
240
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
241
|
+
end
|
|
242
|
+
end
|
|
243
|
+
end
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: universal_renderer
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.8.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- thaske
|
|
@@ -76,7 +76,7 @@ files:
|
|
|
76
76
|
- lib/generators/universal_renderer/templates/ssr/globals.ts
|
|
77
77
|
- lib/generators/universal_renderer/templates/ssr/server.ts
|
|
78
78
|
- lib/generators/universal_renderer/templates/vite.config.ssr.mts
|
|
79
|
-
- lib/
|
|
79
|
+
- lib/puma/plugin/universal_renderer.rb
|
|
80
80
|
- lib/tasks/universal_renderer_tasks.rake
|
|
81
81
|
- lib/universal_renderer.rb
|
|
82
82
|
- lib/universal_renderer/client/base.rb
|
|
@@ -93,6 +93,7 @@ files:
|
|
|
93
93
|
- lib/universal_renderer/ssr/placeholders.rb
|
|
94
94
|
- lib/universal_renderer/ssr/response.rb
|
|
95
95
|
- lib/universal_renderer/ssr/scrubber.rb
|
|
96
|
+
- lib/universal_renderer/supervisor.rb
|
|
96
97
|
- lib/universal_renderer/version.rb
|
|
97
98
|
homepage: https://github.com/thaske/universal_renderer
|
|
98
99
|
licenses:
|
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bash
|
|
2
|
-
# Boots the SSR renderer alongside the app server.
|
|
3
|
-
set -uo pipefail
|
|
4
|
-
|
|
5
|
-
SSR_BUNDLE="${SSR_BUNDLE:-ssr-build/server.mjs}"
|
|
6
|
-
export SSR_PORT="${SSR_PORT:-3001}"
|
|
7
|
-
|
|
8
|
-
# Override these for non-Bun runtimes or non-Puma app servers.
|
|
9
|
-
SSR_RUNTIME="${SSR_RUNTIME:-bun}"
|
|
10
|
-
WEB_CMD="${WEB_CMD:-bundle exec puma -C config/puma.rb}"
|
|
11
|
-
|
|
12
|
-
# Set SSR_WATCHDOG=0 to disable health-based renderer restarts.
|
|
13
|
-
SSR_WATCHDOG="${SSR_WATCHDOG:-1}"
|
|
14
|
-
SSR_HEALTH_URL="${SSR_HEALTH_URL:-http://127.0.0.1:${SSR_PORT}/health}"
|
|
15
|
-
SSR_HEALTH_INTERVAL="${SSR_HEALTH_INTERVAL:-10}"
|
|
16
|
-
SSR_HEALTH_FAILURES="${SSR_HEALTH_FAILURES:-3}"
|
|
17
|
-
|
|
18
|
-
SSR_PID=""
|
|
19
|
-
APP_PID=""
|
|
20
|
-
shutting_down=0
|
|
21
|
-
health_failures=0
|
|
22
|
-
|
|
23
|
-
start_ssr() {
|
|
24
|
-
if [ ! -f "$SSR_BUNDLE" ]; then
|
|
25
|
-
echo "[web] $SSR_BUNDLE missing — serving client-rendered pages only." >&2
|
|
26
|
-
return
|
|
27
|
-
fi
|
|
28
|
-
|
|
29
|
-
"$SSR_RUNTIME" "$SSR_BUNDLE" &
|
|
30
|
-
SSR_PID=$!
|
|
31
|
-
echo "[web] SSR renderer started (pid $SSR_PID, port $SSR_PORT)"
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
stop_ssr() {
|
|
35
|
-
[ -n "$SSR_PID" ] || return 0
|
|
36
|
-
|
|
37
|
-
kill -TERM "$SSR_PID" 2>/dev/null || true
|
|
38
|
-
for _ in 1 2 3 4 5; do
|
|
39
|
-
kill -0 "$SSR_PID" 2>/dev/null || break
|
|
40
|
-
sleep 1
|
|
41
|
-
done
|
|
42
|
-
kill -KILL "$SSR_PID" 2>/dev/null || true
|
|
43
|
-
wait "$SSR_PID" 2>/dev/null || true
|
|
44
|
-
SSR_PID=""
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
check_ssr_health() {
|
|
48
|
-
[ "$SSR_WATCHDOG" = "1" ] || return 0
|
|
49
|
-
[ -n "$SSR_PID" ] || return 0
|
|
50
|
-
command -v curl >/dev/null 2>&1 || return 0
|
|
51
|
-
|
|
52
|
-
if curl -fsS --max-time 5 "$SSR_HEALTH_URL" >/dev/null 2>&1; then
|
|
53
|
-
health_failures=0
|
|
54
|
-
return 0
|
|
55
|
-
fi
|
|
56
|
-
|
|
57
|
-
health_failures=$((health_failures + 1))
|
|
58
|
-
[ "$health_failures" -ge "$SSR_HEALTH_FAILURES" ] || return 0
|
|
59
|
-
|
|
60
|
-
echo "[web] SSR renderer unhealthy after ${health_failures} checks — restarting." >&2
|
|
61
|
-
stop_ssr
|
|
62
|
-
health_failures=0
|
|
63
|
-
start_ssr
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
on_signal() {
|
|
67
|
-
shutting_down=1
|
|
68
|
-
if [ -n "$APP_PID" ]; then kill -TERM "$APP_PID" 2>/dev/null || true; fi
|
|
69
|
-
}
|
|
70
|
-
trap on_signal INT TERM
|
|
71
|
-
trap 'if [ -n "$SSR_PID" ]; then kill -KILL "$SSR_PID" 2>/dev/null || true; fi' EXIT
|
|
72
|
-
|
|
73
|
-
start_ssr
|
|
74
|
-
|
|
75
|
-
# shellcheck disable=SC2086
|
|
76
|
-
$WEB_CMD &
|
|
77
|
-
APP_PID=$!
|
|
78
|
-
|
|
79
|
-
elapsed=0
|
|
80
|
-
while [ "$shutting_down" -eq 0 ] && kill -0 "$APP_PID" 2>/dev/null; do
|
|
81
|
-
sleep 1
|
|
82
|
-
elapsed=$((elapsed + 1))
|
|
83
|
-
if [ "$shutting_down" -eq 0 ] && [ "$elapsed" -ge "$SSR_HEALTH_INTERVAL" ]; then
|
|
84
|
-
elapsed=0
|
|
85
|
-
check_ssr_health
|
|
86
|
-
fi
|
|
87
|
-
done
|
|
88
|
-
|
|
89
|
-
wait "$APP_PID"
|
|
90
|
-
APP_STATUS=$?
|
|
91
|
-
APP_PID=""
|
|
92
|
-
|
|
93
|
-
stop_ssr
|
|
94
|
-
exit "$APP_STATUS"
|