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

Development: Migrate build agents components #9923

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

BBesrour
Copy link
Member

@BBesrour BBesrour commented Dec 1, 2024

Checklist

General

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.
  • Following the theming guidelines, I specified colors only in the theming variable files and checked that the changes look consistent in both the light and the dark theme.
  • I added multiple integration tests (Jest) related to the features (with a high test coverage), while following the test guidelines.
  • I added authorities to all new routes and checked the course groups for displaying navigation elements (links, buttons).
  • I documented the TypeScript code using JSDoc style.
  • I added multiple screenshots/screencasts of my UI changes.
  • I translated all newly inserted strings into English and German.

Changes affecting Programming Exercises

  • High priority: I tested all changes and their related features with all corresponding user types on a test server configured with the integrated lifecycle setup (LocalVC and LocalCI).

Motivation and Context

Migrate build agent components to new Angular standars

Steps for Testing

Prerequisites:

  • Deploy locally or on TS3
  • 1 Admin
  1. Submit to a programming exercise a few times
  2. Navigate to the Build Agents view (Click on Server administration > Build Agents)
  3. Make sure that the build agent is displayed and that the processing jobs are displayed correctly
  4. Click on build agent
  5. Make sure that the build agent details view works correctly

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

Manual Tests

  • Test 1
  • Test 2

Summary by CodeRabbit

Release Notes

  • New Features

    • BuildAgentSummaryComponent and BuildAgentDetailsComponent are now standalone components, enhancing modularity and reusability.
  • Improvements

    • Streamlined dependency injection for components and services, simplifying code structure.
    • Enhanced test setups by removing unnecessary imports and focusing on core functionality.
  • Bug Fixes

    • No specific bug fixes were noted, but overall stability and performance improvements are expected from the refactoring.

@BBesrour BBesrour self-assigned this Dec 1, 2024
@BBesrour BBesrour requested a review from a team as a code owner December 1, 2024 19:48
@github-actions github-actions bot added tests client Pull requests that update TypeScript code. (Added Automatically!) labels Dec 1, 2024
Copy link

coderabbitai bot commented Dec 1, 2024

Walkthrough

The changes in this pull request involve modifications to the ArtemisAdminModule and the components related to build agents. The BuildAgentSummaryComponent and BuildAgentDetailsComponent have been transitioned from declarations to imports within the admin.module.ts, indicating a refactor in their usage. Additionally, both components are now defined as standalone components, enhancing their modularity. The BuildAgentsService has also been updated to utilize Angular's inject function for dependency management, and the associated test files have been simplified to reflect these structural changes.

Changes

File Change Summary
src/main/webapp/app/admin/admin.module.ts Removed BuildAgentSummaryComponent and BuildAgentDetailsComponent from declarations; added to imports.
src/main/webapp/app/localci/build-agents/build-agent-details/build-agent-details.component.ts Updated to standalone component; added new imports; removed constructor, using inject for services.
src/main/webapp/app/localci/build-agents/build-agent-summary/build-agent-summary.component.ts Updated to standalone component; added new imports; removed constructor, using inject for services.
src/main/webapp/app/localci/build-agents/build-agents.service.ts Removed constructor; injected HttpClient using inject function.
src/test/javascript/spec/component/localci/build-agents/build-agent-details.component.spec.ts Removed unnecessary imports and declarations; updated test setup.
src/test/javascript/spec/component/localci/build-agents/build-agent-summary.component.spec.ts Removed unnecessary imports and declarations; updated test setup.

Possibly related PRs

Suggested labels

tests, client, ready to merge, refactoring, code quality, programming

Suggested reviewers

  • SimonEntholzer
  • magaupp
  • krusche

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

🧹 Outside diff range and nitpick comments (10)
src/main/webapp/app/localci/build-agents/build-agents.service.ts (2)

Line range hint 22-38: Inconsistent URL encoding across methods

While pauseBuildAgent and resumeBuildAgent properly encode agent names using encodeURIComponent, getBuildAgentDetails doesn't encode the agentName parameter, which could cause issues with special characters.

