Skip to content

Fix #2607: align Pro worker-count env var naming#2611

Merged
justin808 merged 10 commits intomainfrom
jg-codex/issue-2607-workers-env-var
Mar 18, 2026
Merged

Fix #2607: align Pro worker-count env var naming#2611
justin808 merged 10 commits intomainfrom
jg-codex/issue-2607-workers-env-var

Conversation

@justin808
Copy link
Copy Markdown
Member

@justin808 justin808 commented Mar 15, 2026

Summary

  • make generated Pro use as canonical env var
  • keep backward-compatible fallback to
  • update docs/examples to match canonical naming and mention legacy fallback

Why

Issue #2607 reported naming drift between generated template and runtime/docs conventions. This change removes the mismatch while preserving compatibility for existing deployments.

Testing

  • Run options: include {focus: true, locations: {"./react_on_rails/spec/react_on_rails/generators/install_generator_spec.rb" => [1173, 1405]}}
    ..

Finished in 1 minute 5.27 seconds (files took 1.77 seconds to load)
2 examples, 0 failures

Run options: --seed 59137

Running:

Finished in 0.000702s, 0.0000 runs/s, 0.0000 assertions/s.

0 runs, 0 assertions, 0 failures, 0 errors, 0 skips


Note

Low Risk
Low risk: changes are limited to worker-count env var parsing/precedence plus docs and generator template updates; runtime behavior only differs when env values are invalid/blank or when CI defaults previously overrode an explicit worker count.

Overview
Aligns Pro Node Renderer worker-count configuration around RENDERER_WORKERS_COUNT as the canonical env var, while keeping backward-compatible fallback to legacy NODE_RENDERER_CONCURRENCY in generated node-renderer.js templates and quick-start docs.

Adds parseWorkersCount (with tests) to validate/normalize worker-count inputs (supports 0 for single-process mode, ignores invalid values with a warning), and updates the CI defaulting logic to apply workersCount=2 only when no explicit override is provided. Documentation and README examples are updated to reflect the new precedence and behavior.

Written by Cursor Bugbot for commit 1a71dee. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

  • Enhancements

    • Worker count resolution now validates and accepts explicit 0 or positive integers, prefers the new renderer env, falls back to the legacy concurrency env, defaults to 3, and remains 2 in CI.
    • Renderer config access unified via an environment alias for clearer configuration.
  • Documentation

    • Clarified precedence, validation, legacy fallback and single-process (0) behavior; updated quick reference formatting and troubleshooting guidance.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 15, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Node renderer now parses worker counts via a new helper: primary RENDERER_WORKERS_COUNT, fallback NODE_RENDERER_CONCURRENCY, then default 3. Invalid inputs return null to allow fallback; CI still forces workersCount to 2. Documentation and minor formatting/directive presentation updated.

Changes

Cohort / File(s) Summary
Documentation
docs/oss/getting-started/pro-quick-start.md, packages/react-on-rails-pro-node-renderer/README.md, docs/README.md, docs/oss/migrating/rsc-troubleshooting.md
Updated docs to reference RENDERER_WORKERS_COUNT as primary env var, clarified legacy NODE_RENDERER_CONCURRENCY support, adjusted formatting and altered two occurrences of the 'use client' directive presentation.
Node Renderer Template
react_on_rails/lib/generators/react_on_rails/templates/pro/base/client/node-renderer.js
Added parseWorkersCount(value) to validate/normalize worker counts; replaced direct env parsing with parseWorkersCount(env.RENDERER_WORKERS_COUNT) ?? parseWorkersCount(env.NODE_RENDERER_CONCURRENCY) ?? 3; retained CI override to 2 and documented single-process (0) option.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 I hop through envs, sniffing each name,
RENDERER first, then an old flame.
If numbers fail or none apply,
Three carrots wait beneath the sky.
CI taps two—off we go, nimble and spry. 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: aligning Pro worker-count environment variable naming by standardizing on RENDERER_WORKERS_COUNT while maintaining backward compatibility with NODE_RENDERER_CONCURRENCY.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jg-codex/issue-2607-workers-env-var
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Comment thread docs/oss/getting-started/pro-quick-start.md Outdated
@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 15, 2026

Review: Fix #2607 – align Pro worker-count env var naming

Overall the change is clean and the backward-compatibility story is solid. A couple of issues worth addressing:


1. || 3 in the docs snippet silently swallows an explicit 0

See the inline comment on pro-quick-start.md:126. The generated template correctly handles this with a nested ternary, but the docs snippet uses Number(... ?? ...) || 3, which converts 0 back to the default 3. Keeping the two implementations inconsistent is a latent footgun for anyone who copies the docs example directly.


