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

feat: bulk checker goroutine cancellation #1694

Merged
merged 2 commits into from
Oct 16, 2024

Conversation

tolgaOzen
Copy link
Member

@tolgaOzen tolgaOzen commented Oct 16, 2024

Summary by CodeRabbit

  • New Features

    • Updated API documentation to version 1.1.4, reflecting the latest changes.
    • Enhanced error handling for bulk requests and entity filtering processes.
  • Bug Fixes

    • Improved pagination handling for reading relationships and attributes.
  • Documentation

    • Updated versioning in API reference files and OpenAPI specifications to 1.1.4.
  • Chores

    • Enhanced configuration file structure for better readability and maintainability.

Copy link

coderabbitai bot commented Oct 16, 2024

Walkthrough

The pull request includes multiple updates primarily focused on enhancing the structure and readability of configuration files and code within the Permify project. Key modifications involve changing the name_template to version_template in the .goreleaser.yml file, incrementing the API version in several JSON and proto files, and improving the functionality of the BulkChecker and EntityFilter components. Additionally, new fields and methods were introduced in the VisitsMap struct, and pagination handling was refined in the dataServer.

Changes

File Path Change Summary
.goreleaser.yml Updated snapshot section to use version_template, corrected indentation in nfpms, standardized formatting in docker_manifests and dockers, adjusted release and changelog sections.
docs/api-reference/apidocs.swagger.json Version updated from "v1.1.3" to "v1.1.4".
docs/api-reference/openapiv2/apidocs.swagger.json Version updated from "v1.1.3" to "v1.1.4".
internal/engines/bulk.go Added prepareRequestList method, improved context handling in ExecuteRequests, and enhanced error handling with IsContextRelatedError.
internal/engines/entityFilter.go Removed la method, integrated its functionality into attributeEntrance, updated related methods for duplicate checks.
internal/engines/utils.go Added ea field and AddEA method to VisitsMap struct.
internal/info.go Updated Version constant from "v1.1.3" to "v1.1.4".
internal/servers/dataServer.go Improved handling of pageSize parameter in ReadRelationships and ReadAttributes methods.
proto/base/v1/openapi.proto Version updated from "v1.1.3" to "v1.1.4".

Possibly related PRs

🐰 In the meadow where bunnies play,
Changes hop in, brightening the day.
With templates and versions, all in line,
Our code now dances, oh so fine!
Readability blooms, like flowers in spring,
Hooray for the updates, let the rabbits sing! 🎶


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.

@tolgaOzen tolgaOzen merged commit eaef635 into master Oct 16, 2024
10 of 12 checks passed
@tolgaOzen tolgaOzen deleted the feat/bulk-checker-goroutine-cancellation branch October 16, 2024 08:40
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: 5

🧹 Outside diff range and nitpick comments (4)
internal/servers/dataServer.go (2)

66-70: LGTM! Consider extracting the default page size as a constant.

The changes improve the robustness of the pagination logic by ensuring a default page size when not specified by the client. This is a good practice for maintaining consistent behavior.

For better code maintainability and consistency, consider extracting the default page size (50) as a package-level constant. This would allow easy modification of the default value across all methods if needed in the future. For example:

const defaultPageSize = 50

// In the method
size := request.GetPageSize()
if size == 0 {
    size = defaultPageSize
}

Also applies to: 91-91


Line range hint 1-442: Overall, the changes improve pagination handling.

The modifications to ReadRelationships and ReadAttributes methods enhance the robustness of pagination logic by ensuring a default page size when not specified by the client. These changes are consistent across both methods and do not introduce any new issues.

To further improve the code:

  1. Extract the default page size as a package-level constant for better maintainability.
  2. Consider adding a unit test to verify the behavior when the client doesn't specify a page size, ensuring the default is correctly applied.
internal/engines/utils.go (1)

85-85: LGTM. Consider adding documentation for the new field.

The addition of ea sync.Map is consistent with the existing structure and extends the functionality of VisitsMap. To improve clarity, consider adding a comment explaining the purpose of this new field.

 type VisitsMap struct {
 	er        sync.Map
-	ea        sync.Map
+	ea        sync.Map // Stores entity-attribute pairs
 	published sync.Map
 }
internal/engines/bulk.go (1)

134-134: Use copy instead of append to duplicate the request list

Using copy can be more efficient and idiomatic when duplicating slices.

Apply this diff:

