wurk 1.16.0 → 1.17.1

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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +3 -1
  3. data/app/controllers/concerns/wurk/same_origin_guard.rb +8 -39
  4. data/app/controllers/concerns/wurk/sse_streaming.rb +3 -38
  5. data/app/controllers/wurk/api_controller.rb +8 -642
  6. data/app/controllers/wurk/dashboard_controller.rb +5 -156
  7. data/app/controllers/wurk/extensions_controller.rb +5 -43
  8. data/app/controllers/wurk/profiles_controller.rb +4 -117
  9. data/lib/wurk/api/serializers.rb +2 -2
  10. data/lib/wurk/batch/server_middleware.rb +3 -3
  11. data/lib/wurk/component.rb +1 -0
  12. data/lib/wurk/engine.rb +3 -111
  13. data/lib/wurk/fetcher/private_list_key.rb +40 -8
  14. data/lib/wurk/fetcher/reaper.rb +12 -4
  15. data/lib/wurk/fetcher/unparseable_keys.rb +8 -9
  16. data/lib/wurk/finished_job_cleanup.rb +155 -0
  17. data/lib/wurk/job_retry.rb +2 -10
  18. data/lib/wurk/processor.rb +26 -47
  19. data/lib/wurk/redis_pool.rb +16 -1
  20. data/lib/wurk/unique_jobs_compat/private_list_digests.rb +121 -0
  21. data/lib/wurk/unique_jobs_compat.rb +87 -0
  22. data/lib/wurk/version.rb +1 -1
  23. data/lib/wurk/web/asset_mount.rb +119 -0
  24. data/lib/wurk/web/dashboard/api_actions.rb +657 -0
  25. data/lib/wurk/web/dashboard/controller.rb +146 -0
  26. data/lib/wurk/web/dashboard/endpoints.rb +92 -0
  27. data/lib/wurk/web/dashboard/extension_actions.rb +53 -0
  28. data/lib/wurk/web/dashboard/profile_actions.rb +130 -0
  29. data/lib/wurk/web/dashboard/routes.rb +134 -0
  30. data/lib/wurk/web/dashboard/shell.rb +181 -0
  31. data/lib/wurk/web/dashboard/stats_tick.rb +49 -0
  32. data/lib/wurk/web/dashboard/stream_concurrency_guard.rb +97 -0
  33. data/lib/wurk/web/rack_app.rb +27 -29
  34. data/lib/wurk/web/same_origin.rb +43 -0
  35. data/lib/wurk.rb +1 -0
  36. data/vendor/assets/dashboard/wurk-manifest.json +2 -2
  37. metadata +17 -4
  38. data/app/controllers/concerns/wurk/stream_concurrency_guard.rb +0 -94
  39. /data/{app/controllers/wurk/api → lib/wurk/web/dashboard}/pagination.rb +0 -0
  40. /data/{app/controllers/wurk/api → lib/wurk/web/dashboard}/serializers.rb +0 -0
@@ -1,173 +1,22 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'erb'
4
- require 'json'
5
- require 'net/http'
6
- require 'uri'
3
+ require 'wurk/web/dashboard/shell'
7
4
 
8
5
  module Wurk
9
- # Serves the SPA shell. Everything else is JSON from ApiController.
10
- #
11
- # Production: returns the precompiled index.html shipped in
12
- # vendor/assets/dashboard. The release pipeline (`frontend:build` →
13
- # `gem build`) writes both that file and the wurk-manifest.json validated
14
- # at engine boot.
15
- #
16
- # Development: when WURK_VITE_DEV=1 is set, fetches the shell from the
17
- # Vite dev server (default :5173) so contributors get HMR without
18
- # rebuilding the bundle on every change.
6
+ # Serves the SPA shell (Wurk::Web::Dashboard::Shell). Everything else is JSON
7
+ # from ApiController.
19
8
  class DashboardController < ApplicationController
