Skip to content

Conversation

@adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Apr 20, 2025

Summary by CodeRabbit

  • New Features
    • Resource deletions are now processed asynchronously, improving reliability and scalability.
  • Refactor
    • Internal deletion logic updated to use an event-driven queue instead of immediate deletion.
  • Bug Fixes
    • Enhanced filtering ensures only non-deleted resources are considered in deployment and environment matching.
  • Chores
    • Updated event channel types and mappings to support new deletion workflow.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 20, 2025

Walkthrough

This change introduces an asynchronous, event-driven approach to resource deletion across the system. A new worker, deleteResourceWorker, is added to handle deletions on the DeleteResource channel. All direct, synchronous resource deletion calls are replaced with jobs enqueued to this channel, allowing deletions to be processed in the background. The worker ensures all related entities (such as deployments, environment resources, and release targets) are properly handled within a transaction. Additionally, resource selection logic is updated to consider the deletedAt field, and event types are expanded to include DeleteResource.

Changes

File(s) Change Summary
apps/event-worker/src/workers/delete-resource.ts Added deleteResourceWorker to process resource deletion events, handling cascading deletions and event dispatching.
apps/event-worker/src/workers/index.ts Registered deleteResourceWorker under Channel.DeleteResource in the workers map.
apps/webservice/src/app/api/v1/resources/[resourceId]/route.ts
apps/webservice/src/app/api/v1/workspaces/[workspaceId]/resources/identifier/[identifier]/route.ts
Replaced direct resource deletion with enqueuing deletion jobs to Channel.DeleteResource.
packages/api/src/router/resources.ts Modified the delete mutation to enqueue deletion jobs instead of deleting resources directly.
packages/db/src/selectors/compute/deployment-builder.ts
packages/db/src/selectors/compute/environment-builder.ts
packages/db/src/selectors/compute/resource-builder.ts
Updated resource queries to include a filter on deletedAt being null (exclude deleted resources).
packages/events/src/types.ts Added Channel.DeleteResource and Channel.UpdatedResource to ChannelMap; reorganized and deduplicated entries.
packages/job-dispatch/src/resource/handle-provider-scan.ts Replaced direct resource deletion with enqueuing deletion jobs to Channel.DeleteResource.

Sequence Diagram(s)

sequenceDiagram
    participant API
    participant Queue
    participant Worker
    participant DB

    API->>Queue: Enqueue DeleteResource job (resourceId, resource)
    Queue->>Worker: Dispatch DeleteResource job
    Worker->>DB: Begin transaction
    Worker->>DB: Soft delete resource (set deletedAt)
    Worker->>DB: Delete related deployments, env resources, release targets
    Worker->>DB: Commit transaction
    Worker->>Queue: Dispatch DeploymentResourceRemoved events (for exit hooks)
Loading

Possibly related PRs

Suggested reviewers

  • jsbroks

Poem

In the warren of code, a new worker hops,
Deleting old resources, it never stops.
No more direct calls—just queue up the deed,
The worker will handle each deletion with speed.
With soft deletes and hooks, it keeps things neat,
Asynchronous burrows make our system complete!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ac8977e and 311a41f.

📒 Files selected for processing (3)
  • packages/db/src/selectors/compute/deployment-builder.ts (3 hunks)
  • packages/db/src/selectors/compute/environment-builder.ts (3 hunks)
  • packages/db/src/selectors/compute/resource-builder.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/db/src/selectors/compute/resource-builder.ts
  • packages/db/src/selectors/compute/environment-builder.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/db/src/selectors/compute/deployment-builder.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (3)
packages/db/src/selectors/compute/deployment-builder.ts (3)

6-6: Added import matches implementation needs.

Appropriate addition of the isNull import to support the new filtering conditions for excluding deleted resources.


49-49: Correctly implemented resource filtering to exclude deleted resources.

This change ensures that only non-deleted resources (where deletedAt is null) are matched to deployments. The implementation properly supports the new asynchronous resource deletion workflow.


124-124: Correctly implemented resource filtering in WorkspaceDeploymentBuilder.

Similar to the DeploymentBuilder implementation, this change ensures that only non-deleted resources are matched to deployments in the workspace context.

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

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

