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

fix: Always dispatch resources with changed vars #227

Merged
merged 4 commits into from
Nov 23, 2024

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Nov 23, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced resource management with improved handling of resource IDs during insert operations.
    • Added logic for dispatching jobs related to newly added resources.
  • Bug Fixes

    • Corrected filtering logic to ensure updated resources are not misclassified as removed.
  • Refactor

    • Updated function return types to explicitly return a set of resource IDs, streamlining output.
    • Introduced early return condition in job dispatching to improve efficiency.
    • Modified PATCH method response structure for better resource update handling.
    • Streamlined schema definition by removing redundant optional calls.

Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

Walkthrough

This pull request introduces updates to the insertResourceVariables, upsertResources, and dispatchJobsForAddedResources functions within the job-dispatch package. The insertResourceVariables function now explicitly returns a Promise<Set<string>> containing resource IDs, enhancing its output clarity. The upsertResources function has been modified to improve the handling of resource variables and the dispatching of jobs for newly added resources, ensuring that updated variables are tracked correctly and that job dispatching occurs in parallel. Additionally, an early return condition has been added to dispatchJobsForAddedResources to improve efficiency when no resources are available for dispatch.

Changes

File Path Change Summary
packages/job-dispatch/src/resource/insert-resource-variables.ts - Updated return type of insertResourceVariables to Promise<Set<string>>.
- Modified internal logic to return a Set of resource IDs instead of an object.
packages/job-dispatch/src/resource/upsert.ts - Restructured handling of resource variables in upsertResources.
- Added logic for dispatching jobs for added resources based on updated variable IDs.
- Adjusted filtering logic for removed resource IDs.
packages/job-dispatch/src/resource/dispatch-resource.ts - Added early return condition in dispatchJobsForAddedResources to return immediately if resourceIds is empty.
apps/webservice/src/app/api/v1/resources/[resourceId]/route.ts - Updated PATCH method to return an object with an all property instead of updated for resource processing.
- Streamlined patchSchema by removing redundant .optional() calls.

Possibly related PRs

Suggested reviewers

  • jsbroks

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.

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

🧹 Outside diff range and nitpick comments (3)
packages/job-dispatch/src/resource/insert-resource-variables.ts (1)

69-75: Consider optimizing Set creation.

While the current implementation is correct, we can optimize it by avoiding the intermediate array creation.

Here's a more efficient approach:

-  const updatedResourceIds = [
-    ...created.map((r) => r.resourceId),
-    ...deleted.map((r) => r.resourceId),
-    ...updated.map((r) => r.resourceId),
-  ];
-
-  return new Set(updatedResourceIds);
+  return new Set([
+    ...created,
+    ...deleted,
+    ...updated
+  ].map(r => r.resourceId));

Or even better, to avoid spreading arrays altogether:

-  const updatedResourceIds = [
-    ...created.map((r) => r.resourceId),
-    ...deleted.map((r) => r.resourceId),
-    ...updated.map((r) => r.resourceId),
-  ];
-
-  return new Set(updatedResourceIds);
+  const resourceIds = new Set<string>();
+  for (const r of created) resourceIds.add(r.resourceId);
+  for (const r of deleted) resourceIds.add(r.resourceId);
+  for (const r of updated) resourceIds.add(r.resourceId);
+  return resourceIds;
packages/job-dispatch/src/resource/upsert.ts (2)

65-65: Clarify the ignored result from insertResourceMetadata

In the destructuring of the results from Promise.all, the result of insertResourceMetadata is being ignored:

const [, updatedVariableResourceIds] = await Promise.all([
  insertResourceMetadata(tx, resourcesWithId),
  insertResourceVariables(tx, resourcesWithId),
]);

If insertResourceMetadata does not return a value or its result is not needed, consider the following:

  • Remove it from the Promise.all and await it separately to make it clear that its result is intentionally ignored.
  • Alternatively, if it returns a value that should be handled, ensure that it is appropriately captured and used.

This will improve code clarity and maintainability.


131-135: Review the filtering logic for removed resources

In the filtering of removedIds:

.filter(
  (id) =>
    !deletedResourceIds.has(id) &&
    !updatedVariableResourceIds.has(id),
);