Apply this change:

    getBuildAgentDetails(agentName: string): Observable<BuildAgentInformation> {
-       return this.http.get<BuildAgentInformation>(`${this.adminResourceUrl}/build-agent`, { params: { agentName } }).pipe(
+       const encodedAgentName = encodeURIComponent(agentName);
+       return this.http.get<BuildAgentInformation>(`${this.adminResourceUrl}/build-agent`, { params: { agentName: encodedAgentName } }).pipe(
            catchError((err) => {
                return throwError(() => new Error(`Failed to fetch build agent details ${agentName}\n${err.message}`));
            }),
        );
    }

Line range hint 22-75: Consider extracting common error handling logic

Multiple methods share similar error handling patterns. Consider extracting this into a reusable operator.

Create a utility operator:

private handleBuildAgentError(operation: string, agentName?: string) {
    return catchError((err) => {
        const context = agentName ? ` ${agentName}` : 's';
        return throwError(() => new Error(`Failed to ${operation} build agent${context}\n${err.message}`));
    });
}

Then use it in methods:

    getBuildAgentDetails(agentName: string): Observable<BuildAgentInformation> {
        const encodedAgentName = encodeURIComponent(agentName);
        return this.http.get<BuildAgentInformation>(`${this.adminResourceUrl}/build-agent`, { params: { agentName: encodedAgentName } }).pipe(
-           catchError((err) => {
-               return throwError(() => new Error(`Failed to fetch build agent details ${agentName}\n${err.message}`));
-           }),
+           this.handleBuildAgentError('fetch', agentName)
        );
    }
src/test/javascript/spec/component/localci/build-agents/build-agent-summary.component.spec.ts (1)

Line range hint 146-151: Consider using MockProvider consistently

While MockProvider is used for AlertService, other services are using manual mock objects. Consider using MockProvider consistently for all services.

Replace manual mocks with MockProvider:

            providers: [
-               { provide: JhiWebsocketService, useValue: mockWebsocketService },
-               { provide: BuildAgentsService, useValue: mockBuildAgentsService },
-               { provide: DataTableComponent, useClass: DataTableComponent },
+               MockProvider(JhiWebsocketService, mockWebsocketService),
+               MockProvider(BuildAgentsService, mockBuildAgentsService),
+               MockProvider(DataTableComponent),
                MockProvider(AlertService),
            ],
src/test/javascript/spec/component/localci/build-agents/build-agent-details.component.spec.ts (1)

Line range hint 155-158: Use more specific assertion methods

According to the coding guidelines, we should use more specific assertion methods. For example:

  • Use toHaveBeenCalledOnce() instead of just toHaveBeenCalled()
  • Use toStrictEqual() instead of toEqual() for object comparisons
-        expect(mockBuildAgentsService.getBuildAgentDetails).toHaveBeenCalled();
-        expect(component.buildAgent).toEqual(mockBuildAgent);
+        expect(mockBuildAgentsService.getBuildAgentDetails).toHaveBeenCalledOnce();
+        expect(component.buildAgent).toStrictEqual(mockBuildAgent);

-        expect(component.buildAgent).toEqual(mockBuildAgent);
+        expect(component.buildAgent).toStrictEqual(mockBuildAgent);

Also applies to: 166-169

src/main/webapp/app/localci/build-agents/build-agent-details/build-agent-details/build-agent-details.component.ts (5)

Line range hint 1-15: Update import statements to use single quotes consistently

Per the coding guidelines, string literals should use single quotes consistently.

-import { BuildAgentInformation } from "app/entities/programming/build-agent-information.model";
+import { BuildAgentInformation } from 'app/entities/programming/build-agent-information.model';

18-22: Update component decorator to use styleUrls instead of styleUrl

The styleUrl property is newer but less flexible than the standard styleUrls array property. For consistency with Angular style guide, use styleUrls.

@Component({
    selector: 'jhi-build-agent-details',
    templateUrl: './build-agent-details.component.html',
-    styleUrl: './build-agent-details.component.scss',
+    styleUrls: ['./build-agent-details.component.scss'],
    standalone: true,
    imports: [ArtemisSharedModule, NgxDatatableModule, ArtemisDataTableModule, SubmissionResultStatusModule],
})

Line range hint 39-44: Improve comment formatting for better readability

The icons section comment could be formatted better.

-    //icons
+    // Font Awesome icons for UI elements

Line range hint 124-126: Consider moving URL construction to a service

The viewBuildLogs method directly constructs API URLs. Consider moving this to the BuildAgentsService for better maintainability and reusability.

+    // In BuildAgentsService
+    getBuildLogsUrl(resultId: number): string {
+        return `/api/build-log/${resultId}`;
+    }

+    // In component
     viewBuildLogs(resultId: number): void {
-        const url = `/api/build-log/${resultId}`;
+        const url = this.buildAgentsService.getBuildLogsUrl(resultId);
         window.open(url, '_blank');
     }

Line range hint 128-183: Refactor duplicate alert handling logic

The pauseBuildAgent and resumeBuildAgent methods contain similar error handling patterns. Consider extracting this to a reusable method.

+    private handleBuildAgentOperation(
+        operation: () => void,
+        successMessage: string,
+        failureMessage: string,
+    ): void {
+        if (!this.buildAgent.buildAgent?.name) {
+            this.alertService.addAlert({
+                type: AlertType.WARNING,
+                message: 'artemisApp.buildAgents.alerts.buildAgentWithoutName',
+            });
+            return;
+        }
+
+        operation();
+    }

     pauseBuildAgent(): void {
-        if (this.buildAgent.buildAgent?.name) {
-            this.buildAgentsService.pauseBuildAgent(this.buildAgent.buildAgent.name).subscribe({
+        this.handleBuildAgentOperation(
+            () => this.buildAgentsService.pauseBuildAgent(this.buildAgent.buildAgent!.name).subscribe({
                 next: () => {
                     this.alertService.addAlert({
                         type: AlertType.SUCCESS,
                         message: 'artemisApp.buildAgents.alerts.buildAgentPaused',
                     });
                 },
                 error: () => {
                     this.alertService.addAlert({
                         type: AlertType.DANGER,
                         message: 'artemisApp.buildAgents.alerts.buildAgentPauseFailed',
                     });
                 },
-            });
-        } else {
-            this.alertService.addAlert({
-                type: AlertType.WARNING,
-                message: 'artemisApp.buildAgents.alerts.buildAgentWithoutName',
-            });
-        }
+            }),
+            'artemisApp.buildAgents.alerts.buildAgentPaused',
+            'artemisApp.buildAgents.alerts.buildAgentPauseFailed'
+        );
     }
src/main/webapp/app/localci/build-agents/build-agent-summary/build-agent-summary.component.ts (1)

Line range hint 31-37: Consider implementing state management.

Given the component manages multiple build agents and their states, consider implementing a state management solution (e.g., NgRx, RxJS BehaviorSubject) to:

  • Centralize build agent state
  • Improve state predictability
  • Enable easier testing
  • Facilitate future scalability
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dece904 and bc92966.

📒 Files selected for processing (6)
  • src/main/webapp/app/admin/admin.module.ts (1 hunks)
  • src/main/webapp/app/localci/build-agents/build-agent-details/build-agent-details/build-agent-details.component.ts (2 hunks)
  • src/main/webapp/app/localci/build-agents/build-agent-summary/build-agent-summary.component.ts (2 hunks)
  • src/main/webapp/app/localci/build-agents/build-agents.service.ts (2 hunks)
  • src/test/javascript/spec/component/localci/build-agents/build-agent-details.component.spec.ts (2 hunks)
  • src/test/javascript/spec/component/localci/build-agents/build-agent-summary.component.spec.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
src/main/webapp/app/localci/build-agents/build-agents.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/main/webapp/app/admin/admin.module.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/javascript/spec/component/localci/build-agents/build-agent-details.component.spec.ts (1)

Pattern src/test/javascript/spec/**/*.ts: jest: true; mock: NgMocks; bad_practices: avoid_full_module_import; perf_improvements: mock_irrelevant_deps; service_testing: mock_http_for_logic; no_schema: avoid_NO_ERRORS_SCHEMA; expectation_specificity: true; solutions: {boolean: toBeTrue/False, reference: toBe, existence: toBeNull/NotNull, undefined: toBeUndefined, class_obj: toContainEntries/toEqual, spy_calls: {not_called: not.toHaveBeenCalled, once: toHaveBeenCalledOnce, with_value: toHaveBeenCalledWith|toHaveBeenCalledExactlyOnceWith}}

src/test/javascript/spec/component/localci/build-agents/build-agent-summary.component.spec.ts (1)

Pattern src/test/javascript/spec/**/*.ts: jest: true; mock: NgMocks; bad_practices: avoid_full_module_import; perf_improvements: mock_irrelevant_deps; service_testing: mock_http_for_logic; no_schema: avoid_NO_ERRORS_SCHEMA; expectation_specificity: true; solutions: {boolean: toBeTrue/False, reference: toBe, existence: toBeNull/NotNull, undefined: toBeUndefined, class_obj: toContainEntries/toEqual, spy_calls: {not_called: not.toHaveBeenCalled, once: toHaveBeenCalledOnce, with_value: toHaveBeenCalledWith|toHaveBeenCalledExactlyOnceWith}}

src/main/webapp/app/localci/build-agents/build-agent-summary/build-agent-summary.component.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/main/webapp/app/localci/build-agents/build-agent-details/build-agent-details/build-agent-details.component.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

🔇 Additional comments (7)
src/main/webapp/app/localci/build-agents/build-agents.service.ts (1)

1-1: LGTM: Successful migration to modern DI pattern

The migration from constructor-based dependency injection to the new inject() pattern aligns with modern Angular practices and reduces boilerplate code.

Also applies to: 11-11

src/main/webapp/app/admin/admin.module.ts (1)

78-79: LGTM: Proper migration to standalone components

Moving BuildAgentSummaryComponent and BuildAgentDetailsComponent to the imports array correctly reflects their new standalone nature. This change:

  • Improves tree-shaking capabilities
  • Reduces bundle size
  • Aligns with Angular's recommended architecture
src/test/javascript/spec/component/localci/build-agents/build-agent-summary.component.spec.ts (1)

144-145: LGTM: Improved test configuration

The simplified test configuration with ArtemisTestModule and empty declarations array aligns with best practices for testing standalone components.

src/main/webapp/app/localci/build-agents/build-agent-details/build-agent-details/build-agent-details.component.ts (1)

25-29: LGTM! Modern dependency injection pattern implemented correctly

The migration to using inject() function aligns well with modern Angular practices and improves code maintainability.

src/main/webapp/app/localci/build-agents/build-agent-summary/build-agent-summary.component.ts (3)

Line range hint 1-21: LGTM! Component migration to standalone looks good.

The migration to a standalone component follows Angular's best practices. The necessary modules are correctly imported and the component decorator is properly configured.


24-29: Verify memory management with inject pattern.

The migration to inject() function looks good, but let's ensure there are no memory leaks with the websocket subscriptions.

✅ Verification successful

Memory management is properly implemented

The component correctly handles websocket subscription cleanup in the ngOnDestroy lifecycle hook by:

  • Unsubscribing from the websocket channel
  • Cleaning up the websocket subscription
  • Cleaning up the REST subscription
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for proper cleanup of subscriptions in component
ast-grep --pattern 'ngOnDestroy() {
  $$$
  this.websocketSubscription?.unsubscribe();
  $$$
}'

