Skip to content
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

Enhanced care config to validate env during build process #9032

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

Alokih
Copy link

@Alokih Alokih commented Nov 6, 2024

Proposed Changes

  • Fixes Enhancements to care config #8470
  • Vite build process now includes validation of the required environment variables using the @julr/vite-plugin-validate-env plugin
  • Sentry & Plausible are optional & will only be enabled if env are configured correctly

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Added new dependencies for environment validation (@julr/vite-plugin-validate-env and zod).
    • Integrated environment validation within the configuration setup to ensure required variables are defined.
  • Bug Fixes

    • Enhanced error handling in the Plausible and Sentry components to ensure correct configuration before execution.
  • Documentation

    • Improved internal documentation related to configuration checks and error handling mechanisms.

@Alokih Alokih requested a review from a team as a code owner November 6, 2024 18:14
Copy link

coderabbitai bot commented Nov 6, 2024

Walkthrough

The pull request introduces several changes across multiple files. In package.json, two new development dependencies, @julr/vite-plugin-validate-env and zod, are added. The Plausible and Sentry components are updated to include validation checks for their respective configurations, enhancing error handling. Additionally, vite.config.mts is modified to integrate the ValidateEnv plugin for environment variable validation, ensuring the correctness of configurations during the build process.

Changes

File Change Summary
package.json Added @julr/vite-plugin-validate-env and zod to devDependencies.
src/Integrations/Plausible.tsx Added validation checks for careConfig.plausible.domain and careConfig.plausible.server.
src/Integrations/Sentry.tsx Expanded validation checks to include careConfig.sentry.environment.
vite.config.mts Added ValidateEnv and z imports; integrated environment validation into the Vite config.

Assessment against linked issues

Objective Addressed Explanation
Perform config validation during vite build
Sentry config to be optional and enable sentry only if configured
Plausible config to be optional and enable plausible only if configured

Poem

🐰 In the garden where code does thrive,
New plugins and checks help us survive.
With Sentry and Plausible, all set to go,
Our configs are ready, let the builds flow!
Hopping with joy, we celebrate today,
For robust code keeps the bugs at bay! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5966af0 and 7a897b4.

📒 Files selected for processing (2)
  • src/Integrations/Plausible.tsx (1 hunks)
  • vite.config.mts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/Integrations/Plausible.tsx
  • vite.config.mts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

netlify bot commented Nov 6, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 7a897b4
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/672c51fba30cff00081ae4ec
😎 Deploy Preview https://deploy-preview-9032--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

@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: 2

🧹 Outside diff range and nitpick comments (5)
src/Integrations/Sentry.tsx (1)

11-13: Consider making the error message more specific.