Verify that excluding resource IDs in updatedVariableResourceIds from removedIds is the intended behavior. Resources with updated variables might still need to have certain operations performed even if they are not deleted. If this logic is intentional, consider adding a comment to explain the reasoning for future maintainability.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a3cc0c4 and 9834222.

📒 Files selected for processing (2)
  • packages/job-dispatch/src/resource/insert-resource-variables.ts (3 hunks)
  • packages/job-dispatch/src/resource/upsert.ts (3 hunks)
🔇 Additional comments (2)
packages/job-dispatch/src/resource/insert-resource-variables.ts (2)

34-34: LGTM! Consistent return type handling.

The early return of an empty Set maintains consistency with the function's contract.


16-16: LGTM! Verify consumers of this function.

The explicit return type improves type safety and makes the contract clearer.

Let's verify the impact on existing consumers:

✅ Verification successful

Return type change is safe to proceed

The new Promise<Set<string>> return type is correctly handled in the only consumer (upsert.ts). The result is stored in updatedVariableResourceIds and used appropriately with the Set's has() method in two places:

  • Line 89: Filtering resources for variable changes
  • Line 134: Filtering removed resource IDs
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all usages of insertResourceVariables to ensure they handle the new return type
ast-grep --pattern 'insertResourceVariables($$$)' 

Length of output: 151


Script:

#!/bin/bash
# Let's check how the result is used in upsert.ts
cat packages/job-dispatch/src/resource/upsert.ts

Length of output: 5185

Comment on lines +83 to +92
const envVariableChangePromises = envsAfterInsert.map((env) =>
dispatchJobsForAddedResources(
tx,
env.resources
.filter((r) => updatedVariableResourceIds.has(r.id))
.map((r) => r.id),
env.id,
),
);
await Promise.all(envVariableChangePromises);
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

Ensure proper handling when no resources have updated variables

The code dispatches jobs for resources with updated variables:

const envVariableChangePromises = envsAfterInsert.map((env) =>
  dispatchJobsForAddedResources(
    tx,
    env.resources
      .filter((r) => updatedVariableResourceIds.has(r.id))
      .map((r) => r.id),
    env.id,
  ),
);
await Promise.all(envVariableChangePromises);

If updatedVariableResourceIds is empty, dispatchJobsForAddedResources may be called with an empty array of resource IDs. Confirm that dispatchJobsForAddedResources correctly handles an empty array to avoid unnecessary processing or potential errors.

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

🧹 Outside diff range and nitpick comments (1)
packages/job-dispatch/src/resource/dispatch-resource.ts (1)

58-58: LGTM! Consider adding debug logging for early return.

The early return optimization is a good addition that prevents unnecessary processing when no resources are provided.

Consider adding a debug log before the early return to maintain consistent logging throughout the function:

+  log.debug("No resources to dispatch, returning early");
   if (resourceIds.length === 0) return;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9834222 and 1915c67.

📒 Files selected for processing (1)
  • packages/job-dispatch/src/resource/dispatch-resource.ts (1 hunks)

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

🧹 Outside diff range and nitpick comments (2)
apps/webservice/src/app/api/v1/resources/[resourceId]/route.ts (2)

Line range hint 44-47: Remove redundant .optional() calls in schema definition

The schema fields have unnecessary double .optional() calls which should be simplified.

-  name: z.string().optional().optional(),
-  version: z.string().optional().optional(),
-  kind: z.string().optional().optional(),
-  identifier: z.string().optional().optional(),
+  name: z.string().optional(),
+  version: z.string().optional(),
+  kind: z.string().optional(),
+  identifier: z.string().optional(),

96-97: Consider adding error handling for variable updates

Given that upsertResources now handles variable changes and job dispatching differently, consider adding specific error handling for these scenarios.

-    const { all } = await upsertResources(db, [_.merge(resource, body)]);
+    try {
+      const { all } = await upsertResources(db, [_.merge(resource, body)]);
+    } catch (error) {
+      console.error('Failed to update resource:', error);
+      return NextResponse.json(
+        { error: 'Failed to update resource variables' },
+        { status: 500 }
+      );
+    }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1915c67 and b23a8a3.