20
- # bin/dev exports VITE_PORT and vite.config.ts binds it, with strictPort, so this
21
- # has to read the same variable or an overridden port answers every page with a 500.
22
- def self.vite_dev_url
23
- "http://localhost:#{ENV.fetch('VITE_PORT', '5173')}#{VITE_ASSET_BASE}"
24
- end
25
-
26
- # Vite serves the dev shell under its `base` (vite.config.ts), which is the
27
- # same path the engine mounts assets at — so derive these from
28
- # AssetMount::PREFIX to keep the Ruby side in lockstep. Fetching the server
29
- # root instead returns Vite's "did you mean /wurk-assets/" hint page, not the
30
- # shell (issue #181).
31
- VITE_ASSET_BASE = "#{::Wurk::Engine::AssetMount::PREFIX}/".freeze # "/wurk-assets/"
32
- INDEX_REL_PATH = ['vendor', 'assets', 'dashboard', 'index.html'].freeze
33
- # The SPA mount point, matched without its closing `>` so the locale hint
34
- # appends to whatever attributes the shell already carries.
35
- ROOT_DIV = '<div id="wurk-root"'
36
- # The theme hint's anchor. It is the one payload that has to land at the
37
- # *top* of <head> rather than before </head> with the others: the shell's
38
- # pre-paint script reads it, and that script runs before the stylesheet so
39
- # a host default never flashes the other palette.
40
- HEAD_OPEN = '<head>'
41
- # The built shell's asset URLs: Vite builds with a relative `base`
42
- # (frontend/vite.config.ts) so the bundle's own chunk and font URLs resolve
43
- # against wherever it is served from; only the shell needs an absolute
44
- # prefix, because it is served from the page URL, not the asset mount.
45
- RELATIVE_ASSET_URL = %r{(["'])\./}
46
- SCRIPT_OPEN = '<script'
47
-
48
9
  def index
49
- render layout: false, html: decorate_shell(spa_html).html_safe
10
+ render layout: false, html: ::Wurk::Web::Dashboard::Shell.new(request, asset_base: asset_base).html.html_safe
50
11
  end
51
12
 
52
13
  private
53
14
 
54
- def decorate_shell(html)
55
- stamp_csp_nonce(inject_theme_default(inject_locale_hint(inject_head(html))))
56
- end
57
-
58
- # A host policy with a nonce generator (`script-src 'self' 'nonce-…'`)
59
- # refuses every inline script without the request's nonce, and the shell
60
- # cannot run without its injected mount base. Every <script> gets it, the
61
- # external module included, so a `'strict-dynamic'` policy loads it too.
62
- def stamp_csp_nonce(html)
63
- nonce = request.content_security_policy_nonce
64
- return html unless nonce
65
-
66
- html.gsub(SCRIPT_OPEN) { %(#{SCRIPT_OPEN} nonce="#{::ERB::Util.html_escape(nonce)}") }
67
- end
68
-
69
- def spa_html
70
- ENV['WURK_VITE_DEV'] == '1' ? fetch_vite_dev_shell : read_built_index
71
- end
72
-
73
- # Block form deliberately: a string replacement would interpret `\0`/`\&`
74
- # backreferences inside the host-configured JSON these scripts carry.
75
- def inject_head(html)
76
- html.sub('</head>') { "#{mount_base_script}#{host_translations_script}</head>" }
77
- end
78
-
79
- # The SPA is mount-agnostic: it reads window.__WURK_BASE__ to build every API
80
- # URL and its client-router base, so the same precompiled bundle works whether
81
- # the host mounts the engine at /wurk, /sidekiq, or /admin/jobs. script_name
82
- # is the mount prefix ("/sidekiq"), or "" at the app root. Injected into every
83
- # served shell (built and Vite-dev) so a non-/wurk mount needs no rebuild.
84
- def mount_base_script
85
- base = request.script_name.to_s.chomp('/')
86
- %(<script>window.__WURK_BASE__ = #{json_literal(base)};</script>\n )
87
- end
88
-
89
- # Host copy overrides (Wurk::Web.config.translations), read once at SPA boot
90
- # by loadHostOverrides() in frontend/src/i18n/index.ts and deep-merged over
91
- # the shipped bundle for the locale in use.
92
- def host_translations_script
93
- overrides = ::Wurk::Web.config.translations
94
- return '' unless overrides.is_a?(::Hash) && !overrides.empty?
95
-
96
- %(<script type="application/json" id="wurk-i18n">#{json_literal(overrides)}</script>\n )
97
- end
98
-
99
- # First-paint language hint, third in the SPA's precedence chain (`?locale=`
100
- # and a stored pick both outrank it), so it only decides the render for a
101
- # visitor who has never chosen. The negotiator returns a tag from the host's
102
- # offered list or nothing — request text never reaches the attribute — and
103
- # no hint at all is the right answer for an unrecognized language: the SPA
104
- # then falls through to navigator.languages.
105
- def inject_locale_hint(html)
106
- locale = negotiated_locale
107
- return html unless locale
108
-
109
- html.sub(ROOT_DIV) { %(#{ROOT_DIV} data-locale="#{::ERB::Util.html_escape(locale)}") }
110
- end
111
-
112
- # First-paint theme default (Wurk::Web.config.default_theme), last in the
113
- # SPA's precedence chain behind a stored pick — so it only decides the
114
- # palette for a visitor who has never chosen one. No config emits nothing
115
- # and leaves the SPA on 'system', which follows the visitor's OS.
116
- def inject_theme_default(html)
117
- theme = ::Wurk::Web.config.default_theme
118
- return html unless theme
119
-
120
- script = %(<script>window.__WURK_THEME__ = #{json_literal(theme)};</script>)
121
- html.sub(HEAD_OPEN) { "#{HEAD_OPEN}\n #{script}" }
122
- end
123
-
124
- def negotiated_locale
125
- config = ::Wurk::Web.config
126
- header = request.get_header('HTTP_ACCEPT_LANGUAGE')
127
- ::Wurk::Web::LocaleNegotiator.call(header, offered: config.offered_locales) || config.default_locale
128
- end
129
-
130
- # JSON-encode a value as a literal inside <script>, escaping the sequences
131
- # that could otherwise break out of the tag. Both payloads are
132
- # host-configured, not request input, but the injection stays safe regardless.
133
- def json_literal(value)
134
- value.to_json.gsub(/[<>&]/) { |c| format('\u%04x', c.ord) }
135
- end
136
-
137
- def fetch_vite_dev_shell
138
- uri = ::URI.parse(self.class.vite_dev_url)
139
- rewrite_dev_asset_urls(::Net::HTTP.get(uri))
140
- rescue ::StandardError => e
141
- raise "Wurk dashboard: cannot reach Vite dev server at #{self.class.vite_dev_url} " \
142
- "(#{e.class}: #{e.message}). Run `bin/rake frontend:dev` from the gem root, or `bin/dev`, " \
143
- 'with the same VITE_PORT.'
144
- end
145
-
146
- # The shell's entry URLs (`src="/wurk-assets/@vite/client"`,
147
- # `src="/wurk-assets/src/main.tsx"`) are base-absolute, but the page is
148
- # served from the host origin (e.g. :3000), where that path only maps to the
149
- # built bundle. Point them back at the Vite dev server so the browser loads
150
- # the modules + HMR client straight from Vite (CORS-enabled in dev). Vite's
151
- # `server.origin` covers runtime-generated asset URLs but not these entry
152
- # tags, so rewrite them here.
153
- def rewrite_dev_asset_urls(html)
154
- html.gsub(/(["'])#{::Regexp.escape(VITE_ASSET_BASE)}/, "\\1#{self.class.vite_dev_url}")
155
- end
156
-
157
- def read_built_index
158
- path = ::Wurk::Engine.root.join(*INDEX_REL_PATH)
159
- unless path.exist?
160
- raise "Wurk dashboard: precompiled SPA index.html missing at #{path}. " \
161
- 'Run `bin/rake frontend:build`.'
162
- end
163
- path.read.gsub(RELATIVE_ASSET_URL) { "#{::Regexp.last_match(1)}#{asset_base}/" }
164
- end
165
-
166
15
  # AssetMount sits in the host's stack, so its URL carries the host's own
167
16
  # prefix (RAILS_RELATIVE_URL_ROOT, or a proxy's SCRIPT_NAME), not the
168
17
  # engine mount: `/app/wurk` serves its assets from `/app/wurk-assets`.
169
18
  def asset_base
170
- "#{request.get_header('ORIGINAL_SCRIPT_NAME').to_s.chomp('/')}#{::Wurk::Engine::AssetMount::PREFIX}"
19
+ "#{request.get_header('ORIGINAL_SCRIPT_NAME').to_s.chomp('/')}#{::Wurk::Web::AssetMount::PREFIX}"
171
20
  end
172
21
  end
173
22
  end
@@ -1,53 +1,15 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'wurk/web/extension'
3
+ require 'wurk/web/dashboard/extension_actions'
4
4
 
5
5
  module Wurk
6
- # Serves third-party Web extensions (#187): `ext/:name/*subpath` runs the
7
- # registered extension's matched route and returns its rendered HTML for the
8
- # SPA's Extension page to embed; `ext-assets/:name/*file` serves files from
9
- # the extension's `asset_paths`.
10
- #
11
- # Inherits DashboardController so an /ext/* URL that is actually the SPA's
12
- # client-side route (no extension registered under that name — e.g. a browser
13
- # refresh on /wurk/ext/<tab>/) falls through to the SPA shell instead of 404.
6
+ # The engine's transport for third-party Web extensions
7
+ # (Wurk::Web::Dashboard::ExtensionActions). Inherits DashboardController for
8
+ # the shell an /ext URL that is the SPA's own client route falls back to.
14
9
  class ExtensionsController < DashboardController
15
10
  # Extension forms carry no Rails CSRF token — SameOriginGuard supplies
16
11
  # Sidekiq's same-origin CSRF defense (spec §25.1) in its place.
17
12
  include SameOriginGuard
18
-
19
- def show
20
- result = Web::Extension::Renderer.call(
21
- name: params[:name], method: request.request_method,
22
- subpath: "/#{params[:subpath]}", env: request.env, mount: request.script_name
23
- )
24
- return index unless result # not an extension → SPA client route; let the SolidJS router handle it
25
-
26
- respond_with(result)
27
- end
28
-
29
- def asset
30
- file, cache_for = Web::Extension::Renderer.asset_file(params[:name], params[:file])
31
- return head :not_found unless file
32
-
33
- response.headers['Cache-Control'] = "public, max-age=#{cache_for}"
34
- send_file file, disposition: 'inline'
35
- end
36
-
37
- private
38
-
39
- def respond_with((status, headers, body))
40
- return redirect_to(headers['Location'], allow_other_host: false) if status == 302 && headers['Location']
41
-
42
- content_type = 'text/html; charset=utf-8'
43
- headers.each do |key, value|
44
- next content_type = value if key.casecmp?('content-type')
45
-
46
- response.headers[key] = value
47
- end
48
- # Extension output is host-registered server code, same trust model as
49
- # Sidekiq::Web rendering its extensions — not user input.
50
- render body: body, content_type: content_type, status: status
51
- end
13
+ include ::Wurk::Web::Dashboard::ExtensionActions
52
14
  end
53
15
  end
@@ -1,127 +1,14 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'net/http'
4
- require 'uri'
3
+ require 'wurk/web/dashboard/profile_actions'
5
4
 
6
5
  module Wurk
7
- # Profiles pane non-JSON endpoints (spec §25.4):
8
- #
9
- # GET /profiles/:key/data → the stored gzipped gecko JSON, streamed with a
10
- # gzip Content-Encoding (Firefox profiler pulls
11
- # this when given a `from-url` source).
12
- # POST /profiles/:key → upload the profile to the Firefox profiler
13
- # store and 302 to its public view URL.
14
- # GET /profiles/:key → 302 to an upload already made (by either UI),
15
- # 405 when there is none yet.
16
- #
17
- # Sidekiq uploads on the GET. Sending job data to a third party is a side
18
- # effect, so here only a POST does it: SameOriginGuard covers it like every
19
- # other mutation, and read-only mode refuses it (#101 W5).
20
- #
21
- # `:key` is "<token>-<jid>". The JSON list lives at /api/profiles.
22
- #
23
- # `:key` is request input that is otherwise used verbatim as a Redis key, so
24
- # every action first requires it to be a member of the `profiles` ZSET
25
- # (where both Wurk and Sidekiq register each stored profile). Without that,
26
- # a non-HASH key WRONGTYPEs into a false "redis_unavailable" 503, and any
27
- # HASH with a `data` field could be shipped to the profiler and have a `sid`
28
- # written into it.
6
+ # The engine's transport for the profile routes
7
+ # (Wurk::Web::Dashboard::ProfileActions).
29
8
  class ProfilesController < ApplicationController
30
9
  include SameOriginGuard
10
+ include ::Wurk::Web::Dashboard::ProfileActions
31
11
 
32
12
  before_action :require_listed_profile
33
-
34
- def data
35
- blob = profile_blob(params[:key])
36
- return head(:not_found) unless blob
37
-
38
- response.headers['Content-Encoding'] = 'gzip'
39
- send_data blob, type: 'application/json', disposition: 'inline'
40
- end
41
-
42
- def show
43
- return head(:forbidden) if ::Wurk::Web.config.read_only?
44
-
45
- sid = cached_sid(params[:key])
46
- return redirect_to_profile(sid) if sid
47
-
48
- response.headers['Allow'] = 'POST'
49
- head :method_not_allowed
50
- end
51
-
52
- # Read-only mode 403s this POST in Wurk::Web::Authorization, before it
53
- # gets here.
54
- def upload
55
- sid = profile_sid(params[:key])
56
- return head(:not_found) if sid == :missing
57
- return head(:bad_gateway) unless sid
58
-
59
- redirect_to_profile(sid)
60
- end
61
-
62
- private
63
-
64
- def redirect_to_profile(sid)
65
- redirect_to(format(::Wurk::Web.config.profile_view_url, sid), allow_other_host: true)
66
- end
67
-
68
- # The member's score is its expiry, the same instant the HASH's TTL lapses;
69
- # ProfileSet purges expired members lazily, so a past score is gone too.
70
- def require_listed_profile
71
- expires_at = ::Wurk.redis { |c| c.call('ZSCORE', ::Wurk::Keys::PROFILES, params[:key].to_s) }
72
- head(:not_found) unless expires_at && Float(expires_at) > ::Time.now.to_f
73
- end
74
-
75
- def cached_sid(key) = ::Wurk.redis { |c| c.call('HGET', key, 'sid') }
76
-
77
- def profile_blob(key)
78
- ::Wurk::ProfileRecord.data_for(key)
79
- end
80
-
81
- # The profile-store id, cached in the HASH's `sid` field after the first
82
- # upload exactly as Sidekiq's Web UI does, so either UI reuses the other's
83
- # upload. :missing when the profile is gone, nil when the upload failed.
84
- def profile_sid(key)
85
- sid = cached_sid(key)
86
- return sid if sid
87
-
88
- blob = profile_blob(key)
89
- return :missing unless blob
90
-
91
- sid = upload_to_profiler(blob)
92
- ::Wurk.redis { |c| c.call('HSET', key, 'sid', sid) } if sid
93
- sid
94
- end
95
-
96
- # POSTs the gzipped profile to the Firefox profiler's compressed-store,
97
- # which answers with a JWT whose payload carries the `profileToken` the
98
- # view URL needs. Returns that token, or nil on failure.
99
- def upload_to_profiler(gzipped)
100
- uri = URI.parse(::Wurk::Web.config.profile_store_url)
101
- res = post_gzip(uri, gzipped)
102
- res.is_a?(Net::HTTPSuccess) ? profile_token(res.body.to_s) : nil
103
- rescue StandardError => e
104
- Wurk.configuration.handle_exception(e, context: 'Wurk::ProfilesController#upload')
105
- nil
106
- end
107
-
108
- def profile_token(jwt)
109
- payload = jwt.strip.split('.')[1].to_s.tr('-_', '+/')
110
- ::JSON.parse(payload.unpack1('m'))['profileToken']
111
- end
112
-
113
- def post_gzip(uri, body)
114
- req = Net::HTTP::Post.new(uri)
115
- req['Content-Encoding'] = 'gzip'
116
- req['Content-Type'] = 'application/json'
117
- req['Accept'] = 'application/vnd.firefox-profiler+json;version=1.0'
118
- req.body = body
119
- # Explicit timeouts so a slow/unreachable profiler can't tie up the Rails
120
- # request thread for Ruby's ~60s defaults.
121
- Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
122
- open_timeout: 5, read_timeout: 15) do |http|
123
- http.request(req)
124
- end
125
- end
126
13
  end
127
14
  end
@@ -10,9 +10,9 @@ module Wurk
10
10
  # JobRecord, SortedEntry — so the API and the dashboard cannot report
11
11
  # different numbers for the same Redis. Only the shape differs, and it
12
12
  # differs on purpose: the dashboard's serializers
13
- # (app/controllers/wurk/api/serializers.rb) answer to the SPA and change
13
+ # (lib/wurk/web/dashboard/serializers.rb) answer to the SPA and change
14
14
  # whenever it does, and they reach into Wurk::Web for host-registered
15
- # extension rows — an engine dependency the API cannot take, because it
15
+ # extension rows — a dashboard dependency the API cannot take, because it
16
16
  # also runs standalone. Under /v1 these field names are a contract.
17
17
  module Serializers
18
18
  # Three missed beats at {Wurk::Heartbeat::BEAT_PAUSE} cadence, which is
@@ -23,9 +23,9 @@ module Wurk
23
23
  # The success ack runs outside the job's rescue: once `perform` returned,
24
24
  # nothing the batch bookkeeping raises may be mistaken for the job failing,
25
25
  # or a job that already did its work is retried and runs twice. The ack
26
- # itself is retried in-process and only raises (sending the job to retry,
27
- # at-least-once) when Redis stays unreachable — a jid left in the live set
28
- # would hold the batch open forever. The fire after it never raises: it is
26
+ # itself is retried in-process; when Redis stays unreachable it raises and
27
+ # the Processor hands the ack to FinishedJobCleanup, which sends it once
28
+ # Redis answers, without running the job again. The fire after it never raises: it is
29
29
  # re-driven in-process and then reported to the error handlers. Both wait
30
30
  # out a store that is not serving (Callbacks::STORE_OUTAGE_BUDGET): once
31
31
  # this job is ACKed nothing re-drives a fire that gave up.
@@ -170,6 +170,7 @@ module Wurk
170
170
  # `reraise: true` (used in tests / fail-fast boot). `oneshot: true`
171
171
  # clears the bucket after dispatch so the event can't fire twice.
172
172
  def fire_event(event, oneshot: true, reverse: false, reraise: false)
173
+ UniqueJobsCompat.install if event == :startup
173
174
  bucket = config[:lifecycle_events][event]
174
175
  return if bucket.nil? || bucket.empty?
175
176
 
data/lib/wurk/engine.rb CHANGED
@@ -3,6 +3,7 @@
3
3
  require 'rails/engine'
4
4
  require_relative '../active_job/queue_adapters/wurk_adapter'
5
5
  require_relative 'dashboard_manifest'
6
+ require_relative 'web/asset_mount'
6
7
 
7
8
  module Wurk
8
9
  # Rails mountable engine. Owns the dashboard mount, the asset path for
@@ -15,118 +16,9 @@ module Wurk
15
16
  g.test_framework :minitest, fixtures: false
16
17
  end
17
18
 
18
- # Rack::Files doesn't strip the URL prefix before file lookup, so
19
- # `/wurk-assets/assets/foo.js` would resolve under `vendor/assets/dashboard/
20
- # wurk-assets/assets/foo.js` — a path that doesn't exist. AssetMount
21
- # rewrites PATH_INFO to drop the `/wurk-assets` prefix before delegating
22
- # to Rack::Files, then falls through to the next middleware on 404 so
23
- # host-app routes outside the mount keep working.
24
- class AssetMount
25
- PREFIX = '/wurk-assets'
26
-
27
- # Vite fingerprints everything it emits into `assets/`
28
- # (`Dashboard-cGKycyd0.js`), so the bytes behind one of those URLs can
29
- # never change — cache them for a year and never revalidate. The rest of
30
- # the bundle (index.html, the favicons, wurk-manifest.json,
31
- # .vite/manifest.json) keeps a stable name across builds, so it must be
32
- # revalidated or a client would pin a stale dashboard shell forever.
33
- FINGERPRINTED_PREFIX = '/assets/'
34
- IMMUTABLE_CACHE_CONTROL = 'public, max-age=31536000, immutable'
35
- REVALIDATE_CACHE_CONTROL = 'public, no-cache'
36
-
37
- # Only a served body gets a cache directive. Rack::Files answers more than
38
- # file reads: OPTIONS with 200 + Allow, 405 for any other verb
39
- # (`ALLOWED_VERBS = %w[GET HEAD OPTIONS]`), and 416 for an unsatisfiable
40
- # Range. 405 is cacheable by default (RFC 9110 §15.5.6), so stamping it
41
- # `immutable` would let a shared proxy serve "method not allowed" for a
42
- # year to everyone behind it.
43
- CACHEABLE_METHODS = %w[GET HEAD].freeze
44
- CACHEABLE_STATUSES = [200, 206, 304].freeze
45
-
46
- # `rake frontend:build` writes a .br and a .gz next to each fingerprinted
47
- # text asset (frontend/vite.config.ts, wurk-precompress). The mount sits
48
- # ahead of any deflater the host runs, so without these the dashboard
49
- # went out uncompressed. Preference order when the client's q-values tie.
50
- ENCODINGS = { 'br' => '.br', 'gzip' => '.gz' }.freeze
51
- OFFERED_ENCODINGS = [*ENCODINGS.keys, 'identity'].freeze
52
- PRECOMPRESSED = /\.(?:js|css|svg|json)\z/
53
-
54
- def initialize(app, root:)
55
- @app = app
56
- @files = ::Rack::Files.new(root)
57
- end
58
-
59
- def call(env)
60
- path = env[::Rack::PATH_INFO]
61
- return @app.call(env) unless path == PREFIX || path.start_with?("#{PREFIX}/")
62
-
63
- inner = env.dup
64
- stripped = path.delete_prefix(PREFIX)
65
- inner[::Rack::PATH_INFO] = stripped.empty? ? '/' : stripped
66
- response = precompressed(inner, env, stripped) || @files.call(inner)
67
- return @app.call(env) if response[0] == 404
68
-
69
- stamp_cache_headers(response, env, stripped)
70
- response
71
- end
72
-
73
- private
74
-
75
- # The variant the client accepts and the build wrote, served with the
76
- # original's content type; nil sends the identity file. A Range request
77
- # gets identity so byte offsets mean what the client thinks they mean.
78
- def precompressed(inner, env, stripped)
79
- return unless CACHEABLE_METHODS.include?(env[::Rack::REQUEST_METHOD])
80
- return unless precompressible?(stripped)
81
- return if env['HTTP_RANGE']
82
-
83
- encoding = negotiated_encoding(env)
84
- return unless encoding
85
-
86
- variant = @files.call(inner.merge(::Rack::PATH_INFO => "#{stripped}#{ENCODINGS[encoding]}"))
87
- return unless variant[0] == 200
88
-
89
- variant[1]['content-type'] = ::Rack::Mime.mime_type(::File.extname(stripped))
90
- variant[1]['content-encoding'] = encoding
91
- variant
92
- end
93
-
94
- # 'br', 'gzip', or nil for identity (no header, or every coding refused).
95
- def negotiated_encoding(env)
96
- accepted = ::Rack::Utils.q_values(env['HTTP_ACCEPT_ENCODING'].to_s)
97
- encoding = ::Rack::Utils.select_best_encoding(OFFERED_ENCODINGS, accepted)
98
- encoding if ENCODINGS.key?(encoding)
99
- end
100
-
101
- def precompressible?(stripped)
102
- stripped.start_with?(FINGERPRINTED_PREFIX) && stripped.match?(PRECOMPRESSED)
103
- end
104
-
105
- # This mount is inserted at index 0 of the HOST app's stack (see the
106
- # initializer below), so Rack::ETag and Rack::ConditionalGet never see
107
- # these responses — without this the dashboard's fingerprinted bundle
108
- # shipped with no cache directive at all and was refetched every load.
109
- #
110
- # Vary goes on every answer for a path that has variants, identity
111
- # included, or a shared cache could hand gzip to a client that can't
112
- # read it.
113
- def stamp_cache_headers(response, env, stripped)
114
- response[1]['vary'] = 'accept-encoding' if precompressible?(stripped)
115
- return unless CACHEABLE_METHODS.include?(env[::Rack::REQUEST_METHOD])
116
- return unless CACHEABLE_STATUSES.include?(response[0])
117
-
118
- response[1]['cache-control'] ||=
119
- if stripped.start_with?(FINGERPRINTED_PREFIX)
120
- IMMUTABLE_CACHE_CONTROL
121
- else
122
- REVALIDATE_CACHE_CONTROL
123
- end
124
- end
125
- end
126
-
127
19
  # Precompiled SPA lives in vendor/assets/dashboard; the engine serves
128
20
  # those files as static assets under the /wurk-assets mount point via
129
- # AssetMount (above).
21
+ # Wurk::Web::AssetMount (lib/wurk/web/asset_mount.rb).
130
22
  #
131
23
  # Deliberately unauthenticated: this middleware is inserted straight into
132
24
  # the *host app's* middleware stack (`app.middleware`), not the engine's
@@ -148,7 +40,7 @@ module Wurk
148
40
  # omits it — insert_before(Static) would crash the host app's boot.
149
41
  app.middleware.insert_before(
150
42
  0,
151
- ::Wurk::Engine::AssetMount,
43
+ ::Wurk::Web::AssetMount,
152
44
  root: assets_path.to_s
153
45
  )
154
46
  end
@@ -4,19 +4,51 @@ require_relative '../keys'
4
4
 
5
5
  module Wurk
6
6
  class Fetcher
7
- # Reads the owner back out of a reliable-fetch private list key
8
- # (`queue:<public>|<host>|<pid>|<nonce>|<idx>`, see
9
- # Reliable.private_queue_name) for the Reaper's liveness check. Pure string
10
- # work, no Redis.
7
+ # Reads the owner back out of a reliable-fetch private list key for the
8
+ # Reaper's liveness check: Wurk's `queue:<public>|<host>|<pid>|<nonce>|<idx>`
9
+ # (Reliable.private_queue_name) or Sidekiq Pro's
10
+ # `queue:sq|<host>:<pid>:<nonce>|<public>` (SuperFetch#private_queue). Pure
11
+ # string work, no Redis.
11
12
  module PrivateListKey
12
13
  # The nonce shape Component::PROCESS_NONCE writes (`SecureRandom.hex(6)`).
13
14
  NONCE_PATTERN = /\A[0-9a-f]{12}\z/
14
15
 
16
+ PRO_PREFIX = "#{Keys::QUEUE_PREFIX}sq|".freeze
17
+ # Rebuilt byte for byte into the heartbeat key the liveness check reads,
18
+ # so a pid that would not round-trip through Integer is refused.
19
+ PRO_IDENTITY = /\A(.+):([1-9]\d*):([0-9a-f]{12})\z/
20
+ PRO_QUEUE = /\A[^|]+(?:\|[^|]+)*\z/
21
+
15
22
  module_function
16
23
 
17
- # `queue:<public>|<host>|<pid>|<nonce>|<idx>` → [public_q, host, pid,
18
- # nonce], parsed from the right so a `|` inside the queue name is
19
- # tolerated. nil when the key isn't a well-formed private list.
24
+ # [public_q, host, pid, nonce], or nil when the key isn't a well-formed
25
+ # private list.
26
+ #
27
+ # A key that reads as both Pro's and Wurk's is refused: the two name
28
+ # different owners, and judging the wrong one dead would drain a live
29
+ # owner's list. It stays put and the Reaper reports it.
30
+ def parse_full(key)
31
+ return unless key.valid_encoding?
32
+
33
+ pro = parse_pro(key)
34
+ wurk = parse_wurk(key)
35
+ pro && wurk ? nil : pro || wurk
36
+ end
37
+
38
+ # `queue:sq|<identity>|<public>`. Everything after the identity is the
39
+ # queue, so a `|` inside its name is kept.
40
+ def parse_pro(key)
41
+ return unless key.start_with?(PRO_PREFIX)
42
+
43
+ identity, queue = key.delete_prefix(PRO_PREFIX).split('|', 2)
44
+ owner = PRO_IDENTITY.match(identity.to_s)
45
+ return unless owner && queue&.match?(PRO_QUEUE)
46
+
47
+ ["#{Keys::QUEUE_PREFIX}#{queue}", owner[1], owner[2].to_i, owner[3]]
48
+ end
49
+
50
+ # `queue:<public>|<host>|<pid>|<nonce>|<idx>`, parsed from the right so a
51
+ # `|` inside the queue name is tolerated.
20
52
  #
21
53
  # With no known prefix to split on, both owner shapes are tried in
22
54
  # preference order and the first one leaving a real public queue behind
@@ -27,7 +59,7 @@ module Wurk
27
59
  # pipe and puts the real pid in the nonce slot (pipe-bearing queue).
28
60
  # Both misreads are refused: the leftover must be a real queue name and
29
61
  # the pseudo-nonce must be nonce-shaped (see wide_tail).
30
- def parse_full(key)
62
+ def parse_wurk(key)
31
63
  parts = key.split('|')
32
64
  owner_tails(parts).each do |host, pid, nonce, width|
33
65
  public_q = parts[0...-width].join('|')
@@ -229,9 +229,9 @@ module Wurk
229
229
  end
230
230
 
231
231
  # Yields private_list_key, [public_q, host, pid, nonce] for every list.
232
- # MATCH `queue:*|*` matches only private lists (public queue
233
- # keys carry no `|`); PrivateListKey.parse_full drops anything that isn't a
234
- # well-formed `queue:<public>|<host>|<pid>|<nonce>|<idx>`.
232
+ # MATCH `queue:*|*` also matches a public queue with `|` in its name
233
+ # (#public_queue?); PrivateListKey.parse_full drops anything that is not
234
+ # a well-formed Wurk or Sidekiq Pro private list.
235
235
  def each_private_list
236
236
  cursor = '0'
237
237
  loop do
@@ -275,11 +275,19 @@ module Wurk
275
275
  @grace.forget(key)
276
276
  return false
277
277
  end
278
- return false if @grace.recent?(key, owner)
278
+ return false if public_queue?(key) || @grace.recent?(key, owner)
279
279
 
280
280
  owner_gone?(host, pid, nonce)
281
281
  end
282
282
 
283
+ # A public queue's own name can read as a private list. It has no owner to
284
+ # be dead, and draining it would move its waiting jobs to another queue.
285
+ def public_queue?(key)
286
+ redis(idempotent: true) do |c|
287
+ c.call('SISMEMBER', Keys::QUEUES_SET, key.delete_prefix(Keys::QUEUE_PREFIX))
288
+ end == 1
289
+ end
290
+
283
291
  def owner_key(host, pid, nonce)
284
292
  nonce ? "#{host}:#{pid}:#{nonce}" : "#{host}:#{pid}"
285
293
  end