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

General: Fix an issue when trying to delete too many users at once #9430

Merged
merged 6 commits into from
Oct 12, 2024

Conversation

chrisknedl
Copy link
Contributor

@chrisknedl chrisknedl commented Oct 6, 2024

Checklist

General

Server

Client

  • Important: I implemented the changes with a very good performance, prevented too many (unnecessary) REST calls and made sure the UI is responsive, even with large data (e.g. using paging).
  • I strictly followed the principle of data economy for all client-server REST calls.
  • I strictly followed the client coding and design guidelines.

Motivation and Context

Closes #9364

Description

Instead of sending the logins of the users in the URL, we put them in the request body.

Steps for Testing

Can't be tested. The related server and client tests still work.

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Performance Review

  • I (as a reviewer) confirm that the client changes (in particular related to REST calls and UI responsiveness) are implemented with a very good performance even for very large courses with more than 2000 students.
  • I (as a reviewer) confirm that the server changes (in particular related to database calls) are implemented with a very good performance even for very large courses with more than 2000 students.

Code Review

  • Code Review 1
  • Code Review 2
  • Code Review 3
  • Code Review 4

Summary by CodeRabbit

  • New Features

    • Enhanced user deletion process by allowing user logins to be sent in the request body instead of as query parameters.
  • Bug Fixes

    • Improved error handling and logging during user deletion.
  • Documentation

    • Updated method signatures and descriptions to reflect changes in the user deletion process.

@chrisknedl chrisknedl self-assigned this Oct 6, 2024
@github-actions github-actions bot added tests server Pull requests that update Java code. (Added Automatically!) client Pull requests that update TypeScript code. (Added Automatically!) core Pull requests that affect the corresponding module labels Oct 6, 2024
@chrisknedl chrisknedl added bugfix small server-api Improves the server API labels Oct 6, 2024
@chrisknedl chrisknedl marked this pull request as ready for review October 9, 2024 12:07
@chrisknedl chrisknedl requested a review from a team as a code owner October 9, 2024 12:07
Copy link

coderabbitai bot commented Oct 9, 2024

Walkthrough

The pull request modifies the user deletion functionality in the application. Specifically, it changes the deleteUsers method in the AdminUserResource class to accept a list of user logins via the request body instead of as query parameters. Corresponding changes are made in the AdminUserService to accommodate this new method signature, simplifying the request handling. Additionally, the UserTestService class has been updated to streamline the collection of logins for testing purposes. The overall functionality remains focused on soft-deleting users while preserving logging and error handling.

Changes

File Path Change Summary
src/main/java/de/tum/cit/aet/artemis/core/web/admin/AdminUserResource.java Changed deleteUsers method parameter from @RequestParam to @RequestBody.
src/main/webapp/app/core/user/admin-user.service.ts Updated deleteUsers method to send logins as a request body instead of query parameters; removed HttpParams.
src/test/java/de/tum/cit/aet/artemis/core/user/util/UserTestService.java Simplified collection of logins in the deleteUsers method using toList().

Assessment against linked issues

Objective Addressed Explanation
Inactive users shall be deleted (9364)

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 or @coderabbitai title 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

@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

🧹 Outside diff range comments (2)
src/main/java/de/tum/cit/aet/artemis/core/web/admin/AdminUserResource.java (2)

Line range hint 292-318: Consider refactoring for improved readability and maintainability.

While the method's logic is sound, its structure could be improved for better readability and maintainability. Consider extracting the user deletion logic into a separate private method. This would make the main method more concise and easier to understand at a glance.

Here's a suggested refactoring:

@DeleteMapping("users")
@EnforceAdmin
public ResponseEntity<List<String>> deleteUsers(@RequestBody List<String> logins) {
    log.debug("REST request to delete {} users", logins.size());
    List<String> deletedUsers = Collections.synchronizedList(new ArrayList<>());

    var currentUser = userRepository.getUser();
    logins.remove(currentUser.getLogin());

    logins.parallelStream().forEach(login -> deleteUserIfNotCurrent(login, deletedUsers));

    return ResponseEntity.ok()
            .headers(HeaderUtil.createAlert(applicationName, "artemisApp.userManagement.batch.deleted", String.valueOf(deletedUsers.size())))
            .body(deletedUsers);
}

private void deleteUserIfNotCurrent(String login, List<String> deletedUsers) {
    try {
        if (!userRepository.isCurrentUser(login)) {
            userService.softDeleteUser(login);
            deletedUsers.add(login);
        }
    } catch (Exception exception) {
        log.error("REST request to delete user {} failed", login);
        log.error(exception.getMessage(), exception);
    }
}

This refactoring improves the method's structure by separating concerns and reducing the cognitive load when reading the main method.


Line range hint 292-318: Consider batch processing for very large lists of users.

While the current implementation using parallel streams is efficient for moderate-sized lists, it may not be optimal for extremely large lists of users. For scenarios involving thousands of users, consider implementing a batch processing approach. This could involve processing users in smaller chunks and potentially using database batch operations for better performance and resource management.

Would you like assistance in implementing a batch processing approach for this method?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between b6b47e7 and 5d39b92.

📒 Files selected for processing (3)
  • src/main/java/de/tum/cit/aet/artemis/core/web/admin/AdminUserResource.java (1 hunks)
  • src/main/webapp/app/core/user/admin-user.service.ts (2 hunks)
  • src/test/java/de/tum/cit/aet/artemis/core/user/util/UserTestService.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/main/java/de/tum/cit/aet/artemis/core/web/admin/AdminUserResource.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/webapp/app/core/user/admin-user.service.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