2. Generator spec should assert the canonical env var names

react_on_rails/spec/react_on_rails/generators/install_generator_spec.rb (lines 1173–1182) only checks expect(content).to include("workersCount:"). That assertion wouldn't have caught the original naming drift in issue #2607, and it won't catch a future rename either.

Suggested additions to the "creates node-renderer.js bootstrap file" example:

expect(content).to include("RENDERER_WORKERS_COUNT")
expect(content).to include("NODE_RENDERER_CONCURRENCY")

3. Minor – README wording could be clearer

packages/react-on-rails-pro-node-renderer/README.md:103 now reads:

Legacy NODE_RENDERER_CONCURRENCY is still supported in generated templates.

The phrase "in generated templates" implies the legacy var is only honored when using the generator, but users who hand-wrote their node-renderer.js will also benefit if they use the pattern shown in the docs. Something like "Legacy NODE_RENDERER_CONCURRENCY is still honored as a fallback" would be less ambiguous.


No security or performance concerns. The logic change is correct and the risk is low as stated.

@greptile-apps
Copy link
Copy Markdown

greptile-apps Bot commented Mar 15, 2026

Greptile Summary

This PR standardizes the worker-count env var naming for the Pro Node Renderer. The generated template (node-renderer.js) now uses RENDERER_WORKERS_COUNT as the canonical env var (consistent with the RENDERER_* convention used by all other renderer settings) and falls back to the legacy NODE_RENDERER_CONCURRENCY for backward compatibility. Docs and README are updated accordingly.

  • The template's fallback logic uses a clear ternary chain with != null checks, correctly handling all edge cases
  • The runtime library (configBuilder.ts) already reads only RENDERER_WORKERS_COUNT; the legacy fallback exists solely in the generated template for existing deployments
  • Note: docs/pro/installation.md (line 256) still references only NODE_RENDERER_CONCURRENCY without the new canonical var — a follow-up update may be needed there

Confidence Score: 5/5

  • This PR is safe to merge — it's a straightforward env var naming alignment with proper backward compatibility.
  • All changes are documentation and template updates with no runtime library modifications. The fallback logic preserves backward compatibility. Tests pass. The change is small, well-scoped, and aligns with existing conventions.
  • No files require special attention. Optionally, docs/pro/installation.md (not in this PR) could be updated for full consistency.

Important Files Changed

Filename Overview
react_on_rails/lib/generators/react_on_rails/templates/pro/base/client/node-renderer.js Correctly refactored to use RENDERER_WORKERS_COUNT as canonical env var with backward-compatible fallback to NODE_RENDERER_CONCURRENCY using a clear ternary chain.
docs/oss/getting-started/pro-quick-start.md Docs snippet updated with legacy fallback using ?? and `
packages/react-on-rails-pro-node-renderer/README.md Configuration table description updated to clarify legacy NODE_RENDERER_CONCURRENCY support in generated templates. Accurate and clear.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["workersCount resolution"] --> B{"RENDERER_WORKERS_COUNT\nset?"}
    B -- "Yes" --> C["Use Number(RENDERER_WORKERS_COUNT)"]
    B -- "No" --> D{"NODE_RENDERER_CONCURRENCY\nset? (legacy)"}
    D -- "Yes" --> E["Use Number(NODE_RENDERER_CONCURRENCY)"]
    D -- "No" --> F["Default: 3"]
    G["CI environment?"] --> H{"env.CI truthy?"}
    H -- "Yes" --> I["Override: workersCount = 2"]
    H -- "No" --> J["Keep resolved value"]
Loading

Last reviewed commit: 960a39e

Comment thread docs/oss/getting-started/pro-quick-start.md Outdated
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Mar 15, 2026

size-limit report 📦

Path Size
react-on-rails/client bundled (gzip) 62.63 KB (0%)
react-on-rails/client bundled (gzip) (time) 62.63 KB (0%)
react-on-rails/client bundled (brotli) 53.74 KB (0%)
react-on-rails/client bundled (brotli) (time) 53.74 KB (0%)
react-on-rails-pro/client bundled (gzip) 63.65 KB (0%)
react-on-rails-pro/client bundled (gzip) (time) 63.65 KB (0%)
react-on-rails-pro/client bundled (brotli) 54.68 KB (0%)
react-on-rails-pro/client bundled (brotli) (time) 54.68 KB (0%)
registerServerComponent/client bundled (gzip) 127.46 KB (0%)
registerServerComponent/client bundled (gzip) (time) 127.46 KB (0%)
registerServerComponent/client bundled (brotli) 61.64 KB (0%)
registerServerComponent/client bundled (brotli) (time) 61.64 KB (0%)
wrapServerComponentRenderer/client bundled (gzip) 122.02 KB (0%)
wrapServerComponentRenderer/client bundled (gzip) (time) 122.02 KB (0%)
wrapServerComponentRenderer/client bundled (brotli) 56.77 KB (0%)
wrapServerComponentRenderer/client bundled (brotli) (time) 56.77 KB (0%)

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@react_on_rails/lib/generators/react_on_rails/templates/pro/base/client/node-renderer.js`:
- Around line 17-22: The workersCount calculation currently allows non-numeric
env values to produce NaN; update the logic that reads
env.RENDERER_WORKERS_COUNT and env.NODE_RENDERER_CONCURRENCY so you parse values
(e.g., parseInt) and validate they are finite non-negative integers before
accepting them, treat empty or invalid strings as null/ignored, and only fall
back to the next source or default 3 when validation fails; ensure the
normalized workersCount variable passed to master.ts (for loop) and checked in
ReactOnRailsProNodeRenderer.ts (workersCount === 0) is always a valid integer or
null to preserve single-process detection and avoid NaN propagation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9eaf0e0e-a167-482b-85e0-a49a8b05d408