📒 Files selected for processing (1)
  • apps/webservice/src/app/api/v1/resources/[resourceId]/route.ts (1 hunks)
🔇 Additional comments (1)
apps/webservice/src/app/api/v1/resources/[resourceId]/route.ts (1)

96-99: Verify upsertResources response structure change

The change from updated to all property reflects an API change in the upsertResources function. The null check is a good addition for type safety.

Let's verify this change is consistent across the codebase:

Consider adding a more descriptive error message:

-    if (res == null) throw new Error("Failed to update resource");
+    if (res == null) throw new Error(`Failed to update resource ${params.resourceId}`);
✅ Verification successful

Let me verify the usage of upsertResources response handling across the codebase.


Let me check how the other files handle the response when not destructuring.


Change from updated to all property is consistently implemented

The codebase shows consistent usage of the all property from upsertResources response in files that need the result data. Two files explicitly destructure { all } while others either don't use the return value or store it directly. The null check is appropriately added where single resource access is needed.

  • apps/webservice/src/app/api/v1/resources/[resourceId]/route.ts: Uses { all } with null check
  • apps/pty-proxy/src/controller/agent-socket.ts: Uses { all } consistently
  • Other files either don't use the return value or store it directly
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of upsertResources to ensure consistent handling
rg -A 3 "upsertResources\(" --type ts

Length of output: 1867


Script:

#!/bin/bash
# Let's check the implementation of these files to see how they handle the response
ast-grep --pattern 'const { $_ } = await upsertResources($$$)'

Length of output: 1076


Script:

#!/bin/bash
# Get more context around the other upsertResources calls
rg -B 2 -A 5 "await upsertResources\(" --type ts

Length of output: 3300

Comment on lines 131 to 135
.filter(
(id) =>
!deletedResourceIds.has(id) &&
!updatedVariableResourceIds.has(id),
);
Copy link
Member

Choose a reason for hiding this comment

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

shouldn't we be doing this in the addedResources section?

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

🧹 Outside diff range and nitpick comments (2)
packages/job-dispatch/src/resource/upsert.ts (2)

83-92: Add an early return optimization for empty variable updates

While the parallel dispatch logic is good, we should add an early return to avoid unnecessary processing when there are no updated variables.

Consider adding this optimization:

+   if (updatedVariableResourceIds.size === 0) {
+     log.debug("No resources with updated variables, skipping dispatch");
+     return;
+   }
    const envVariableChangePromises = envsAfterInsert.map((env) =>
      dispatchJobsForAddedResources(
        tx,
        env.resources
          .filter((r) => updatedVariableResourceIds.has(r.id))
          .map((r) => r.id),
        env.id,
      ),
    );
    await Promise.all(envVariableChangePromises);

Line range hint 26-155: Consider implementing a state machine for resource lifecycle management

The current implementation handles multiple state transitions (variable updates, additions, removals) with implicit sequencing. Consider implementing a state machine pattern to:

  • Make the resource lifecycle states explicit
  • Ensure transitions are handled consistently
  • Improve debugging and monitoring
  • Make the code more maintainable

This would help in tracking which resources are in which state and why certain jobs are being dispatched.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b23a8a3 and b7f52dc.

📒 Files selected for processing (1)
  • packages/job-dispatch/src/resource/upsert.ts (3 hunks)
🔇 Additional comments (2)
packages/job-dispatch/src/resource/upsert.ts (2)

65-68: LGTM: Clean destructuring of Promise results

The destructuring correctly captures the metadata insertion result and the set of updated variable resource IDs, which is used effectively in the subsequent operations.


123-125: LGTM: Prevents duplicate job dispatches

The filter correctly excludes resources that already had jobs dispatched due to variable updates, preventing duplicate processing. This answers @jsbroks's question - we handle variable updates separately to ensure proper sequencing and avoid double-dispatching jobs.

@adityachoudhari26 adityachoudhari26 merged commit c1535f0 into main Nov 23, 2024
8 of 9 checks passed
@adityachoudhari26 adityachoudhari26 deleted the always-dispatch-var-change branch November 23, 2024 20:39
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