Fixed conversion of environment variables to number types with Claude Code 2#154
Fixed conversion of environment variables to number types with Claude Code 2#154
Conversation
WalkthroughIntroduces parseEnvInteger for integer parsing in env.ts, applies it to timeouts, MAX_DELAY, and PORT with defaults, and adds ordering validations between timeouts. Module now throws on invalid integers or misordered values. Tests added to verify rejection messages for invalid integers and out-of-range values. Changes
Sequence Diagram(s)sequenceDiagram
participant App
participant Env as loadEnv()
participant Parser as parseEnvInteger
participant Validator as validateOrdering
App->>Env: initialize config
Env->>Parser: parse PORT, MAX_DELAY, timeouts
Parser-->>Env: integers or throw on invalid
Env->>Validator: check timeout ordering
Validator-->>Env: ok or throw
Env-->>App: config or error
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Summary of Changes
Hello @ryo8000, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request refactors how environment variables are parsed into number types, introducing a dedicated utility function for robust integer conversion. It enhances error handling by explicitly throwing errors for invalid or unsafe integer inputs, ensuring that environment-dependent configurations are correctly and safely loaded.
Highlights
- Robust Environment Variable Parsing: A new parseEnvInteger utility function has been introduced to safely convert string-based environment variables into integer types. This function handles default values and integrates toSafeInteger for validation.
- Enhanced Input Validation: The system now provides explicit error messages when environment variables intended to be integers are malformed (e.g., non-numeric strings, floating-point numbers, or values outside JavaScript's safe integer range).
- Comprehensive Test Coverage: New unit tests have been added to env.test.ts to cover various invalid scenarios for integer environment variables, ensuring the new validation logic functions as expected.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
String to number,Safe parse, no silent errors,Code runs true and strong.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Code Review
This pull request addresses a flaw in how environment variables are converted to number types. The previous method using Number(process.env['VAR']) || defaultValue would incorrectly handle 0 as a falsy value, causing it to fall back to the default. It also silently used the default for any non-numeric string values. The introduction of the parseEnvInteger helper function is a great improvement. It correctly handles 0, only uses the default value if the variable is undefined, and throws an explicit error for invalid integer values, making the application's configuration loading much more robust and predictable. The accompanying tests are thorough, and I have one suggestion to make them more maintainable.
| it('should throw an error when HEADERS_TIMEOUT is not a valid integer', async () => { | ||
| process.env.HEADERS_TIMEOUT = 'invalid'; | ||
|
|
||
| await expect(loadEnv()).rejects.toThrow( | ||
| 'Invalid HEADERS_TIMEOUT environment variable: "invalid" is not a valid integer' | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw an error when REQUEST_TIMEOUT is not a valid integer', async () => { | ||
| process.env.REQUEST_TIMEOUT = '1.5'; | ||
|
|
||
| await expect(loadEnv()).rejects.toThrow( | ||
| 'Invalid REQUEST_TIMEOUT environment variable: "1.5" is not a valid integer' | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw an error when KEEP_ALIVE_TIMEOUT is not a valid integer', async () => { | ||
| process.env.KEEP_ALIVE_TIMEOUT = '2e10'; | ||
|
|
||
| await expect(loadEnv()).rejects.toThrow( | ||
| 'Invalid KEEP_ALIVE_TIMEOUT environment variable: "2e10" is not a valid integer' | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw an error when MAX_DELAY is not a valid integer', async () => { | ||
| process.env.MAX_DELAY = 'abc'; | ||
|
|
||
| await expect(loadEnv()).rejects.toThrow( | ||
| 'Invalid MAX_DELAY environment variable: "abc" is not a valid integer' | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw an error when PORT is not a valid integer', async () => { | ||
| process.env.PORT = '8000.0'; | ||
|
|
||
| await expect(loadEnv()).rejects.toThrow( | ||
| 'Invalid PORT environment variable: "8000.0" is not a valid integer' | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw an error when integer is out of safe range', async () => { | ||
| process.env.PORT = '9007199254740992'; | ||
|
|
||
| await expect(loadEnv()).rejects.toThrow( | ||
| 'Invalid PORT environment variable: "9007199254740992" is not a valid integer' | ||
| ); | ||
| }); |
There was a problem hiding this comment.
These tests are great for ensuring invalid values are handled correctly. To improve maintainability and reduce code duplication, you could parameterize these tests using it.each, which you're already using elsewhere in the test suite. This would make the test suite more concise and easier to extend with new invalid cases in the future.
describe('when an integer environment variable is invalid', () => {
const testCases = [
{ name: 'not an integer', envVar: 'HEADERS_TIMEOUT', value: 'invalid' },
{ name: 'a float string', envVar: 'REQUEST_TIMEOUT', value: '1.5' },
{ name: 'scientific notation', envVar: 'KEEP_ALIVE_TIMEOUT', value: '2e10' },
{ name: 'a non-numeric string', envVar: 'MAX_DELAY', value: 'abc' },
{ name: 'a float string with .0', envVar: 'PORT', value: '8000.0' },
{ name: 'an out of safe range integer', envVar: 'PORT', value: '9007199254740992' },
];
it.each(testCases)('should throw an error when $envVar is $name ($value)', async ({ envVar, value }) => {
process.env[envVar] = value;
await expect(loadEnv()).rejects.toThrow(
`Invalid ${envVar} environment variable: "${value}" is not a valid integer`
);
});
});There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (5)
src/env.ts (3)
3-13: Harden integer parsing with min/max bounds to prevent negative timeouts and invalid port valuesparseEnvInteger is solid. To avoid subtle misconfigurations (e.g., negative timeouts, negative MAX_DELAY disabling delays, or ports outside 0–65535), consider adding optional range validation.
Apply this diff to extend the helper:
-const parseEnvInteger = (envVar: string, defaultValue: number): number => { +const parseEnvInteger = ( + envVar: string, + defaultValue: number, + opts?: { min?: number; max?: number } +): number => { const value = process.env[envVar]; if (value === undefined) { return defaultValue; } const parsed = toSafeInteger(value); if (parsed === undefined) { throw new Error(`Invalid ${envVar} environment variable: "${value}" is not a valid integer`); } - return parsed; + if (opts?.min !== undefined && parsed < opts.min) { + throw new Error(`Invalid ${envVar} environment variable: ${parsed} must be >= ${opts.min}`); + } + if (opts?.max !== undefined && parsed > opts.max) { + throw new Error(`Invalid ${envVar} environment variable: ${parsed} must be <= ${opts.max}`); + } + return parsed; };
15-17: Clamp timeouts to non-negative valuesNegative timeout values can lead to confusing behavior or immediate timeouts. If you adopt range support in parseEnvInteger, pass min: 0 here.
-const headersTimeout = parseEnvInteger('HEADERS_TIMEOUT', 10000); -const requestTimeout = parseEnvInteger('REQUEST_TIMEOUT', 30000); -const keepAliveTimeout = parseEnvInteger('KEEP_ALIVE_TIMEOUT', 5000); +const headersTimeout = parseEnvInteger('HEADERS_TIMEOUT', 10000, { min: 0 }); +const requestTimeout = parseEnvInteger('REQUEST_TIMEOUT', 30000, { min: 0 }); +const keepAliveTimeout = parseEnvInteger('KEEP_ALIVE_TIMEOUT', 5000, { min: 0 });
36-39: Validate MAX_DELAY is non-negative and PORT within [0, 65535]
- MAX_DELAY < 0 will effectively disable delays due to Math.min(...) yielding a negative actualDelay.
- PORT outside the valid range or negative can cause server startup failures.
- maxDelay: parseEnvInteger('MAX_DELAY', 10000), + maxDelay: parseEnvInteger('MAX_DELAY', 10000, { min: 0 }), nodeEnv: process.env['NODE_ENV'] || 'development', origin: process.env['ORIGIN'] || '*', - port: parseEnvInteger('PORT', 8000), + port: parseEnvInteger('PORT', 8000, { min: 0, max: 65535 }),tests/ut/env.test.ts (2)
83-130: De-duplicate repetitive “invalid integer” tests with a table-driven patternYou can compact these into a single parameterized case while keeping explicit assertions.
Example refactor:
it.each([ { name: 'HEADERS_TIMEOUT', value: 'invalid' }, { name: 'REQUEST_TIMEOUT', value: '1.5' }, { name: 'KEEP_ALIVE_TIMEOUT', value: '2e10' }, { name: 'MAX_DELAY', value: 'abc' }, { name: 'PORT', value: '8000.0' }, ] as const)('should throw when %s is not a valid integer', async ({ name, value }) => { process.env[name] = value; await expect(loadEnv()).rejects.toThrow( `Invalid ${name} environment variable: "${value}" is not a valid integer` ); });
83-130: Consider adding range tests (negative and out-of-range port), especially if you enforce min/maxIf you adopt min/max in parseEnvInteger:
- Add tests to ensure negative timeouts and MAX_DELAY are rejected.
- Add tests to reject PORT < 0 and PORT > 65535 (PORT=0 should still be allowed).
Proposed additional tests:
it('should throw when MAX_DELAY is negative', async () => { process.env.MAX_DELAY = '-1'; await expect(loadEnv()).rejects.toThrow(/MAX_DELAY environment variable: -1 must be >= 0/); }); it('should throw when HEADERS_TIMEOUT is negative', async () => { process.env.HEADERS_TIMEOUT = '-100'; await expect(loadEnv()).rejects.toThrow(/HEADERS_TIMEOUT environment variable: -100 must be >= 0/); }); it('should throw when PORT is negative', async () => { process.env.PORT = '-1'; await expect(loadEnv()).rejects.toThrow(/PORT environment variable: -1 must be >= 0/); }); it('should throw when PORT exceeds 65535', async () => { process.env.PORT = '70000'; await expect(loadEnv()).rejects.toThrow(/PORT environment variable: 70000 must be <= 65535/); }); it('should allow PORT=0 (ephemeral port)', async () => { process.env.PORT = '0'; expect(await loadEnv()).toEqual(expect.objectContaining({ port: 0 })); });I can open a follow-up PR to implement the range checks and add these tests if helpful.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
src/env.ts(2 hunks)tests/ut/env.test.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/ut/env.test.ts (1)
tests/ut/utils/number.test.ts (1)
validIntegerTestCases(4-19)
src/env.ts (1)
src/utils/number.ts (1)
toSafeInteger(16-28)
🔇 Additional comments (2)
src/env.ts (1)
31-41: Confirm stricter empty-string handling for numeric env varsIn src/env.ts (lines 31–41),
parseEnvIntegernow treats an empty string ('') as an invalid integer and throws, whereas the previousNumber(value) || defaultapproach silently fell back to the default. As a result, settingPORT=''orMAX_DELAY=''(or any other numeric env var) will now crash on import instead of using the default.Please verify that this fail-fast behavior is intended. If it is:
- Update documentation or error messages to call out that empty strings are disallowed.
- Ensure all deployment tooling and CI pipelines won’t inadvertently pass empty strings.
If you’d rather preserve the old fallback for
'', consider normalizingvalue === ''toundefinedbefore callingtoSafeInteger.Affected env vars:
- Numeric:
HEADERS_TIMEOUT,KEEP_ALIVE_TIMEOUT,REQUEST_TIMEOUT,MAX_DELAY,PORT
– impactsserver.ts(app.listen onenvironment.port) anddelay.ts(capped byenvironment.maxDelay)- String:
LOG_LEVEL,NODE_ENV,ORIGINremain unchanged and still default on emptytests/ut/env.test.ts (1)
83-130: LGTM: strong coverage for invalid integers and safe-range overflowThese tests precisely match the new error messages and guard against common bad inputs (non-integers and out-of-safe-range). Good use of dynamic import + resetModules to isolate env per test.
Summary by CodeRabbit
New Features
Bug Fixes
Tests