-	return append([]BulkCheckerRequest{}, bc.list...) // Return a copy of the list to avoid modifying the original
+	listCopy := make([]BulkCheckerRequest, len(bc.list))
+	copy(listCopy, bc.list)
+	return listCopy // Return a copy of the list to avoid modifying the original
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f8a8d42 and 6f57b22.

⛔ Files ignored due to path filters (1)
  • pkg/pb/base/v1/openapi.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (9)
  • .goreleaser.yml (1 hunks)
  • docs/api-reference/apidocs.swagger.json (1 hunks)
  • docs/api-reference/openapiv2/apidocs.swagger.json (1 hunks)
  • internal/engines/bulk.go (7 hunks)
  • internal/engines/entityFilter.go (2 hunks)
  • internal/engines/utils.go (2 hunks)
  • internal/info.go (1 hunks)
  • internal/servers/dataServer.go (4 hunks)
  • proto/base/v1/openapi.proto (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • docs/api-reference/apidocs.swagger.json
  • docs/api-reference/openapiv2/apidocs.swagger.json
  • proto/base/v1/openapi.proto
🧰 Additional context used
🔇 Additional comments (7)
internal/info.go (1)

26-26: LGTM: Version increment looks good.

The version has been correctly updated from "v1.1.3" to "v1.1.4", which is consistent with semantic versioning for a patch release.

To ensure consistency across the project, let's verify if this version update is reflected in other relevant files:

Please review the output of this script and update any necessary files to reflect the new version.

.goreleaser.yml (1)

Line range hint 1-96: Overall assessment of .goreleaser.yml changes

The change in this file is minimal but potentially significant. The modification from name_template to version_template in the snapshot section may reflect an update in GoReleaser's configuration schema.

While this change appears intentional and isolated, it's crucial to verify its correctness against the latest GoReleaser documentation. The verification script provided in the previous comment will help ensure this change aligns with current best practices.

Additionally, it's worth noting that no other parts of the file were modified. The overall structure and other configurations remain unchanged, which suggests this update was targeted specifically at the snapshot versioning mechanism.

internal/servers/dataServer.go (1)

117-121: LGTM! Consider the same improvement as in ReadRelationships.

The changes in this method mirror those in ReadRelationships, which is good for consistency across the codebase. They improve the robustness of the pagination logic in the same manner.

As suggested for ReadRelationships, consider extracting the default page size (50) as a package-level constant for better maintainability and consistency across both methods.

Also applies to: 142-142

internal/engines/utils.go (1)

Line range hint 1-100: Summary of changes and recommendations

  1. The addition of the ea sync.Map field to the VisitsMap struct enhances its functionality to track entity-attribute pairs.
  2. The new AddEA method provides a way to add entity-attribute pairs to the VisitsMap.
  3. A minor issue was found in the AddEA method where it uses the wrong map (er instead of ea).

Please address the issue in the AddEA method and consider adding documentation for the new ea field. Once these changes are made, the modifications will improve the VisitsMap functionality without introducing any breaking changes to the existing codebase.

internal/engines/bulk.go (1)

215-221: Ensure IsContextRelatedError function is used correctly

After fixing IsContextRelatedError, it will correctly identify context-related errors. Ensure that all places where it's called pass the appropriate error.

Run the following script to check for all usages of IsContextRelatedError and verify that the correct error variable is passed:

✅ Verification successful

Usage of IsContextRelatedError is correct across all instances.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct usage of IsContextRelatedError

# Search for all calls to IsContextRelatedError in Go files
rg --type go 'IsContextRelatedError\([^)]+\)' -A 1

Length of output: 1060

internal/engines/entityFilter.go (2)

127-129: Prevent redundant processing with visits.AddEA

Good job adding the check to prevent processing entities that have already been visited. This enhances efficiency and avoids infinite loops.


186-210: Efficiently publish unique entities

The added logic correctly checks for previously visited entities using visits.AddPublished(entity), ensuring that duplicates are not processed. This maintains the integrity of the published results.

@@ -93,7 +93,7 @@ nfpms:
maintainer: "permify <help@permify.co>"
vendor: "permify inc."
snapshot:
name_template: "{{ incpatch .Version }}-next"
version_template: "{{ incpatch .Version }}-next"
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Issues with the change from name_template to version_template

The version_template key was not found in GoReleaser's documentation for snapshot configuration. Additionally, name_template is still present in .goreleaser.yml. Please verify and correct the configuration to ensure it aligns with GoReleaser's requirements.

🔗 Analysis chain

Confirm the change from name_template to version_template

The change from name_template to version_template in the snapshot section appears to be intentional. This modification alters how versioning for snapshots is defined.

To ensure this change aligns with GoReleaser's current best practices, please run the following verification script:

This script will help verify if the change is consistent with GoReleaser's current documentation and if all relevant occurrences have been updated.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if 'version_template' is the correct key for snapshot configuration in GoReleaser

# Test: Check GoReleaser's documentation for the correct key in snapshot configuration
curl -s https://goreleaser.com/customization/snapshot/ | grep -q 'version_template:'
if [ $? -eq 0 ]; then
    echo "The change to 'version_template' is correct according to GoReleaser's documentation."
else
    echo "Warning: 'version_template' was not found in GoReleaser's documentation for snapshot configuration. Please double-check this change."
fi

# Test: Check for any remaining occurrences of 'name_template' in the snapshot section
if grep -q 'name_template' .goreleaser.yml; then
    echo "Warning: 'name_template' is still present in .goreleaser.yml. Ensure all occurrences have been updated if intended."
else
    echo "All occurrences of 'name_template' have been updated in .goreleaser.yml."
fi

Length of output: 673

Comment on lines +95 to +99
func (s *VisitsMap) AddEA(entityType, attribute string) bool {
key := fmt.Sprintf("%s$%s", entityType, attribute)
_, existed := s.er.LoadOrStore(key, struct{}{})
return !existed
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the map used in AddEA method.

The AddEA method is using the er map instead of the newly added ea map. This appears to be an error and should be corrected to ensure proper functionality.

Please apply the following fix:

 func (s *VisitsMap) AddEA(entityType, attribute string) bool {
 	key := fmt.Sprintf("%s$%s", entityType, attribute)
-	_, existed := s.er.LoadOrStore(key, struct{}{})
+	_, existed := s.ea.LoadOrStore(key, struct{}{})
 	return !existed
 }
📝 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
func (s *VisitsMap) AddEA(entityType, attribute string) bool {
key := fmt.Sprintf("%s$%s", entityType, attribute)
_, existed := s.er.LoadOrStore(key, struct{}{})
return !existed
}
func (s *VisitsMap) AddEA(entityType, attribute string) bool {
key := fmt.Sprintf("%s$%s", entityType, attribute)
_, existed := s.ea.LoadOrStore(key, struct{}{})
return !existed
}

Comment on lines +9 to +10
"github.com/pkg/errors"

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 using the standard errors package

Since Go 1.13, the standard library's errors package provides errors.Is and errors.As functions. You may not need to import "github.com/pkg/errors".

Apply this diff to switch to the standard library:

-	"github.com/pkg/errors"
+	"errors"
📝 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
"github.com/pkg/errors"
"errors"

Comment on lines +347 to +349
func IsContextRelatedError(ctx context.Context, err error) bool {
return errors.Is(ctx.Err(), context.Canceled) || errors.Is(ctx.Err(), context.DeadlineExceeded)
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix IsContextRelatedError to check the passed error

The function currently checks ctx.Err() instead of the provided err. It should check err to accurately determine if the error is context-related.

Apply this diff:

func IsContextRelatedError(ctx context.Context, err error) bool {
-	return errors.Is(ctx.Err(), context.Canceled) || errors.Is(ctx.Err(), context.DeadlineExceeded)
+	return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}
📝 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
func IsContextRelatedError(ctx context.Context, err error) bool {
return errors.Is(ctx.Err(), context.Canceled) || errors.Is(ctx.Err(), context.DeadlineExceeded)
}
func IsContextRelatedError(ctx context.Context, err error) bool {
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}

Comment on lines +198 to +201
if err := ctx.Err(); err == context.Canceled {
return nil // Gracefully exit the goroutine if context is canceled
}

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle all context-related errors when checking context

Currently, only context.Canceled is checked. Consider handling context.DeadlineExceeded as well to cover all context cancellation scenarios.

Apply this diff:

-	if err := ctx.Err(); err == context.Canceled {
+	if err := ctx.Err(); err != nil {
		return nil // Gracefully exit the goroutine if context is canceled or deadline exceeded
	}

Alternatively, use the IsContextRelatedError function:

-	if err := ctx.Err(); err == context.Canceled {
+	if IsContextRelatedError(ctx, ctx.Err()) {
		return nil // Gracefully exit the goroutine if context is canceled or deadline exceeded
	}
📝 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 err := ctx.Err(); err == context.Canceled {
return nil // Gracefully exit the goroutine if context is canceled
}
if err := ctx.Err(); err != nil {
return nil // Gracefully exit the goroutine if context is canceled or deadline exceeded
}

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