Length of output: 97


Script:

#!/bin/bash
# Let's search for websocket subscription and cleanup patterns more broadly
rg -A 10 "websocketService" src/main/webapp/app/localci/build-agents/build-agent-summary/build-agent-summary.component.ts

# Also search for any subscription cleanup patterns
rg -A 5 "ngOnDestroy|unsubscribe" src/main/webapp/app/localci/build-agents/build-agent-summary/build-agent-summary.component.ts

Length of output: 2236


Line range hint 116-146: Verify translation keys for alert messages.

The alert messages use translation keys. Let's verify that these keys are properly defined in the translation files.

✅ Verification successful

Translation keys are properly defined and available

The translation keys used in the component are correctly defined in both English and German language files:

  • artemisApp.buildAgents.alerts.buildAgentPaused
  • artemisApp.buildAgents.alerts.buildAgentResumed
  • artemisApp.buildAgents.alerts.buildAgentPauseFailed
  • artemisApp.buildAgents.alerts.buildAgentResumeFailed
  • artemisApp.buildAgents.alerts.buildAgentWithoutName

All keys have corresponding translations in both src/main/webapp/i18n/en/buildAgents.json and src/main/webapp/i18n/de/buildAgents.json.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for translation keys in i18n files
rg "artemisApp.buildAgents.alerts" -g "*.json"

Length of output: 46


Script:

#!/bin/bash
# Let's try searching in all files, not just JSON, to understand the usage pattern
rg "artemisApp\.buildAgents\.alerts\." --type-add 'i18n:*.{json,ts,js}' -t i18n

# Also search for general i18n file patterns to ensure we're looking in the right places
fd -e json -e yml "i18n|translations|locale|messages"

Length of output: 3717


Script:

#!/bin/bash
# Let's check the src/main/webapp directory for i18n files specifically
fd -e json . src/main/webapp/i18n || fd -e json . src/main/webapp/app/i18n

# Also let's check the root directory for any translation files
fd -e json -e properties "messages|translations|i18n" .

Length of output: 13900


Script:

#!/bin/bash
# Let's check the content of buildAgents.json files for the specific alert messages
rg -A 5 "alerts" src/main/webapp/i18n/*/buildAgents.json

Length of output: 1904

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
client Pull requests that update TypeScript code. (Added Automatically!) ready for review tests
Projects
Status: Ready For Review
Development

Successfully merging this pull request may close these issues.

1 participant