📥 Commits

Reviewing files that changed from the base of the PR and between 68a6f04 and 960a39e.

📒 Files selected for processing (3)
  • docs/oss/getting-started/pro-quick-start.md
  • packages/react-on-rails-pro-node-renderer/README.md
  • react_on_rails/lib/generators/react_on_rails/templates/pro/base/client/node-renderer.js

Comment thread docs/oss/getting-started/pro-quick-start.md Outdated
@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 15, 2026

Review Summary

Overall the direction is correct — using RENDERER_WORKERS_COUNT as the canonical env var with a backward-compatible fallback to NODE_RENDERER_CONCURRENCY is a clean fix for the naming drift. The parseWorkersCount helper and nullish-coalescing chain in the template are readable and correct. A few things worth addressing before merge:

Issues

1. Whitespace-only string treated as 0 workers (inline, template line 6)
Number(' ') returns 0, which passes the current validation and silently sets workersCount: 0. A .trim() guard fixes this.

2. Zero workers allowed without warning (inline, template line 8)
parsed >= 0 permits workersCount: 0, which would leave the renderer with no workers and break SSR silently. Should require >= 1, or explicitly document that 0 is an intentional sentinel.

3. No deprecation signal for legacy env var (inline, template lines 22–25)
When NODE_RENDERER_CONCURRENCY is the active fallback, nothing in the runtime tells operators to migrate. A one-time console.warn would make the migration path self-documenting in production logs.

4. Doc example diverges from template pattern (inline, quick-start lines 126–139)
The quick-start guide shows a verbose inline IIFE while the generated template uses parseWorkersCount + ??. These will drift independently. The doc should mirror the template pattern or be simplified to a single readable expression.

Minor

The README table update is accurate and the wording is clear. No issues there.

Comment thread docs/oss/getting-started/pro-quick-start.md Outdated
@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 15, 2026

Follow-up after latest commit (3c00d20)

The latest commit addressed two issues flagged earlier:

  • Whitespace-only string handled correctly now via the trim() guard
  • Docs/template divergence fixed: quick-start guide now uses the same parseWorkersCount + nullish-coalescing pattern as the generated template

One issue remains in both files: the guard uses parsed >= 0, which accepts 0. If RENDERER_WORKERS_COUNT=0 or NODE_RENDERER_CONCURRENCY=0 is set, workersCount resolves to 0 and the renderer silently starts with no workers, breaking all SSR requests. Changing to parsed >= 1 (see inline comments) closes this gap with minimal risk.

