Skip to content

Conversation

@adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Apr 30, 2025

Summary by CodeRabbit

  • Refactor
    • Approval record management is now unified under a single deployment version approval record system, simplifying approval tracking and validation.
    • Old approval record tables and related logic have been removed for a more streamlined approach.
    • New enums and validation schemas improve data consistency and type safety for approval records.
    • Internal naming and function usage have been updated for clarity and consistency.

- Changed the approval record schema from `policyRuleAnyApprovalRecord` to `deploymentVersionApprovalRecord`.
- Removed unused base approval record definitions and related validation fields.
- Updated approval record retrieval functions to use the new schema and improved parameter handling for role and user approvals.
- Cleaned up imports and adjusted related types for consistency.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 30, 2025

Walkthrough

This change consolidates approval record management by removing the old policyRule*ApprovalRecord tables and schemas and introducing a new unified deploymentVersionApprovalRecord table and schema. The codebase is updated to reference this new table for all approval record operations, including API mutations and rule engine logic. Supporting TypeScript enums and validation schemas are also updated or replaced. The refactor standardizes naming conventions and centralizes approval record handling, while removing now-obsolete base schema modules and exports.

Changes

File(s) Change Summary
packages/api/src/router/deployment-version-checks/approvals.ts Modified the addRecord mutation to insert into deploymentVersionApprovalRecord instead of policyRuleAnyApprovalRecord.
packages/db/src/schema/rbac.ts Added a new exported TypeScript enum, EntityTypeEnum, for entity types "user" and "team".
packages/db/src/schema/rules/approval-any.ts,
approval-role.ts,
approval-user.ts
Removed all references, schemas, types, and exports related to the old policyRule*ApprovalRecord tables.
packages/db/src/schema/rules/approval-base.ts Deleted the foundational approval record schema and validation logic module.
packages/db/src/schema/rules/approval-record.ts Introduced a new schema module defining the deploymentVersionApprovalRecord table, its validation schema, and supporting enums/types.
packages/db/src/schema/rules/index.ts Updated exports: removed approval-base, added approval-record.
packages/rule-engine/src/manager/version-manager-rules.ts Refactored imports and callbacks to use the new role/user approval record retrieval functions.
packages/rule-engine/src/rules/version-approval-rule.ts Refactored approval record logic to use the new unified table; renamed parameters for clarity; replaced and removed old approval record retrieval functions with new parameterized versions.
packages/db/src/schema/rules/rule-relations.ts Removed old approval record relations and replaced multiple user approval record relations with a single relation to deploymentVersionApprovalRecord. Added new relations for the unified approval record table.

Sequence Diagram(s)

sequenceDiagram
    participant API
    participant DB
    participant RuleEngine

    API->>DB: Insert into deploymentVersionApprovalRecord (on approval)
    RuleEngine->>DB: Query deploymentVersionApprovalRecord for approvals
    DB-->>API: Return approval record
    DB-->>RuleEngine: Return approval records
Loading

Possibly related PRs

  • ctrlplanedev/ctrlplane#454: Introduced the original policyRuleAnyApproval and policyRuleAnyApprovalRecord tables and schemas, which are now removed or replaced in this PR.

Suggested reviewers

  • jsbroks

Poem

In the garden of code, where approvals once sprawled,
Old tables uprooted, new schemas installed.
A single record blooms, unified and bright,
Bringing order to queries, and clarity to write.
The rabbits hop on, with enums in tow—
Cleaner, simpler, onward we go!
🐇✨

✨ 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.
    • 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.

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.

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

🧹 Nitpick comments (4)
packages/db/src/schema/rules/approval-record.ts (2)

36-38: approvedAt defaulting to NULL is redundant

In Postgres, the absence of a default already yields NULL. Dropping the explicit sql\NULL`` simplifies the DDL and avoids surprising diffs when generating migrations.


52-55: Consider a dedicated index on deploymentVersionId for query speed