🧹 Nitpick comments (1)
apps/event-worker/src/workers/delete-resource.ts (1)

44-61: Consider adding error logging for hook failures.

Using Promise.allSettled ensures all hooks are processed regardless of individual failures, which is excellent. However, consider adding logging for rejected promises to help with debugging.

-  await Promise.allSettled(handleEventPromises);
+  const results = await Promise.allSettled(handleEventPromises);
+  // Log any errors for observability
+  results
+    .filter((result): result is PromiseRejectedResult => result.status === "rejected")
+    .forEach((result, index) => {
+      console.error(`Failed to handle event for deployment ${deployments[index].id}:`, result.reason);
+    });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 45ff1d3 and ac8977e.

📒 Files selected for processing (10)
  • apps/event-worker/src/workers/delete-resource.ts (1 hunks)
  • apps/event-worker/src/workers/index.ts (2 hunks)
  • apps/webservice/src/app/api/v1/resources/[resourceId]/route.ts (1 hunks)
  • apps/webservice/src/app/api/v1/workspaces/[workspaceId]/resources/identifier/[identifier]/route.ts (2 hunks)
  • packages/api/src/router/resources.ts (2 hunks)
  • packages/db/src/selectors/compute/deployment-builder.ts (2 hunks)
  • packages/db/src/selectors/compute/environment-builder.ts (2 hunks)
  • packages/db/src/selectors/compute/resource-builder.ts (3 hunks)
  • packages/events/src/types.ts (1 hunks)
  • packages/job-dispatch/src/resource/handle-provider-scan.ts (1 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/selectors/compute/resource-builder.ts
  • packages/db/src/selectors/compute/environment-builder.ts
  • packages/db/src/selectors/compute/deployment-builder.ts
  • apps/event-worker/src/workers/index.ts
  • apps/webservice/src/app/api/v1/workspaces/[workspaceId]/resources/identifier/[identifier]/route.ts
  • packages/job-dispatch/src/resource/handle-provider-scan.ts
  • packages/api/src/router/resources.ts
  • packages/events/src/types.ts
  • apps/webservice/src/app/api/v1/resources/[resourceId]/route.ts
  • apps/event-worker/src/workers/delete-resource.ts
🧬 Code Graph Analysis (3)
apps/event-worker/src/workers/index.ts (1)
apps/event-worker/src/workers/delete-resource.ts (1)
  • deleteResourceWorker (63-74)
packages/job-dispatch/src/resource/handle-provider-scan.ts (2)
packages/events/src/index.ts (1)
  • getQueue (28-34)
packages/db/src/selectors/index.ts (1)
  • selector (18-18)
packages/events/src/types.ts (5)
packages/db/src/schema/resource.ts (2)
  • Resource (105-105)
  • ResourceVariable (417-417)
packages/db/src/schema/deployment-variables.ts (1)
  • DeploymentVariable (48-48)
packages/db/src/schema/environment.ts (1)
  • Environment (86-86)
packages/validators/src/resources/conditions/resource-condition.ts (1)
  • ResourceCondition (29-39)
packages/db/src/schema/deployment.ts (1)
  • Deployment (105-105)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (17)
packages/events/src/types.ts (2)

42-44: Type updates look good

The type definitions for the NewEnvironment, NewResource, and NewPolicy channels have been appropriately updated with standard type imports.


54-56: Channel additions for resource lifecycle events

Good addition of the UpdatedResource and DeleteResource channel types, which aligns with the event-driven approach for resource management. These new channel types enable asynchronous processing of resource updates and deletions.

apps/event-worker/src/workers/index.ts (2)

6-6: Worker import added correctly

The import for the new deleteResourceWorker has been properly added.


38-38: Delete resource worker registration

The deleteResourceWorker has been correctly registered for the Channel.DeleteResource channel, completing the event-driven architecture for resource deletion.

apps/webservice/src/app/api/v1/resources/[resourceId]/route.ts (1)

141-141: Successful implementation of asynchronous resource deletion

The code has been updated to use the event-driven deletion approach via the DeleteResource channel instead of direct synchronous deletion. This aligns with the broader architectural shift in the system.

packages/db/src/selectors/compute/resource-builder.ts (1)

5-5: Import modification looks good

The addition of isNotNull to the imports is appropriate for the new filter condition being added.

apps/webservice/src/app/api/v1/workspaces/[workspaceId]/resources/identifier/[identifier]/route.ts (2)

6-6: Import changes correctly reflect new approach

The imports have been updated to support the asynchronous deletion pattern, removing the direct deleteResources import and adding the event queue functionality.


99-99: Successful implementation of asynchronous resource deletion

The code has been updated to use the event-driven deletion approach via the DeleteResource channel instead of direct synchronous deletion. This change is consistent with the modifications in other API routes.

packages/job-dispatch/src/resource/handle-provider-scan.ts (2)

45-47: Effective implementation of batch deletion via event queue

The code has been updated to queue deletions in bulk through the DeleteResource channel, which aligns with the new asynchronous deletion pattern. Good use of addBulk for efficient batch processing.


54-57: Return value properly includes deleted resources

The updated return structure preserves the information about which resources were deleted, ensuring downstream operations have access to this data even though the actual deletion now happens asynchronously.

apps/event-worker/src/workers/delete-resource.ts (6)

1-10: Well-organized imports.

The imports are appropriately grouped and organized, keeping related imports together.


11-15: Good implementation of soft deletion.

Using a transaction to set the deletedAt timestamp is the correct approach for implementing soft deletion.


17-22: Appropriate returning of deleted entities.

Good practice to return the deleted release targets, as they're needed for subsequent operations in the deletion flow.


23-32: Efficient parallel deletion of computed resources.

Using Promise.all to handle multiple deletions in parallel is an efficient approach.


33-43: Effective batch deletion strategy.

Using inArray for batch deletion of computed release targets is an efficient approach.


63-74: Well-structured transactional approach to resource deletion.

The worker implementation uses a transaction to ensure all deletion operations are atomic, which is crucial for maintaining data consistency. The sequence of operations is logical and ensures all related entities are properly cleaned up.

packages/api/src/router/resources.ts (1)

698-706: Good shift to asynchronous deletion pattern.

Changing from synchronous deletion to an asynchronous job-based approach is a good architectural decision. This improves API responsiveness and allows for better error handling and retry mechanisms.

isResourceMatchingDeployment,
inArray(SCHEMA.resource.id, this.resourceIds),
isNotNull(SCHEMA.resource.deletedAt),
),
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify the query filter logic for deleted resources