If 0 is intentional (e.g. as a single-process sentinel the underlying library uses), that should be explicitly documented rather than accepted silently here.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/oss/migrating/rsc-troubleshooting.md`:
- Line 378: The documentation shows an invalid parenthesized directive ("('use
client')") which will not be recognized by parsers or the ESLint rule; replace
every occurrence of the parenthesized form with a bare string literal 'use
client' (no parentheses) so the directive prologue is valid and detectable by
the rule (see the snippet "('use client')" and the
eslint-rules/no-use-client-in-server-files.cjs tests for context).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 32c55612-e34a-4f3a-866d-1aa21f1a819b

📥 Commits

Reviewing files that changed from the base of the PR and between 3c00d20 and 956e987.

📒 Files selected for processing (2)
  • docs/README.md
  • docs/oss/migrating/rsc-troubleshooting.md
✅ Files skipped from review due to trivial changes (1)
  • docs/README.md

Comment thread docs/oss/migrating/rsc-troubleshooting.md Outdated
Comment thread docs/oss/migrating/rsc-troubleshooting.md Outdated
Comment thread docs/oss/migrating/rsc-troubleshooting.md Outdated
@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 15, 2026

Review Summary

The core logic change (introducing RENDERER_WORKERS_COUNT as the canonical env var with a NODE_RENDERER_CONCURRENCY fallback) is sound and the parseWorkersCount validation helper is a genuine improvement over the old unguarded Number() cast.

Bug in docs (rsc-troubleshooting.md) — The change from bare string literals to parenthesized form ('use client') in the GOOD examples introduces incorrect syntax. Bundlers (Next.js/Turbopack/webpack) detect the directive as a bare StringLiteral AST node; wrapping it in parens creates a ParenthesizedExpression that is not reliably recognized as a directive. This change appears unrelated to the PR's stated goal and should be reverted. Inline comments posted on the specific lines.

CI override silently beats the new canonical env var — The pre-existing if (env.CI) { config.workersCount = 2; } block at the bottom of the generated template unconditionally overrides workersCount, so a user who explicitly sets RENDERER_WORKERS_COUNT in their CI pipeline will be silently ignored. Now that this PR promotes RENDERER_WORKERS_COUNT as the canonical var, the CI block should either respect an explicitly set value or at least be documented with a warning. Inline comment posted on the template.

Minor: parseWorkersCount is duplicated between the generator template and pro-quick-start.md — expected for generated-file docs, but future changes to validation logic need updating in both places.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
docs/oss/getting-started/pro-quick-start.md (1)

122-128: Add brief explanation of parseWorkersCount helper.

The parseWorkersCount function is introduced without context. For a quick-start guide, a one-sentence explanation would help users understand its purpose (e.g., "validates and normalizes worker count values, returning an integer >= 0 or null for invalid inputs").

📝 Suggested documentation addition
 const { env } = process;
 
+// Helper to validate and normalize worker count environment variables
 const parseWorkersCount = (value) => {
   if (value == null) return null;
   const normalized = typeof value === 'string' ? value.trim() : String(value);
   if (normalized === '') return null;
   const parsed = Number(normalized);
   return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/oss/getting-started/pro-quick-start.md` around lines 122 - 128, Add a