src/test/java/de/tum/cit/aet/artemis/core/user/util/UserTestService.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

🔇 Additional comments (2)
src/main/webapp/app/core/user/admin-user.service.ts (1)

Line range hint 1-106: Summary: Effective implementation of bulk user deletion.

The changes to the deleteUsers method in AdminUserService successfully address the issue of deleting multiple users simultaneously. By moving the user logins from query parameters to the request body, the implementation avoids URL length limitations and adheres to best practices for bulk operations in RESTful APIs.

The modification is localized and doesn't impact other methods in the service, maintaining the overall structure and functionality. This change aligns well with the PR objectives and coding guidelines.

To ensure that this change is properly integrated, please verify the corresponding server-side implementation:

This will help confirm that the server is prepared to handle the new request format with the user logins in the body.

src/main/java/de/tum/cit/aet/artemis/core/web/admin/AdminUserResource.java (1)

292-292: LGTM: Parameter change aligns with PR objective.

The change from @RequestParam to @RequestBody successfully addresses the issue of deleting a large number of users at once by moving the user logins from URL parameters to the request body. This modification aligns well with the PR objective and resolves the HTTP failure responses encountered when dealing with an extensive list of users.

coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 9, 2024
JohannesStoehr
JohannesStoehr previously approved these changes Oct 10, 2024
Copy link
Contributor

@JohannesStoehr JohannesStoehr left a comment

Choose a reason for hiding this comment

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

Code

ole-ve
ole-ve previously approved these changes Oct 11, 2024
Copy link
Contributor

@ole-ve ole-ve left a comment

Choose a reason for hiding this comment

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

code

dfuchss
dfuchss previously approved these changes Oct 11, 2024
Copy link
Contributor

@dfuchss dfuchss left a comment

Choose a reason for hiding this comment

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

Code

@chrisknedl chrisknedl requested a review from dfuchss October 12, 2024 12:23
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: 0

🧹 Outside diff range comments (2)
src/main/java/de/tum/cit/aet/artemis/core/web/admin/AdminUserResource.java (2)

Line range hint 296-301: Consider enhancing error logging for better traceability.

While the current error logging is functional, it could be improved to provide more context about the specific error that occurred during user deletion.

Consider modifying the error logging as follows:

- log.error("REST request to delete user {} failed", login);
- log.error(exception.getMessage(), exception);
+ log.error("Failed to delete user {}: {}", login, exception.getMessage());
+ log.debug("Detailed stack trace for user {} deletion failure:", login, exception);

This change provides a concise error message at the ERROR level while still allowing for detailed debugging when needed.


Line range hint 296-301: Consider using a more specific exception type for better error handling.

The current implementation catches all exceptions, which might mask specific issues. Using a more targeted exception type could improve error handling and debugging.

Consider creating a custom exception type for user deletion failures:

public class UserDeletionException extends RuntimeException {
    public UserDeletionException(String login, Throwable cause) {
        super("Failed to delete user: " + login, cause);
    }
}

Then, modify the exception handling in the deleteUsers method:

 try {
     if (!userRepository.isCurrentUser(login)) {
         userService.softDeleteUser(login);
         deletedUsers.add(login);
     }
 }
-catch (Exception exception) {
+catch (UserDeletionException exception) {
     // In order to handle all users even if some users produce exceptions, we catch them and ignore them and proceed with the remaining users
-    log.error("REST request to delete user {} failed", login);
-    log.error(exception.getMessage(), exception);
+    log.error("Failed to delete user {}: {}", login, exception.getMessage());
+    log.debug("Detailed stack trace for user {} deletion failure:", login, exception);
 }

This change would require updating the userService.softDeleteUser() method to throw UserDeletionException when appropriate. This approach provides more specific error handling while maintaining the current behavior of continuing with remaining users.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 5d39b92 and 7e1c19c.

📒 Files selected for processing (1)
  • src/main/java/de/tum/cit/aet/artemis/core/web/admin/AdminUserResource.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/main/java/de/tum/cit/aet/artemis/core/web/admin/AdminUserResource.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

🔇 Additional comments (1)
src/main/java/de/tum/cit/aet/artemis/core/web/admin/AdminUserResource.java (1)

283-283: LGTM: Successfully addressed the PR objective.

The change from @RequestParam to @RequestBody for the logins parameter effectively moves the user logins from URL parameters to the request body. This modification aligns with the PR objective and resolves the issue of HTTP failure responses when deleting a large number of users.

@krusche krusche changed the title Development: Fix issue when trying to delete too many users at once General: Fix an issue when trying to delete too many users at once Oct 12, 2024
@krusche krusche added this to the 7.6.0 milestone Oct 12, 2024
@krusche krusche merged commit db90e89 into develop Oct 12, 2024
24 of 31 checks passed
@krusche krusche deleted the bugfix/user-management/delete-inactive-users branch October 12, 2024 17:12
@coderabbitai coderabbitai bot mentioned this pull request Oct 20, 2024
14 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bugfix client Pull requests that update TypeScript code. (Added Automatically!) core Pull requests that affect the corresponding module ready for review server Pull requests that update Java code. (Added Automatically!) server-api Improves the server API small tests
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

Deletion of inactive users does not work if too many users are inactive
5 participants