Skip to content

Add env helpers and refactor config #401

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

djwhitt
Copy link
Collaborator

@djwhitt djwhitt commented May 25, 2025

Summary

  • add helper functions for common env parsing
  • refactor config.ts to use new helpers
  • replace sanitizeUrl with env.urlVar

Testing

  • npx eslint src test
  • yarn test (fails: This package doesn't seem to be present in your lockfile)

Copy link

codecov bot commented May 25, 2025

Codecov Report

Attention: Patch coverage is 97.70642% with 5 lines in your changes missing coverage. Please review.

Project coverage is 73.01%. Comparing base (c2f8851) to head (cfca4a2).

Files with missing lines Patch % Lines
src/lib/env.ts 90.32% 3 Missing ⚠️
src/config.ts 98.93% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #401      +/-   ##
===========================================
+ Coverage    72.91%   73.01%   +0.10%     
===========================================
  Files           49       49              
  Lines        12348    12349       +1     
  Branches       706      702       -4     
===========================================
+ Hits          9003     9017      +14     
+ Misses        3339     3326      -13     
  Partials         6        6              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

coderabbitai bot commented May 25, 2025

📝 Walkthrough

Walkthrough

The configuration system was refactored to use new typed environment variable accessors from the env module, replacing all manual parsing and conversions. The env module was expanded with helpers for booleans, integers, lists, JSON, and URLs, standardizing environment variable handling throughout the configuration file.

Changes

File(s) Change Summary
src/config.ts Refactored all environment variable parsing to use new typed helpers from env module; removed manual conversions and redundant code.
src/lib/env.ts Added helper functions: boolVar, intVar, optionalIntVar, listVar, optionalListVar, jsonVar, urlVar for typed environment variable access.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant EnvHelpers

    App->>EnvHelpers: intVar('PORT', 4000)
    EnvHelpers-->>App: 4000 (number)

    App->>EnvHelpers: boolVar('REDIS_USE_TLS', false)
    EnvHelpers-->>App: false (boolean)

    App->>EnvHelpers: listVar('CHUNK_POST_URLS', default)
    EnvHelpers-->>App: [url1, url2, ...]

    App->>EnvHelpers: jsonVar('ANS104_UNBUNDLE_FILTER_PARSED', {})
    EnvHelpers-->>App: parsedObject

    App->>EnvHelpers: urlVar('AO_MU_URL')
    EnvHelpers-->>App: sanitizedUrl or undefined
Loading

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

yarn install v1.22.22
[1/4] Resolving packages...
(node:22720) [DEP0169] DeprecationWarning: url.parse() behavior is not standardized and prone to errors that have security implications. Use the WHATWG URL API instead. CVEs are not issued for url.parse() vulnerabilities.
(Use node --trace-deprecation ... to show where the warning was created)
[2/4] Fetching packages...
error @permaweb/aoconnect@0.0.57: The engine "yarn" is incompatible with this module. Expected version "please-use-npm". Got "1.22.22"
error Found incompatible module.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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: 3

🔭 Outside diff range comments (2)
src/config.ts (2)

106-119: 🛠️ Refactor suggestion

Inconsistent refactoring: Some manual parsing remains.

Several environment variables still use the old +env.varOrDefault() pattern instead of the new intVar utility.

For consistency, convert these to use intVar:

-export const TRUSTED_GATEWAYS_REQUEST_TIMEOUT_MS = +env.varOrDefault(
-  'TRUSTED_GATEWAYS_REQUEST_TIMEOUT_MS',
-  '10000',
-);
+export const TRUSTED_GATEWAYS_REQUEST_TIMEOUT_MS = env.intVar(
+  'TRUSTED_GATEWAYS_REQUEST_TIMEOUT_MS',
+  10000,
+);

-export const WEIGHTED_PEERS_TEMPERATURE_DELTA = +env.varOrDefault(
-  'WEIGHTED_PEERS_TEMPERATURE_DELTA',
-  '2',
-);
+export const WEIGHTED_PEERS_TEMPERATURE_DELTA = env.intVar(
+  'WEIGHTED_PEERS_TEMPERATURE_DELTA',
+  2,
+);

-export const GATEWAY_PEERS_WEIGHTS_CACHE_DURATION_MS = +env.varOrDefault(
-  'GATEWAY_PEERS_WEIGHTS_CACHE_DURATION_MS',
-  `${5 * 1000}`, // 5 seconds
-);
+export const GATEWAY_PEERS_WEIGHTS_CACHE_DURATION_MS = env.intVar(
+  'GATEWAY_PEERS_WEIGHTS_CACHE_DURATION_MS',
+  5 * 1000, // 5 seconds
+);

197-200: 🛠️ Refactor suggestion

Additional manual parsing instances to refactor.

More instances of the old parsing pattern that should be converted for consistency.

Apply similar refactoring here:

-export const ARWEAVE_PEER_CHUNK_POST_CONCURRENCY_LIMIT = +env.varOrDefault(
-  'ARWEAVE_PEER_CHUNK_POST_CONCURRENCY_LIMIT',
-  '3',
-);
+export const ARWEAVE_PEER_CHUNK_POST_CONCURRENCY_LIMIT = env.intVar(
+  'ARWEAVE_PEER_CHUNK_POST_CONCURRENCY_LIMIT',
+  3,
+);
🧹 Nitpick comments (2)
src/lib/env.ts (2)

42-44: Consider case-insensitive boolean parsing for better usability.

The current implementation only accepts lowercase 'true' as truthy, which might be surprising to users who set environment variables like "TRUE" or "True".

Consider this more flexible approach:

-export function boolVar(envVarName: string, defaultValue: boolean): boolean {
-  return varOrDefault(envVarName, defaultValue ? 'true' : 'false') === 'true';
-}
+export function boolVar(envVarName: string, defaultValue: boolean): boolean {
+  return varOrDefault(envVarName, defaultValue ? 'true' : 'false').toLowerCase() === 'true';
+}

55-62: Review list filtering behavior for edge cases.

The filter(Boolean) approach removes falsy values including "0", "false", and empty strings. This might unexpectedly filter out valid list items.

Consider filtering only empty strings if "0" or "false" are valid list items:

 export function listVar(envVarName: string, defaultValue: string): string[] {
-  return varOrDefault(envVarName, defaultValue).split(',').filter(Boolean);
+  return varOrDefault(envVarName, defaultValue).split(',').filter(item => item.trim() !== '');
 }

 export function optionalListVar(envVarName: string): string[] {
   const value = varOrUndefined(envVarName);
-  return value !== undefined ? value.split(',').filter(Boolean) : [];
+  return value !== undefined ? value.split(',').filter(item => item.trim() !== '') : [];
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c2f8851 and cfca4a2.

📒 Files selected for processing (2)
  • src/config.ts (16 hunks)
  • src/lib/env.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test (ubuntu-latest)
  • GitHub Check: test (macos-latest)
🔇 Additional comments (6)
src/lib/env.ts (1)

68-71: URL sanitization implementation looks good.

The function correctly handles optional URLs and removes trailing slashes using a robust regex pattern.

src/config.ts (5)

32-32: Port configuration conversion looks correct.

The conversion from manual parsing to intVar preserves the default value and improves type safety.


61-61: Boolean environment variable conversions are correct.

The refactoring properly converts manual string comparisons to typed boolVar calls while preserving default values.

Also applies to: 248-248, 317-321


129-131: List parsing conversions look good.

The conversion from manual string splitting to listVar and optionalListVar maintains the same behavior while improving readability.

Also applies to: 134-137, 144-146


802-805: URL variable refactoring is well implemented.

The conversion to urlVar properly handles URL sanitization and maintains the fallback logic with nullish coalescing operators.


255-258: JSON parsing conversions preserve functionality.

The refactoring from manual JSON.parse to jsonVar maintains the same default values and behavior.

Also applies to: 268-270

Comment on lines +64 to +66
export function jsonVar<T>(envVarName: string, defaultValue: T): T {
return JSON.parse(varOrDefault(envVarName, JSON.stringify(defaultValue)));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for JSON parsing.

The jsonVar function uses JSON.parse without error handling, which will throw on malformed JSON and crash the application during startup.

Add error handling:

 export function jsonVar<T>(envVarName: string, defaultValue: T): T {
-  return JSON.parse(varOrDefault(envVarName, JSON.stringify(defaultValue)));
+  try {
+    return JSON.parse(varOrDefault(envVarName, JSON.stringify(defaultValue)));
+  } catch (error) {
+    throw new Error(`Invalid JSON value for ${envVarName}: ${error.message}`);
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function jsonVar<T>(envVarName: string, defaultValue: T): T {
return JSON.parse(varOrDefault(envVarName, JSON.stringify(defaultValue)));
}
export function jsonVar<T>(envVarName: string, defaultValue: T): T {
try {
return JSON.parse(varOrDefault(envVarName, JSON.stringify(defaultValue)));
} catch (error) {
throw new Error(`Invalid JSON value for ${envVarName}: ${error.message}`);
}
}
🤖 Prompt for AI Agents
In src/lib/env.ts around lines 64 to 66, the jsonVar function calls JSON.parse
without error handling, which can cause the application to crash if the JSON is
malformed. Wrap the JSON.parse call in a try-catch block to catch any parsing
errors. If an error occurs, log or handle it appropriately and return the
defaultValue instead of throwing, ensuring the application startup is not
interrupted by malformed JSON.

Comment on lines +46 to +53
export function intVar(envVarName: string, defaultValue: number): number {
return parseInt(varOrDefault(envVarName, String(defaultValue)), 10);
}

export function optionalIntVar(envVarName: string): number | undefined {
const value = varOrUndefined(envVarName);
return value !== undefined ? parseInt(value, 10) : undefined;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for invalid integer values.

Both intVar and optionalIntVar use parseInt without error handling. Invalid values will return NaN, which could cause unexpected behavior in the application.

Consider adding validation:

 export function intVar(envVarName: string, defaultValue: number): number {
-  return parseInt(varOrDefault(envVarName, String(defaultValue)), 10);
+  const parsed = parseInt(varOrDefault(envVarName, String(defaultValue)), 10);
+  if (isNaN(parsed)) {
+    throw new Error(`Invalid integer value for ${envVarName}`);
+  }
+  return parsed;
 }

 export function optionalIntVar(envVarName: string): number | undefined {
   const value = varOrUndefined(envVarName);
-  return value !== undefined ? parseInt(value, 10) : undefined;
+  if (value === undefined) return undefined;
+  const parsed = parseInt(value, 10);
+  if (isNaN(parsed)) {
+    throw new Error(`Invalid integer value for ${envVarName}`);
+  }
+  return parsed;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function intVar(envVarName: string, defaultValue: number): number {
return parseInt(varOrDefault(envVarName, String(defaultValue)), 10);
}
export function optionalIntVar(envVarName: string): number | undefined {
const value = varOrUndefined(envVarName);
return value !== undefined ? parseInt(value, 10) : undefined;
}
export function intVar(envVarName: string, defaultValue: number): number {
const parsed = parseInt(varOrDefault(envVarName, String(defaultValue)), 10);
if (isNaN(parsed)) {
throw new Error(`Invalid integer value for ${envVarName}`);
}
return parsed;
}
export function optionalIntVar(envVarName: string): number | undefined {
const value = varOrUndefined(envVarName);
if (value === undefined) return undefined;
const parsed = parseInt(value, 10);
if (isNaN(parsed)) {
throw new Error(`Invalid integer value for ${envVarName}`);
}
return parsed;
}
🤖 Prompt for AI Agents
In src/lib/env.ts around lines 46 to 53, the functions intVar and optionalIntVar
use parseInt without validating the result, which can lead to NaN values if the
environment variable is not a valid integer. To fix this, add checks after
parseInt to verify the parsed value is a valid number (not NaN). For intVar,
throw an error or handle the invalid case if parseInt returns NaN. For
optionalIntVar, return undefined or handle the invalid case similarly when
parseInt yields NaN.

Comment on lines 252 to 253
export const STOP_HEIGHT = +env.varOrDefault('STOP_HEIGHT', 'Infinity');

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Mixed parsing patterns for numeric values.

Line 252 uses the new intVar while line 253 still uses the old +env.varOrDefault() pattern.

Convert for consistency:

 export const START_HEIGHT = env.intVar('START_HEIGHT', 0);
-export const STOP_HEIGHT = +env.varOrDefault('STOP_HEIGHT', 'Infinity');
+export const STOP_HEIGHT = env.intVar('STOP_HEIGHT', Infinity);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const STOP_HEIGHT = +env.varOrDefault('STOP_HEIGHT', 'Infinity');
export const START_HEIGHT = env.intVar('START_HEIGHT', 0);
export const STOP_HEIGHT = env.intVar('STOP_HEIGHT', Infinity);
🤖 Prompt for AI Agents
In src/config.ts around lines 252 to 253, the code uses mixed patterns for
parsing numeric values: line 252 uses the new intVar method while line 253 uses
the old +env.varOrDefault() pattern. To fix this, replace the usage of
+env.varOrDefault('STOP_HEIGHT', 'Infinity') with the intVar method to maintain
consistency in numeric parsing across the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant