Skip to content

Sync env vars (parent env vars) #2120

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

Merged
merged 6 commits into from
May 29, 2025
Merged

Sync env vars (parent env vars) #2120

merged 6 commits into from
May 29, 2025

Conversation

matt-aitken
Copy link
Member

syncEnvVars (and syncVercelEnvVars) would only sync the environment, not the parent environment's variables.

This is relevant for syncing preview env vars, where you want to set the "Preview" env vars AND the override for the specific environment (if there is an override).

Copy link

changeset-bot bot commented May 29, 2025

⚠️ No Changeset found

Latest commit: ee58d0f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented May 29, 2025

Walkthrough

This set of changes introduces support for handling "parent environment" variables across the application's environment variable management, build, and deployment systems. The changes extend environment variable schemas, types, and APIs to allow an optional parentEnv or parentVariables property. Environment variable synchronization logic in both the build system and CLI now processes and transmits these parent environment variables separately from standard environment variables. Error handling for deployment and schedule syncing is refined to preserve original error details when appropriate. Additionally, logic for environment and schedule counting is updated to account for archived environments, and new debug logging is added throughout the deployment and syncing processes for improved traceability. No breaking changes to exported function signatures occur except for the addition of optional parameters and properties related to parent environment variables.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fb81d6f and ee58d0f.

📒 Files selected for processing (1)
  • packages/cli-v3/src/commands/deploy.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/cli-v3/src/commands/deploy.ts