The current error message could be more helpful by indicating which specific configuration is missing (dsn, environment, or if it's disabled).

-      console.error(
-        "Sentry is not configured correctly. Please check your environment variables.",
-      );
+      console.debug(
+        `Sentry initialization skipped: ${
+          disabled ? "explicitly disabled" :
+          !careConfig.sentry.dsn ? "missing DSN" :
+          !careConfig.sentry.environment ? "missing environment" :
+          "unknown reason"
+        }`
+      );
src/Integrations/Plausible.tsx (2)

13-19: Consider preventing Script component mounting when config is invalid.

The Script component still mounts even when the configuration is invalid, which could lead to unnecessary network requests or script errors.

Consider refactoring the component to handle this case:

+ const isValidConfig = careConfig.plausible.domain && careConfig.plausible.server;
+
  useEffect(() => {
-    if (!careConfig.plausible.domain || !careConfig.plausible.server) {
+    if (!isValidConfig) {
      console.error(
        "Plausible is not configured correctly. Please check your environment variables.",
      );
      return;
    }

    plausible("pageview");
  }, []);

-  return (
+  return isValidConfig ? (
    <Script
      defer
      data-domain={careConfig.plausible.domain}
      src={`${careConfig.plausible.server}/js/script.manual.tagged-events.js`}
    />
+  ) : null;

Also applies to: 22-31


Line range hint 7-12: Consolidate validation logic across event triggers.

The validation check should also be applied to the location change handler to maintain consistency.

Consider extracting the validation to a reusable function:

+ const isValidConfig = () => {
+   const missingConfig = [];
+   if (!careConfig.plausible.domain) missingConfig.push('domain');
+   if (!careConfig.plausible.server) missingConfig.push('server');
+   
+   if (missingConfig.length > 0) {
+     console.error(
+       `Plausible analytics disabled. Missing configuration: ${missingConfig.join(', ')}`,
+     );
+     return false;
+   }
+   return true;
+ };
+
  useLocationChange(() => {
+   if (!isValidConfig()) return;
    plausible("pageview");
  });
package.json (1)

102-102: LGTM! Dependencies align with PR objectives.

The addition of @julr/vite-plugin-validate-env and zod packages will enable environment variable validation during the build process, preventing runtime issues from misconfiguration.

Consider updating zod to the latest version (^3.22.4) for potential bug fixes and improvements.

Also applies to: 150-150

vite.config.mts (1)

106-117: LGTM! Environment validation is well implemented with room for enhancement.

The ValidateEnv plugin configuration successfully addresses all PR objectives:

  • Required API URL validation
  • Optional Sentry configuration
  • Optional Plausible configuration

Consider these enhancements for better developer experience:

 ValidateEnv({
   validator: "zod",
   schema: {
-    REACT_CARE_API_URL: z.string().url(),
+    REACT_CARE_API_URL: z.string().url().describe("Required: The Care API endpoint URL"),

-    REACT_SENTRY_DSN: z.string().url().optional(),
-    REACT_SENTRY_ENVIRONMENT: z.string().optional(),
+    // Group Sentry-related ENVs
+    REACT_SENTRY_DSN: z.string().url().optional()
+      .describe("Optional: Sentry Data Source Name for error tracking"),
+    REACT_SENTRY_ENVIRONMENT: z.string()
+      .regex(/^(development|staging|production)$/)
+      .optional()
+      .describe("Optional: Environment for Sentry (development|staging|production)"),

-    REACT_PLAUSIBLE_SITE_DOMAIN: z.string().url().optional(),
-    REACT_PLAUSIBLE_SERVER_URL: z.string().url().optional(),
+    // Group Plausible-related ENVs
+    REACT_PLAUSIBLE_SITE_DOMAIN: z.string().url().optional()
+      .describe("Optional: Domain for Plausible analytics"),
+    REACT_PLAUSIBLE_SERVER_URL: z.string().url().optional()
+      .describe("Optional: Plausible server URL"),
   },
 }),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c27f595 and 5966af0.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • package.json (2 hunks)
  • src/Integrations/Plausible.tsx (1 hunks)
  • src/Integrations/Sentry.tsx (1 hunks)
  • vite.config.mts (2 hunks)
🔇 Additional comments (4)
src/Integrations/Sentry.tsx (1)

10-13: LGTM! Enhanced validation aligns with making Sentry optional.

The additional check for careConfig.sentry.environment improves the validation logic and properly implements the requirement to make Sentry configuration optional.

src/Integrations/Plausible.tsx (1)

13-19: Verify environment variable validation schema.

The validation here should align with the Vite environment variable validation schema mentioned in the PR objectives.

Let's verify the environment variable validation setup:

✅ Verification successful

Environment variable validation is properly configured

The validation in src/Integrations/Plausible.tsx aligns with the environment variable schema defined in src/vite-env.d.ts and the default configuration in care.config.ts:

  • Environment variables are typed in vite-env.d.ts:
    readonly REACT_PLAUSIBLE_SERVER_URL?: string;
    readonly REACT_PLAUSIBLE_SITE_DOMAIN?: string;
  • Default values are provided in care.config.ts:
    plausible: {
      server: env.REACT_PLAUSIBLE_SERVER_URL || "https://plausible.ohc.network",
      domain: env.REACT_PLAUSIBLE_SITE_DOMAIN || "care.ohc.network",
    }
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for environment variable validation schema in vite config
echo "Searching for Plausible environment validation schema..."
rg -l "plausible.*domain|plausible.*server" "vite.config"

# Check for any existing environment variable documentation
echo "Checking for environment variable documentation..."
fd -g "*env*" -g "*.md" -x cat {} \; 

Length of output: 477


Script:

#!/bin/bash
# Let's try different approaches to find configuration files
echo "Searching for vite configuration files..."
fd -e ts -e js -g "*vite*"

echo "Searching for environment variable schema or validation..."
rg -i "plausible|env.*schema|env.*valid" --type ts --type js -A 3

echo "Searching for environment configuration files..."
fd -g "*.env*"

echo "Looking for configuration related files..."
fd -g "*config*"

Length of output: 7832

package.json (1)

102-102: Verify the integration of new dependencies.

Let's ensure these packages are properly integrated into the build configuration.

Also applies to: 150-150

✅ Verification successful

Let me gather more information about the vite configuration files since the previous search pattern didn't work correctly.


Dependencies are properly integrated and used in the build configuration

The verification shows that:

  • @julr/vite-plugin-validate-env is correctly imported and used in the vite configuration
  • The plugin is properly configured with zod schema for environment validation
  • No version conflicts were found in the dependencies
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration of new dependencies in vite.config

# Test 1: Check if vite.config imports the new packages
echo "Checking vite.config imports..."
rg -l "@julr/vite-plugin-validate-env|zod" "vite.config*"

# Test 2: Look for any potential version conflicts in package-lock.json
echo "Checking for version conflicts..."
if [ -f "package-lock.json" ]; then
    rg -A 5 '"@julr/vite-plugin-validate-env"|"zod"' package-lock.json
fi

Length of output: 928


Script:

#!/bin/bash
# Search for vite config files with any extension
echo "Looking for vite config files..."
fd "vite.config" --type f

# If found, check their content
echo -e "\nChecking content of vite config files..."
fd "vite.config" --type f --exec cat {}

Length of output: 8144

vite.config.mts (1)

1-13: LGTM! Import statements are correctly structured.

The new imports for ValidateEnv and zod are appropriately added to support environment variable validation during the build process.

Comment on lines 13 to 18
if (!careConfig.plausible.domain || !careConfig.plausible.server) {
console.error(
"Plausible is not configured correctly. Please check your environment variables.",
);
return;
}
Copy link

@coderabbitai coderabbitai bot Nov 6, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance validation handling and error reporting.

While the validation logic is a good addition, there are several improvements that could make it more robust:

Consider applying these changes:

-    if (!careConfig.plausible.domain || !careConfig.plausible.server) {
-      console.error(
-        "Plausible is not configured correctly. Please check your environment variables.",
-      );
-      return;
-    }
+    const missingConfig = [];
+    if (!careConfig.plausible.domain) missingConfig.push('domain');
+    if (!careConfig.plausible.server) missingConfig.push('server');
+    
+    if (missingConfig.length > 0) {
+      console.error(
+        `Plausible analytics disabled. Missing configuration: ${missingConfig.join(', ')}`,
+      );
+      return;
+    }
📝 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
if (!careConfig.plausible.domain || !careConfig.plausible.server) {
console.error(
"Plausible is not configured correctly. Please check your environment variables.",
);
return;
}
const missingConfig = [];
if (!careConfig.plausible.domain) missingConfig.push('domain');
if (!careConfig.plausible.server) missingConfig.push('server');
if (missingConfig.length > 0) {
console.error(
`Plausible analytics disabled. Missing configuration: ${missingConfig.join(', ')}`,
);
return;
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Go ahead and make the changes suggested by coderabbit @Alokih

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

vite.config.mts Outdated
Comment on lines 106 to 117
ValidateEnv({
validator: "zod",
schema: {
REACT_CARE_API_URL: z.string().url(),

REACT_SENTRY_DSN: z.string().url().optional(),
REACT_SENTRY_ENVIRONMENT: z.string().optional(),

REACT_PLAUSIBLE_SITE_DOMAIN: z.string().url().optional(),
REACT_PLAUSIBLE_SERVER_URL: z.string().url().optional(),
},
}),
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding validation for CDN URLs configuration.

The REACT_CDN_URLS environment variable is used in the configuration but lacks validation. Consider adding validation to ensure it contains valid URLs when provided:

 ValidateEnv({
   validator: "zod",
   schema: {
     REACT_CARE_API_URL: z.string().url(),

     REACT_SENTRY_DSN: z.string().url().optional(),
     REACT_SENTRY_ENVIRONMENT: z.string().optional(),

     REACT_PLAUSIBLE_SITE_DOMAIN: z.string().url().optional(),
     REACT_PLAUSIBLE_SERVER_URL: z.string().url().optional(),
+
+    // Validate space-separated CDN URLs
+    REACT_CDN_URLS: z.string()
+      .optional()
+      .transform((val) => val?.split(" "))
+      .pipe(
+        z.array(z.string().url())
+        .optional()
+      )
+      .describe("Optional: Space-separated list of CDN URLs"),
   },
 }),
📝 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
ValidateEnv({
validator: "zod",
schema: {
REACT_CARE_API_URL: z.string().url(),
REACT_SENTRY_DSN: z.string().url().optional(),
REACT_SENTRY_ENVIRONMENT: z.string().optional(),
REACT_PLAUSIBLE_SITE_DOMAIN: z.string().url().optional(),
REACT_PLAUSIBLE_SERVER_URL: z.string().url().optional(),
},
}),
ValidateEnv({
validator: "zod",
schema: {
REACT_CARE_API_URL: z.string().url(),
REACT_SENTRY_DSN: z.string().url().optional(),
REACT_SENTRY_ENVIRONMENT: z.string().optional(),
REACT_PLAUSIBLE_SITE_DOMAIN: z.string().url().optional(),
REACT_PLAUSIBLE_SERVER_URL: z.string().url().optional(),
// Validate space-separated CDN URLs
REACT_CDN_URLS: z.string()
.optional()
.transform((val) => val?.split(" "))
.pipe(
z.array(z.string().url())
.optional()
)
.describe("Optional: Space-separated list of CDN URLs"),
},
}),

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

Successfully merging this pull request may close these issues.

Enhancements to care config
2 participants