All read paths shown in version-approval-rule.ts filter by deploymentVersionId only.
A composite UNIQUE index (deploymentVersionId, userId) cannot be used by Postgres for single-column look-ups, so large installations could see a full-index scan.

   uniqueDeploymentVersionIdUserId: uniqueIndex(
     "unique_deployment_version_id_user_id",
   ).on(t.deploymentVersionId, t.userId),
+
+  // Speeds up WHERE ... deployment_version_id IN (...)
+  byDeploymentVersionId: index("idx_approval_record_deployment_version_id").on(
+    t.deploymentVersionId,
+  ),
packages/rule-engine/src/rules/version-approval-rule.ts (2)

42-55: Quadratic filtering – convert to a map for O(n) look-ups

records.filter(…) inside candidates.filter yields O(n²) behaviour.
Building a Map<deploymentVersionId, ApprovalRecord[]> once avoids repeated scans.

-    const allowedCandidates = candidates.filter((release) => {
-      const records = approvalRecords.filter(
-        (r) => r.deploymentVersionId === release.id,
-      );
+    const recordsByVersion = _.groupBy(
+      approvalRecords,
+      (r) => r.deploymentVersionId,
+    );
+
+    const allowedCandidates = candidates.filter((release) => {
+      const records = recordsByVersion[release.id] ?? [];

114-125: Duplicate logic – reuse getAnyApprovalRecords

getUserApprovalRecordsFunc repeats the inArray + userId filter already possible by composing getAnyApprovalRecords and an in-memory filter. Extracting a shared low-level fetch keeps DB logic in one place and simplifies testability.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06db728 and 6a74d8f.

📒 Files selected for processing (10)
  • packages/api/src/router/deployment-version-checks/approvals.ts (1 hunks)
  • packages/db/src/schema/rbac.ts (1 hunks)
  • packages/db/src/schema/rules/approval-any.ts (1 hunks)
  • packages/db/src/schema/rules/approval-base.ts (0 hunks)
  • packages/db/src/schema/rules/approval-record.ts (1 hunks)
  • packages/db/src/schema/rules/approval-role.ts (0 hunks)
  • packages/db/src/schema/rules/approval-user.ts (0 hunks)
  • packages/db/src/schema/rules/index.ts (1 hunks)
  • packages/rule-engine/src/manager/version-manager-rules.ts (3 hunks)
  • packages/rule-engine/src/rules/version-approval-rule.ts (4 hunks)
💤 Files with no reviewable changes (3)
  • packages/db/src/schema/rules/approval-user.ts
  • packages/db/src/schema/rules/approval-base.ts
  • packages/db/src/schema/rules/approval-role.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: **Note on Error Handling:** Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error...

**/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

  • packages/api/src/router/deployment-version-checks/approvals.ts
  • packages/db/src/schema/rules/index.ts
  • packages/db/src/schema/rbac.ts
  • packages/rule-engine/src/manager/version-manager-rules.ts
  • packages/db/src/schema/rules/approval-any.ts
  • packages/rule-engine/src/rules/version-approval-rule.ts
  • packages/db/src/schema/rules/approval-record.ts
🧬 Code Graph Analysis (3)
packages/rule-engine/src/manager/version-manager-rules.ts (1)
packages/rule-engine/src/rules/version-approval-rule.ts (3)
  • VersionApprovalRule (32-72)
  • getRoleApprovalRecordsFunc (85-112)
  • getUserApprovalRecordsFunc (114-125)
packages/rule-engine/src/rules/version-approval-rule.ts (3)
packages/rule-engine/src/types.ts (1)
  • RuleEngineContext (23-28)
packages/db/src/schema/release.ts (1)
  • release (113-124)
packages/db/src/client.ts (1)
  • db (15-15)
packages/db/src/schema/rules/approval-record.ts (1)
packages/db/src/schema/auth.ts (1)
  • user (27-44)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Lint
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (8)
packages/db/src/schema/rules/index.ts (1)

9-9: Export of new approval record module.

This export adds the new unified schema for deployment version approval records, aligning with the refactoring to consolidate approval record management into a single table and schema.

packages/api/src/router/deployment-version-checks/approvals.ts (1)

87-87: Updated insert target to use the new unified approval record table.

The mutation now correctly inserts records into the new deploymentVersionApprovalRecord table instead of the previous approval record table, consistent with the schema consolidation.

packages/db/src/schema/rbac.ts (1)

34-37: Addition of EntityTypeEnum for strongly typed entity references.

The new enum provides a strongly typed alternative to the string literal values, improving type safety when filtering approval records by entity types in the rule engine.

packages/rule-engine/src/manager/version-manager-rules.ts (3)

6-7: Updated imports to use the new approval record retrieval functions.

These imports correctly reference the renamed higher-order functions for role and user approval record retrieval.


40-44: Updated role approval rule implementation to use the new function-returning paradigm.

The code now correctly destructures the input object to get roleId and requiredApprovalsCount, and uses the higher-order function getRoleApprovalRecordsFunc to create a specialized approval record retrieval function for the specific role.


53-57: Updated user approval rule implementation to use the new function-returning paradigm.

Similar to the role approval changes, this code now correctly destructures the input object to get userId and uses the higher-order function getUserApprovalRecordsFunc to create a specialized approval record retrieval function for the specific user.

packages/db/src/schema/rules/approval-any.ts (1)

12-19: Looks correct – table definition and validation in sync

requiredApprovalsCount is constrained both at the DB level (.notNull().default(1)) and at the Zod level (.min(1).default(1)), giving good defence-in-depth.
No further issues spotted in this segment.

packages/rule-engine/src/rules/version-approval-rule.ts (1)

85-112: Strengthen join condition & param naming

  1. The parameter is called versionIds but elsewhere the refactor standardises on deploymentVersionIds; keep naming consistent.
  2. Joining entityRole.entityId to userId is correct, but adding an explicit eq(entityRole.workspaceId, context.environment.workspaceId) (if available in your schema) prevents cross-workspace leakage.

Comment on lines +58 to +64
// Base validation fields for approval records
export const baseApprovalRecordValidationFields = {
deploymentVersionId: z.string().uuid(),
userId: z.string().uuid(),
status: z.enum(approvalStatus.enumValues),
reason: z.string().optional(),
};
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

Validation schema allows undefined but not null for reason

DB column reason is nullable; inserting null directly will violate Zod.

-  reason: z.string().optional(),
+  reason: z.string().nullable().optional(),
📝 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
// Base validation fields for approval records
export const baseApprovalRecordValidationFields = {
deploymentVersionId: z.string().uuid(),
userId: z.string().uuid(),
status: z.enum(approvalStatus.enumValues),
reason: z.string().optional(),
};
// Base validation fields for approval records
export const baseApprovalRecordValidationFields = {
deploymentVersionId: z.string().uuid(),
userId: z.string().uuid(),
status: z.enum(approvalStatus.enumValues),
reason: z.string().nullable().optional(),
};

Comment on lines +25 to +31
deploymentVersionId: uuid("deployment_version_id").notNull(),

// User who performed the approval/rejection action
userId: uuid("user_id")
.references(() => user.id)
.notNull(),

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

Missing FK to the deployment-version table may break referential integrity

deploymentVersionId is declared as a bare UUID. Without a .references(() => deploymentVersion.id …) clause the DB won’t enforce that the referenced deployment version actually exists, and cascaded deletes/updates are impossible.

-    deploymentVersionId: uuid("deployment_version_id").notNull(),
+    deploymentVersionId: uuid("deployment_version_id")
+      .notNull()
+      .references(() => deploymentVersion.id, { onDelete: "cascade" }),

(you’ll need to import deploymentVersion from its schema module at the top).

📝 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
deploymentVersionId: uuid("deployment_version_id").notNull(),
// User who performed the approval/rejection action
userId: uuid("user_id")
.references(() => user.id)
.notNull(),
deploymentVersionId: uuid("deployment_version_id")
.notNull()
.references(() => deploymentVersion.id, { onDelete: "cascade" }),
// User who performed the approval/rejection action
userId: uuid("user_id")
.references(() => user.id)
.notNull(),

Comment on lines +15 to 19
deploymentVersionId: string;
status: "approved" | "rejected";
userId: string;
reason: string | null;
};
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

Avoid shadowing the built-in Record utility type

Using the name Record hides the standard TS Record<K,V> helper and can trip up IDE auto-completion.

-type Record = {
+type ApprovalRecord = {
   deploymentVersionId: string;
   status: "approved" | "rejected";
   userId: string;
   reason: string | null;
 };

(remember to adjust other references).

📝 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
deploymentVersionId: string;
status: "approved" | "rejected";
userId: string;
reason: string | null;
};
type ApprovalRecord = {
deploymentVersionId: string;
status: "approved" | "rejected";
userId: string;
reason: string | null;
};

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 (1)
packages/db/src/schema/rules/rule-relations.ts (1)

71-83: Consider explicit cascade rules for referential integrity

When defining the deploymentVersionApprovalRecord relations you may want to specify onDelete / onUpdate behaviour so that dangling approval-records don’t linger if a deployment version or user is removed.

     deploymentVersion: one(deploymentVersion, {
       fields: [deploymentVersionApprovalRecord.deploymentVersionId],
       references: [deploymentVersion.id],
+      onDelete: "cascade",
     }),
     user: one(user, {
       fields: [deploymentVersionApprovalRecord.userId],
       references: [user.id],
+      onDelete: "cascade",
     }),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bb106c8 and 64434d9.

📒 Files selected for processing (1)
  • packages/db/src/schema/rules/rule-relations.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: **Note on Error Handling:** Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error...

**/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

  • packages/db/src/schema/rules/rule-relations.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
🔇 Additional comments (2)
packages/db/src/schema/rules/rule-relations.ts (2)

13-16: Verify downstream renaming to user.approvalRecords

userApprovalRelations now exposes a single approvalRecords collection that points to deploymentVersionApprovalRecord.
Please confirm every caller that previously accessed user.[any|role|user]ApprovalRecords (or similar) has been migrated to the new property; otherwise those look-ups will fail at runtime.


6-9:

✅ Verification successful

Confirm obsolete schema imports haven’t crept back in

The refactor description states that the policyRule*ApprovalRecord tables were removed, yet we still import policyRuleAnyApproval, policyRuleRoleApproval, and policyRuleUserApproval.
If these modules were also meant to be retired (or renamed), the build will break once the files disappear. Please double-check that the three imports – and the relation blocks that use them – really are still needed.


🏁 Script executed:

#!/bin/bash
# List any remaining approval-record-style schema files – output should be empty.
fd -a "policyRule*ApprovalRecord" packages/db/src/schema || true
# Confirm the three approval schema files still exist.
fd -a "approval-{any,role,user}.ts" packages/db/src/schema/rules

Length of output: 449


Let’s re-run with glob patterns to accurately check for both the removed records and the existing rule files:


🏁 Script executed:

#!/bin/bash
# 1) Look for any leftover ApprovalRecord schema files (should be none)
fd --glob 'policyRule*ApprovalRecord.ts' packages/db/src/schema || echo "No ApprovalRecord files found."

# 2) Verify the three approval-rule modules still exist
fd --glob 'approval-any.ts' packages/db/src/schema/rules || echo "approval-any.ts missing!"
fd --glob 'approval-role.ts' packages/db/src/schema/rules || echo "approval-role.ts missing!"
fd --glob 'approval-user.ts' packages/db/src/schema/rules || echo "approval-user.ts missing!"

Length of output: 375


No obsolete schema imports detected

All policyRule*ApprovalRecord.ts files have been removed, and the three imported modules still exist:

  • packages/db/src/schema/rules/approval-any.ts
  • packages/db/src/schema/rules/approval-role.ts
  • packages/db/src/schema/rules/approval-user.ts

The imports in packages/db/src/schema/rules/rule-relations.ts are valid and required.

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