⏰ Context from checks skipped due to timeout of 90000ms (25)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (8, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (7, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (10, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (6, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (9, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (5, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (8, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (4, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (7, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (3, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (6, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (2, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (5, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (1, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (4, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (3, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (2, 10)
  • GitHub Check: units / packages / 🧪 Unit Tests: Packages (1, 1)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (1, 10)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
✨ 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.

@matt-aitken matt-aitken marked this pull request as ready for review May 29, 2025 10:52
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: 0

🧹 Nitpick comments (3)
apps/webapp/app/routes/api.v1.projects.$projectRef.envvars.$slug.import.ts (1)

50-74: Consider clarifying partial success behavior.

The current logic returns success if either the child or parent environment variable import succeeds, even if the other fails. This could lead to confusion as users might expect both operations to succeed.

Consider:

  1. Adding logging to indicate partial success scenarios
  2. Returning more detailed status information about which operations succeeded/failed
  3. Documenting the expected behavior when only one environment import succeeds

Example enhancement:

-    if (result.success || parentResult.success) {
-      return json({ success: true });
+    if (result.success && parentResult.success) {
+      return json({ success: true });
+    } else if (result.success || parentResult.success) {
+      return json({ 
+        success: true, 
+        partial: true,
+        childSuccess: result.success,
+        parentSuccess: parentResult.success 
+      });
     } else {
packages/cli-v3/src/build/extensions.ts (1)

163-181: Refactor to reduce code duplication.

The new parentEnv handling logic correctly follows the same pattern as the existing env variable logic. However, there's code duplication in the initialization logic (lines 164-166) that already exists above (lines 143-146).

Consider consolidating the initialization logic:

  if (layer.deploy?.env) {
    $manifest.deploy.env ??= {};
    $manifest.deploy.sync ??= {};
    $manifest.deploy.sync.env ??= {};
    $manifest.deploy.sync.parentEnv ??= {};

    for (const [key, value] of Object.entries(layer.deploy.env)) {
      // ... existing logic
    }
  }

+ if (layer.deploy?.env || layer.deploy?.parentEnv) {
+   $manifest.deploy.env ??= {};
+   $manifest.deploy.sync ??= {};
+   $manifest.deploy.sync.env ??= {};
+   $manifest.deploy.sync.parentEnv ??= {};
+ }
+
+ if (layer.deploy?.env) {
+   for (const [key, value] of Object.entries(layer.deploy.env)) {
+     // ... existing logic
+   }
+ }

  if (layer.deploy?.parentEnv) {
-   $manifest.deploy.env ??= {};
-   $manifest.deploy.sync ??= {};
-   $manifest.deploy.sync.parentEnv ??= {};

    for (const [key, value] of Object.entries(layer.deploy.parentEnv)) {
      // ... rest of logic
    }
  }
apps/webapp/app/services/upsertBranch.server.ts (1)

149-175: LGTM! Improved branch limit logic with performance consideration.

The updated logic correctly excludes the current branch being created/updated from the limit count, preventing false limit violations. The change from a count() query to findMany() with filtering is necessary to implement this logic.

For large projects with many branches, consider the performance impact of fetching all branch records vs. using a more targeted query:

  const usedEnvs = await prisma.runtimeEnvironment.findMany({
    where: {
      projectId,
      branchName: {
        not: null,
+       ...(newBranchName && { not: newBranchName }),
      },
      archivedAt: null,
    },
+   select: {
+     id: true,
+     branchName: true,
+   },
  });

- const count = newBranchName
-   ? usedEnvs.filter((env) => env.branchName !== newBranchName).length
-   : usedEnvs.length;
+ const count = usedEnvs.length;

This approach reduces memory usage and potentially improves query performance by filtering at the database level and selecting only necessary fields.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b46371 and 04918be.

⛔ Files ignored due to path filters (1)
  • references/hello-world/trigger.config.ts is excluded by !references/**
📒 Files selected for processing (14)
  • apps/webapp/app/presenters/v3/ScheduleListPresenter.server.ts (1 hunks)
  • apps/webapp/app/routes/api.v1.projects.$projectRef.envvars.$slug.import.ts (1 hunks)
  • apps/webapp/app/services/upsertBranch.server.ts (3 hunks)
  • apps/webapp/app/v3/services/checkSchedule.server.ts (1 hunks)
  • apps/webapp/app/v3/services/createBackgroundWorker.server.ts (1 hunks)
  • apps/webapp/app/v3/services/createDeploymentBackgroundWorker.server.ts (1 hunks)
  • packages/build/src/extensions/core/syncEnvVars.ts (4 hunks)
  • packages/build/src/extensions/core/vercelSyncEnvVars.ts (3 hunks)
  • packages/cli-v3/src/build/extensions.ts (2 hunks)
  • packages/cli-v3/src/commands/deploy.ts (6 hunks)
  • packages/cli-v3/src/commands/workers/build.ts (2 hunks)
  • packages/core/src/v3/build/extensions.ts (1 hunks)
  • packages/core/src/v3/schemas/api.ts (1 hunks)
  • packages/core/src/v3/schemas/build.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
apps/webapp/app/v3/services/createDeploymentBackgroundWorker.server.ts (1)
internal-packages/run-engine/src/engine/errors.ts (1)
  • ServiceValidationError (59-67)
apps/webapp/app/v3/services/createBackgroundWorker.server.ts (1)
internal-packages/run-engine/src/engine/errors.ts (1)
  • ServiceValidationError (59-67)
⏰ Context from checks skipped due to timeout of 90000ms (25)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (10, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (9, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (8, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (7, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (8, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (6, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (7, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (5, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (6, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (4, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (5, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (3, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (4, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (2, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (3, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (1, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (2, 8)
  • GitHub Check: units / packages / 🧪 Unit Tests: Packages (1, 1)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (1, 8)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (22)
packages/core/src/v3/schemas/api.ts (1)

808-808: LGTM! Well-designed schema extension.

The addition of the optional parentVariables field follows the same type pattern as the existing variables field and maintains backward compatibility. This properly supports the parent environment variables feature without introducing breaking changes.

apps/webapp/app/presenters/v3/ScheduleListPresenter.server.ts (1)

72-72: LGTM! Logical field addition for archived environment handling.

Adding the archivedAt field to the environment selection is consistent with the existing pattern and enables proper filtering of archived environments in schedule counting logic.

packages/core/src/v3/build/extensions.ts (1)

65-65: LGTM! Consistent interface extension.

The addition of the optional parentEnv field follows the exact same type pattern as the existing env field, maintaining consistency and backward compatibility while supporting the parent environment variables feature.

apps/webapp/app/v3/services/createDeploymentBackgroundWorker.server.ts (1)

117-120: LGTM! Excellent error handling improvement.

This change properly preserves original ServiceValidationError instances while maintaining the fallback behavior for other error types. This prevents loss of specific error details from upstream services and follows error handling best practices.

packages/core/src/v3/schemas/build.ts (1)

55-55: LGTM! Schema extension follows existing patterns.

The addition of the optional parentEnv property follows the same structure and typing as the existing env property, maintaining consistency and backward compatibility.

apps/webapp/app/v3/services/createBackgroundWorker.server.ts (1)

150-152: Excellent error handling improvement!

This change preserves the original ServiceValidationError details when re-throwing, preventing the loss of specific error information that would occur if the error were wrapped in a generic message.

apps/webapp/app/v3/services/checkSchedule.server.ts (1)

111-115: LGTM! Proper filtering of archived environments.

The updated filtering logic correctly excludes both development and archived environments from schedule counting, ensuring that only active, deployed environments contribute to schedule limits. The type signature update properly reflects the required archivedAt field.

packages/build/src/extensions/core/vercelSyncEnvVars.ts (3)

4-4: LGTM! Clean type definition.

The EnvVar type with the optional isParentEnv flag is well-defined and supports the new parent environment variable functionality.


78-91: LGTM! Sound logic for parent environment detection.

The logic for determining parent environment variables is well-implemented:

  • isBranchable correctly identifies preview environments
  • Parent env vars are those without a gitBranch property in branchable environments
  • The mapping preserves all original properties while adding the new flag

62-62:

✅ Verification successful

Verify the URL parameter simplification doesn't break existing functionality.

The URL construction was simplified by removing conditional gitBranch parameter handling and adding a fixed target parameter. Ensure this change is intentional and doesn't break existing Vercel API integrations.


🏁 Script executed:

#!/bin/bash
# Search for other usages of gitBranch parameter in Vercel API calls
rg -A 5 -B 5 "gitBranch.*vercel|vercel.*gitBranch"

Length of output: 52


🏁 Script executed:

#!/bin/bash
# Locate the vercelSyncEnvVars file and print context around line 62
file=$(fd vercelSyncEnvVars.ts -t f | head -n1)
echo "Inspecting $file (lines 50–80):"
sed -n '50,80p' "$file"

# Search for any usage of a "branch" parameter in Vercel API calls
rg -n 'params\.(set|append)\("branch"' -A3 -B3

Length of output: 1360


No ‘gitBranch’ usages found—URL simplification is safe
I searched the entire repo for any branch or gitBranch query parameters in Vercel API calls and found no matches. The only supported filters on /v8/projects/:id/env are target and (optionally) teamId, so replacing conditional branch logic with a fixed params.set("target", …) won’t break any existing integrations.

packages/cli-v3/src/commands/workers/build.ts (2)

284-286: LGTM! Clean integration of parent environment variables.

The function call correctly passes both regular and parent environment variables to the sync function, maintaining the existing pattern while extending functionality.


460-466: LGTM! Backward-compatible function signature update.

The syncEnvVarsWithServer function signature is properly updated to accept optional parentEnvVars, maintaining backward compatibility while extending functionality to support parent environment variable synchronization.

apps/webapp/app/services/upsertBranch.server.ts (1)

79-81: LGTM! Proper parameter passing for improved branch limit logic.

The updated call correctly passes the sanitized branch name to enable more accurate limit checking that excludes the current branch being created/updated.

packages/build/src/extensions/core/syncEnvVars.ts (4)

3-5: LGTM! Clean type extension for parent environment support.

The addition of the optional isParentEnv flag to the array format provides a clean way to distinguish between regular and parent environment variables.


101-131: Well-structured implementation of parent environment variable support.

The changes correctly handle the separation and filtering of regular and parent environment variables. The debug logging at line 117 will be helpful for troubleshooting deployment issues.


135-152: Good refactoring: Extracted filtering logic improves maintainability.

Extracting the environment variable filtering logic into a dedicated function improves code organization and makes it reusable for both env and parentEnv.


160-206: Correct implementation of parent environment variable separation.

The function properly handles both array and object return formats from the sync function, correctly separating variables based on the isParentEnv flag while maintaining backward compatibility.

packages/cli-v3/src/commands/deploy.ts (5)

354-397: Comprehensive parent environment variable syncing implementation.

The implementation correctly:

  • Checks for variables in both env and parentEnv sets
  • Safely extracts variables with fallback to empty objects
  • Accurately counts the total number of variables
  • Passes both sets to the sync function

The logic handles all edge cases properly.


510-526: Improved error handling with detailed deployment error information.

Good enhancement that extracts and uses detailed error data from the deployment response when available, providing more informative error messages to users while maintaining a fallback for cases where error data is unavailable.


622-638: Clean extension of sync function to support parent environment variables.

The function signature maintains backward compatibility with the optional parentEnvVars parameter, and the implementation correctly passes parent variables to the API. The debug logging will help with troubleshooting sync issues.


649-649: Helpful debug logging for deployment failures.

The debug logging will assist in troubleshooting deployment failures by capturing the full context.


710-710: Important fix: Display error message instead of error name.

Good catch! This ensures users see the actual error message content rather than just the error type name, providing much more useful information.

@matt-aitken matt-aitken merged commit 7ecaf2c into main May 29, 2025
33 checks passed
@matt-aitken matt-aitken deleted the vercel-sync-preview-envs branch May 29, 2025 11:18
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.

2 participants