The added condition isNotNull(SCHEMA.resource.deletedAt) would only match resources that have been deleted (where deletedAt is not null). This seems counterintuitive for a method that finds matching environment-deployment pairs, as typically you'd want to exclude deleted resources, not include only deleted ones.


🏁 Script executed:

#!/bin/bash
# Check if this filtering approach is consistent with other similar queries in the codebase

# Look for similar resource filtering patterns in the codebase
rg -A 3 "isNotNull\(.*\.deletedAt\)" --type ts

Length of output: 1896


#!/bin/bash
# Display relevant context around deletedAt filter in resource-builder.ts
sed -n '1,200p' packages/db/src/selectors/compute/resource-builder.ts

#!/bin/bash
# Display lines around the deletedAt filter in resource-builder.ts for context
sed -n '80,160p' packages/db/src/selectors/compute/resource-builder.ts

Replace isNotNull with isNull to exclude deleted resources

The current filter

  isNotNull(SCHEMA.resource.deletedAt),

matches only deleted resources. For methods that compute active environment–deployment pairs, you should use isNull to exclude those with a non‑null deletedAt.

Please update in all selector builders:

• packages/db/src/selectors/compute/resource‑builder.ts (around line 112)
• packages/db/src/selectors/compute/deployment‑builder.ts
• packages/db/src/selectors/compute/environment‑builder.ts

Suggested diff:

-          isNotNull(SCHEMA.resource.deletedAt),
+          isNull(SCHEMA.resource.deletedAt),

@adityachoudhari26 adityachoudhari26 merged commit fe3b733 into main Apr 20, 2025
9 of 10 checks passed
@adityachoudhari26 adityachoudhari26 deleted the delete-resource-worker branch April 20, 2025 02:10
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