one-sentence explanation for the parseWorkersCount helper immediately before (or
inline with) the function declaration that briefly describes its purpose and
behavior: e.g., state that parseWorkersCount validates and normalizes worker
count inputs, returning an integer >= 0 on success or null for empty/invalid
values; keep the sentence concise and place it next to the parseWorkersCount
function so readers of the quick-start guide understand what it does at a
glance.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/oss/getting-started/pro-quick-start.md`:
- Around line 136-137: Update the docs to explicitly state that
RENDERER_WORKERS_COUNT is the canonical env var and NODE_RENDERER_CONCURRENCY is
the legacy fallback used for backward compatibility (referencing the
workersCount resolution using parseWorkersCount(env.RENDERER_WORKERS_COUNT) ??
parseWorkersCount(env.NODE_RENDERER_CONCURRENCY) ?? 3), and add a note that a
CI-specific override (process.env.CI check in node-renderer.js that forces
workersCount to 2) takes precedence over that resolution chain and will affect
CI runs across platforms; ensure both behaviors and their precedence are clearly
described so users understand why configured counts may differ in CI.

---

Nitpick comments:
In `@docs/oss/getting-started/pro-quick-start.md`:
- Around line 122-128: Add a one-sentence explanation for the parseWorkersCount
helper immediately before (or inline with) the function declaration that briefly
describes its purpose and behavior: e.g., state that parseWorkersCount validates
and normalizes worker count inputs, returning an integer >= 0 on success or null
for empty/invalid values; keep the sentence concise and place it next to the
parseWorkersCount function so readers of the quick-start guide understand what
it does at a glance.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fc1754ad-cf9e-4109-8301-3c693bf76e2c

📥 Commits

Reviewing files that changed from the base of the PR and between 956e987 and d633fbb.

📒 Files selected for processing (2)
  • docs/oss/getting-started/pro-quick-start.md
  • react_on_rails/lib/generators/react_on_rails/templates/pro/base/client/node-renderer.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • react_on_rails/lib/generators/react_on_rails/templates/pro/base/client/node-renderer.js

Comment thread docs/oss/getting-started/pro-quick-start.md Outdated
Comment thread docs/oss/migrating/rsc-troubleshooting.md Outdated
@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 15, 2026

Review of PR #2611: Fix env var naming for Pro worker count

Summary

The core change — making RENDERER_WORKERS_COUNT canonical with a backward-compatible fallback to NODE_RENDERER_CONCURRENCY — is well-motivated and the implementation is solid. The parseWorkersCount helper correctly handles all edge cases: null/undefined, empty strings, floats, negatives, and explicitly 0 (single-process mode).

Bug: Unrelated 'use client' change in rsc-troubleshooting.md

The diff changes every 'use client' to ('use client') in docs/oss/migrating/rsc-troubleshooting.md. This is incorrect and unrelated to this PR's purpose. I've left an inline comment with details, but the short version:

  • React/RSC bundlers detect the directive by looking for a bare StringLiteral expression statement in the AST. A ParenthesizedExpression wrapping a string is not the same AST node and may silently be ignored.
  • Worse, the surrounding // GOOD labels make these the recommended forms for readers — actively misleading anyone who copies the example.

These three occurrences should be reverted to 'use client';.

Minor notes

  • The CI override (if (env.CI) { config.workersCount = 2; }) still hard-codes 2 and cannot be overridden even when a developer explicitly sets RENDERER_WORKERS_COUNT=0 for single-process debugging in CI. Not introduced by this PR, but worth a follow-up issue.
  • The README doc update (changing "The --pro generator uses NODE_RENDERER_CONCURRENCY instead" to "Legacy NODE_RENDERER_CONCURRENCY is still supported") is a clear improvement.

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 15, 2026

Code Review

Overall this is a clean, well-structured change. The backward-compatibility design is correct: RENDERER_WORKERS_COUNT as canonical, NODE_RENDERER_CONCURRENCY as legacy fallback, and the CI override only applies when no explicit value is set (so RENDERER_WORKERS_COUNT=0 correctly disables the CI default of 2).

Observations

Dead code in parseWorkersCount
The branch typeof value === 'string' ? value.trim() : String(value) will never reach the non-string path because the function is only called with process.env.* values, which are always strings (or undefined). The undefined case is already handled by the early null guard. The String(value) path is dead code in the generated template.

Spec coverage is presence-only
The two new spec lines assert the generated file contains specific source strings but don't exercise the runtime logic (e.g., that the fallback chain works, that 0 is accepted, that an invalid string returns null). For a generated template this is the norm, but the parseWorkersCount logic itself has no dedicated unit tests.

Pre-existing: Number(env.RENDERER_PORT) || 3800 inconsistency
Out of scope for this PR, but worth a follow-up: RENDERER_PORT=0 silently falls back to 3800 because Number('0') || 3800 === 3800. The new parseWorkersCount correctly handles 0 via >= 0, making the port parsing inconsistent by comparison.

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 15, 2026

Review

The fix is clean and correct. The parseWorkersCount helper properly handles all edge cases (null/undefined, empty string, negatives, floats, NaN), the ?? chaining correctly preserves 0 as a valid single-process value, and the CI guard now only applies when no explicit override is set — all good.

A few observations:

Missing CHANGELOG entry — This fixes a real user-facing issue (#2607) in the Pro generator template. Per the changelog guidelines, a #### Pro > ##### Fixed entry in CHANGELOG.md seems warranted.

Silent fallback on invalid value — Noted inline on parseWorkersCount. If RENDERER_WORKERS_COUNT=bad is set, it silently falls back without any log message, which can be hard to debug in production. Worth adding a console.warn here.

Pre-existing port inconsistencyNumber(env.RENDERER_PORT) || 3800 uses the old falsy pattern. Port 0 would incorrectly fall back to 3800. Low severity since port 0 isn't a real use case, but it's now more visible alongside the careful parseWorkersCount approach. Could be addressed as a follow-up.

Doc/template duplicationpro-quick-start.md now mirrors the template code, which is the right approach for docs. Just worth being aware that they'll need to be kept in sync manually if the template evolves further.

Overall: good, low-risk change. Addresses the issue cleanly with backward compatibility preserved.

@justin808 justin808 force-pushed the jg-codex/issue-2607-workers-env-var branch from 03872a7 to 6d23d45 Compare March 16, 2026 02:22
if (Number.isInteger(parsed) && parsed >= 0) return parsed;
console.warn(`[react-on-rails] Ignoring invalid worker count "${value}". Expected a non-negative integer.`);
return null;
};
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parseWorkersCount function is now duplicated verbatim in three places: the generator template, packages/react-on-rails-pro-node-renderer/README.md, and docs/oss/getting-started/pro-quick-start.md.

For user-facing docs/examples, copying is unavoidable, but consider whether this helper could live in the react-on-rails-pro-node-renderer package itself and be exported (e.g. parseWorkersCount or a resolveWorkersCount factory). That would mean future bug fixes or validation changes propagate automatically instead of requiring every generated file to be regenerated.

// of CPUs number allocated for current container. This results in spawning many workers while
// only 1-2 of them really needed.
if (env.CI) {
if (env.CI && configuredWorkersCount == null) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a meaningful behaviour change: previously, setting CI=true always forced workersCount to 2, even if the user had explicitly set NODE_RENDERER_CONCURRENCY. Now an explicit env var takes precedence over the CI cap.

That's almost certainly the right semantics, but existing CI setups that relied on CI to act as a hard cap (e.g. to prevent resource exhaustion on shared runners) will silently get more workers if they happen to have RENDERER_WORKERS_COUNT or NODE_RENDERER_CONCURRENCY set. Worth a note in the CHANGELOG / migration guide so operators aren't surprised.

@@ -41,7 +51,8 @@ reactOnRailsProNodeRenderer({
password: process.env.RENDERER_PASSWORD,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The README example only shows RENDERER_WORKERS_COUNT but does not include the NODE_RENDERER_CONCURRENCY legacy fallback that the actual generated template uses. A user copying this snippet (rather than running the generator) won't get the backward-compatible fallback. Either expand the example to match the template, or add a note that the generated template also checks NODE_RENDERER_CONCURRENCY.

| -------------------------------------- | --------------------------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------- |
| `port` | `RENDERER_PORT` | `3800` | Port the renderer listens on |
| `logLevel` | `RENDERER_LOG_LEVEL` | `'info'` | Log level (`fatal`, `error`, `warn`, `info`, `debug`, `trace`, `silent`) |
| `logHttpLevel` | `RENDERER_LOG_HTTP_LEVEL` | `'error'` | HTTP server log level |
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The table still says the default is CPU count - 1, but the generated template (and the example just above) hard-codes 3 as the default when neither env var is set. These should be consistent — either update the table to say 3 (or 2 on CI) or align the generated template with the documented CPU-based default.

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 18, 2026

Review: Fix #2607 — align Pro worker-count env var naming

Overall the approach is sound: RENDERER_WORKERS_COUNT as canonical with a legacy NODE_RENDERER_CONCURRENCY fallback, proper 0-support, and validation. A few things worth addressing before merge:

Missing CHANGELOG entry
The [Unreleased] section is empty. This PR changes the behaviour of generated files (new env var precedence, CI-cap semantics) and should have an entry — tagged [Pro] — so operators upgrading know what to re-generate or watch for.

Spec coverage is thin
The two new assertions in install_generator_spec.rb only check that certain strings appear in the generated file. There are no tests for the parseWorkersCount logic itself (e.g. "0" → 0, "1.5" → null/warn, "" → null, "abc" → null/warn). If the helper ever lives in the library it could be unit-tested there; otherwise a JS test file for the template would help catch regressions.

Inline comments posted on specific lines (see thread above).

Overall: nice clean fix, just needs a CHANGELOG entry and the README/table inconsistencies addressed.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7c577b27f4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +50 to 51
if (env.CI && configuredWorkersCount == null) {
config.workersCount = 2;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stop overriding explicit template worker counts on CI

If an app customizes the generated client/node-renderer.js by hardcoding workersCount in the config object, this guard still rewrites that value to 2 whenever CI is set, because configuredWorkersCount only reflects env-derived overrides. That makes the new "default only when no override is set" behavior incomplete for the common customization path of editing the generated config file directly, even though buildConfig() treats config-object values as authoritative (packages/react-on-rails-pro-node-renderer/src/shared/configBuilder.ts:254-256).

Useful? React with 👍 / 👎.

if (value == null) return null;
const normalized = value.trim();
if (normalized === '') return null;
const parsed = Number(normalized);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Edge case: Number() accepts non-decimal integer literals.

Number('1e2') → 100, Number('0x10') → 16, Number('0b101') → 5. All pass Number.isInteger and >= 0, so they'd silently become valid worker counts. In practice nobody would set RENDERER_WORKERS_COUNT=0x10, but an env var coming from a misconfigured string could produce a surprising result with no warning.

A simple guard using a decimal-only regex before calling Number() would prevent this:

Suggested change
const parsed = Number(normalized);
const parsed = Number(normalized);
if (!/^\d+$/.test(normalized) || !Number.isInteger(parsed) || parsed < 0) {

This restricts accepted values to plain non-negative decimal integers (e.g. "0", "3", "12") and ensures inputs like "1e2" or "0x10" get the warning path.

if (normalized === '') return null;
const parsed = Number(normalized);
if (Number.isInteger(parsed) && parsed >= 0) return parsed;
console.warn(`[react-on-rails] Ignoring invalid worker count "${value}". Expected a non-negative integer.`);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: the warning should use normalized (trimmed value) rather than the raw value when the invalid input is just leading/trailing whitespace, but more importantly — the warn message embeds the raw value in a template string, which is fine.

One correctness note: for the edge case where value contains whitespace around a bad string (e.g. " -1 "), both value and normalized are available. Using normalized in the message would be marginally clearer.

Suggested change
console.warn(`[react-on-rails] Ignoring invalid worker count "${value}". Expected a non-negative integer.`);
console.warn(`[react-on-rails] Ignoring invalid worker count "${normalized}". Expected a non-negative integer.`);

import log from './shared/log.js';
import { majorVersion } from './shared/utils.js';

export function parseWorkersCount(value: string | null | undefined): number | null {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Behavioral inconsistency: configBuilder.ts still parses RENDERER_WORKERS_COUNT with bare parseInt.

parseWorkersCount is now the validated, user-facing API, but the library's own default config (line 168 of configBuilder.ts) still does:

workersCount: env.RENDERER_WORKERS_COUNT ? parseInt(env.RENDERER_WORKERS_COUNT, 10) : defaultWorkersCount(),

When the generated template is used this doesn't matter because workersCount is always set explicitly and overrides the default. However, users who call reactOnRailsProNodeRenderer({ /* no workersCount */ }) and set RENDERER_WORKERS_COUNT=abc will get NaN workers silently rather than a warning and a safe fallback.

Consider also updating configBuilder.ts to use parseWorkersCount so the validation logic is applied uniformly, regardless of whether workersCount is set in code or via env only.

it('warns and returns null for invalid values', () => {
const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => undefined);

expect(parseWorkersCount('workers')).toBeNull();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good test coverage. Two additional cases worth adding to harden the edge-case behaviour:

  1. Scientific / alternate-base notation (currently accepted as valid):

    expect(parseWorkersCount('1e2')).toBeNull();   // 100 via Number(), likely unintended
    expect(parseWorkersCount('0x10')).toBeNull();  // 16 via Number(), likely unintended
  2. NaN string (already covered by the 'workers' case, but worth being explicit):

    expect(parseWorkersCount('NaN')).toBeNull();

Adding these (after deciding whether to fix the underlying behaviour) will lock in the intended contract.

expect(content).to include("serverBundleCachePath")
expect(content).to include("port:")
expect(content).to include("password:")
expect(content).to include("const configuredWorkersCount =")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The spec verifies the implementation details of the CI guard and configuredWorkersCount variable, but doesn't assert that parseWorkersCount is imported in the generated file. If the import is renamed or removed the template would break at runtime without this test catching it.

Suggested change
expect(content).to include("const configuredWorkersCount =")
expect(content).to include("parseWorkersCount")
expect(content).to include("const configuredWorkersCount =")

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 18, 2026

Overall the direction is right: canonicalizing RENDERER_WORKERS_COUNT, introducing a validated parseWorkersCount helper, and keeping backward-compatible fallback to NODE_RENDERER_CONCURRENCY is a clean approach. The test coverage for the new helper is solid.

Issues flagged inline:

  • ReactOnRailsProNodeRenderer.ts (medium): configBuilder.ts still parses RENDERER_WORKERS_COUNT with bare parseInt, so invalid values produce NaN workers when workersCount is not set in code — inconsistent with the new validated helper.
  • ReactOnRailsProNodeRenderer.ts:13 (low): Number() accepts scientific notation (1e2 = 100) and hex (0x10 = 16) as valid worker counts, which is likely unintended.
  • ReactOnRailsProNodeRenderer.ts:15 (nit): Warn message logs raw value — should log trimmed normalized for clarity.
  • parseWorkersCount.test.ts (low): Missing tests for 1e2 / 0x10 edge cases to lock in the intended contract.
  • install_generator_spec.rb (low): Spec checks configuredWorkersCount variable usage but does not assert parseWorkersCount appears in the generated import.

Other observations:

  • The CI guard if (env.CI && configuredWorkersCount == null) correctly preserves an explicit RENDERER_WORKERS_COUNT=0 (single-process mode) even in CI.
  • parseWorkersCount is exported from the main package entry point so the destructured require in templates will work correctly.

@justin808 justin808 merged commit 3cf2881 into main Mar 18, 2026
49 checks passed
@justin808 justin808 deleted the jg-codex/issue-2607-workers-env-var branch March 18, 2026 04:20
justin808 added a commit that referenced this pull request Mar 30, 2026
## Summary
- make generated Pro  use  as canonical env var
- keep backward-compatible fallback to 
- update docs/examples to match canonical naming and mention legacy
fallback

## Why
Issue #2607 reported naming drift between generated template and
runtime/docs conventions. This change removes the mismatch while
preserving compatibility for existing deployments.

## Testing
- Run options: include {focus: true, locations:
{"./react_on_rails/spec/react_on_rails/generators/install_generator_spec.rb"
=> [1173, 1405]}}
..

Finished in 1 minute 5.27 seconds (files took 1.77 seconds to load)
2 examples, 0 failures

Run options: --seed 59137

# Running:



Finished in 0.000702s, 0.0000 runs/s, 0.0000 assertions/s.

0 runs, 0 assertions, 0 failures, 0 errors, 0 skips

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Low risk: changes are limited to worker-count env var
parsing/precedence plus docs and generator template updates; runtime
behavior only differs when env values are invalid/blank or when CI
defaults previously overrode an explicit worker count.
> 
> **Overview**
> Aligns Pro Node Renderer worker-count configuration around
**`RENDERER_WORKERS_COUNT` as the canonical env var**, while keeping
**backward-compatible fallback** to legacy `NODE_RENDERER_CONCURRENCY`
in generated `node-renderer.js` templates and quick-start docs.
> 
> Adds `parseWorkersCount` (with tests) to validate/normalize
worker-count inputs (supports `0` for single-process mode, ignores
invalid values with a warning), and updates the CI defaulting logic to
apply `workersCount=2` **only when no explicit override is provided**.
Documentation and README examples are updated to reflect the new
precedence and behavior.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
1a71dee. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Enhancements**
* Worker count resolution now validates and accepts explicit 0 or
positive integers, prefers the new renderer env, falls back to the
legacy concurrency env, defaults to 3, and remains 2 in CI.
* Renderer config access unified via an environment alias for clearer
configuration.

* **Documentation**
* Clarified precedence, validation, legacy fallback and single-process
(0) behavior; updated quick reference formatting and troubleshooting
guidance.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
justin808 added a commit that referenced this pull request Apr 6, 2026
## Summary
- make generated Pro  use  as canonical env var
- keep backward-compatible fallback to 
- update docs/examples to match canonical naming and mention legacy
fallback

## Why
Issue #2607 reported naming drift between generated template and
runtime/docs conventions. This change removes the mismatch while
preserving compatibility for existing deployments.

## Testing
- Run options: include {focus: true, locations:
{"./react_on_rails/spec/react_on_rails/generators/install_generator_spec.rb"
=> [1173, 1405]}}
..

Finished in 1 minute 5.27 seconds (files took 1.77 seconds to load)
2 examples, 0 failures

Run options: --seed 59137

# Running:



Finished in 0.000702s, 0.0000 runs/s, 0.0000 assertions/s.

0 runs, 0 assertions, 0 failures, 0 errors, 0 skips

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Low risk: changes are limited to worker-count env var
parsing/precedence plus docs and generator template updates; runtime
behavior only differs when env values are invalid/blank or when CI
defaults previously overrode an explicit worker count.
> 
> **Overview**
> Aligns Pro Node Renderer worker-count configuration around
**`RENDERER_WORKERS_COUNT` as the canonical env var**, while keeping
**backward-compatible fallback** to legacy `NODE_RENDERER_CONCURRENCY`
in generated `node-renderer.js` templates and quick-start docs.
> 
> Adds `parseWorkersCount` (with tests) to validate/normalize
worker-count inputs (supports `0` for single-process mode, ignores
invalid values with a warning), and updates the CI defaulting logic to
apply `workersCount=2` **only when no explicit override is provided**.
Documentation and README examples are updated to reflect the new
precedence and behavior.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
1a71dee. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Enhancements**
* Worker count resolution now validates and accepts explicit 0 or
positive integers, prefers the new renderer env, falls back to the
legacy concurrency env, defaults to 3, and remains 2 in CI.
* Renderer config access unified via an environment alias for clearer
configuration.

* **Documentation**
* Clarified precedence, validation, legacy fallback and single-process
(0) behavior; updated quick reference formatting and troubleshooting
guidance.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant