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

Programming exercises: Calculate submission time difference with server time #10123

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

Conversation

badkeyy
Copy link
Contributor

@badkeyy badkeyy commented Jan 10, 2025

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).
  • I tested all changes and their related features with all corresponding user types on a test server configured with Gitlab and Jenkins.

Motivation and Context

Currently the submission time difference ("Submitted X minutes ago") has been calculated with client time. With this PR it gets now calculated with server time.
Fixes #9940

Description

I changed the ArtemisTimeAgoPipe to use server time (ArtemisServerDateService) and not client time. I also adapted the tests for it.

Steps for Testing

Prerequisites:

  • 1 Instructor
  1. Log in to Artemis
  2. Go to a programming exercise
  3. Make a change to it's code
  4. Press on the build run status
  5. See the time since the submission
  6. Change your local system time
  7. Reload the page and find the submission to be still the same time ago

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

Exam Mode Test

  • Test 1
  • Test 2

Performance Tests

  • Test 1
  • Test 2

Test Coverage

Screenshots

video

Summary by CodeRabbit

  • New Features

    • Introduced server time synchronization for time-based calculations
    • Added a mock service for testing time-related functionality
  • Tests

    • Updated test suite to support new server time dependency
    • Added mock implementation for server date service
  • Refactor

    • Modified time calculation logic to use server time instead of local time

@github-actions github-actions bot added the client Pull requests that update TypeScript code. (Added Automatically!) label Jan 10, 2025
@badkeyy badkeyy changed the title 'Programming Exercises': Calculate submission time with server time Programming Exercises: Calculate submission time with server time Jan 10, 2025
@badkeyy badkeyy changed the title Programming Exercises: Calculate submission time with server time Programming exercises: Calculate submission time with server time Jan 10, 2025
Copy link

⚠️ Unable to deploy to test servers ⚠️

The docker build needs to run through before deploying.

@github-actions github-actions bot added the deployment-error Added by deployment workflows if an error occured label Jan 10, 2025
@github-actions github-actions bot added the tests label Jan 10, 2025
@badkeyy badkeyy added deploy:artemis-test2 and removed deployment-error Added by deployment workflows if an error occured labels Jan 10, 2025
@badkeyy badkeyy temporarily deployed to artemis-test2.artemis.cit.tum.de January 10, 2025 02:51 — with GitHub Actions Inactive
@badkeyy badkeyy changed the title Programming exercises: Calculate submission time with server time Programming exercises: Calculate submission time difference with server time Jan 10, 2025
@badkeyy badkeyy marked this pull request as ready for review January 10, 2025 03:51
@badkeyy badkeyy requested a review from a team as a code owner January 10, 2025 03:51
Copy link

coderabbitai bot commented Jan 10, 2025

Walkthrough

The pull request introduces a modification to the ArtemisTimeAgoPipe to use server time instead of local time when calculating time differences. A new ArtemisServerDateService is injected into the pipe, allowing it to retrieve the current time from the server. A mock service is also created for testing purposes. The changes aim to address discrepancies in time calculation that can occur when a client's local time is not synchronized with the server time.

Changes

File Change Summary
src/main/webapp/app/shared/pipes/artemis-time-ago.pipe.ts Added ArtemisServerDateService dependency to constructor, modified format method to use server time
src/test/javascript/spec/helpers/mocks/service/mock-artemis-server-date.service.ts Added new mock service MockArtemisServerDateService with now() method
src/test/javascript/spec/pipe/artemis-time-ago.pipe.spec.ts Updated test suite to include ArtemisServerDateService and its mock implementation

Assessment against linked issues

Objective Addressed Explanation
Calculate submission time using server time [#9940]
Resolve time discrepancy when local time is out of sync

Possibly related PRs

Suggested labels

server, bugfix, ready for review, programming

Suggested reviewers

  • krusche
  • SimonEntholzer
  • HawKhiem
  • EneaGore
  • florian-glombik

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 0

🔭 Outside diff range comments (3)
src/test/javascript/spec/pipe/artemis-time-ago.pipe.spec.ts (1)

Line range hint 35-43: Make tests more deterministic by using fixed timestamps

Current tests use dynamic time calculations with dayjs(), which could lead to flaky tests. Consider using fixed timestamps and the mock service's capabilities for more reliable testing.

-    it.each([
-        { value: dayjs().add(5, 'minutes'), expected: { en: 'in 5 minutes', de: 'in 5 Minuten' } },
-        { value: dayjs().add(10, 'minutes'), expected: { en: 'in 10 minutes', de: 'in 10 Minuten' } },
+    it.each([
+        { minutes: 5, future: true, expected: { en: 'in 5 minutes', de: 'in 5 Minuten' } },
+        { minutes: 10, future: true, expected: { en: 'in 10 minutes', de: 'in 10 Minuten' } },
+    ])('returns the correct time and switches the language correctly', ({ minutes, future, expected }) => {
+        const baseTime = dayjs('2024-01-01T12:00:00Z');
+        const testTime = future ? baseTime.add(minutes, 'minutes') : baseTime.subtract(minutes, 'minutes');
+        (serverTimeService as MockArtemisServerDateService).setMockDate(baseTime);
src/main/webapp/app/shared/pipes/artemis-time-ago.pipe.ts (2)

Line range hint 51-70: Enhance timer cleanup to prevent memory leaks

The timer cleanup in createTimer could be more robust. Consider adding error handling and ensuring cleanup on all paths.

     private createTimer() {
         if (this.currentTimer) {
+            this.removeTimer(); // Ensure cleanup of existing timer
             return;
         }
 
         const dayjsInstance = dayjs(this.lastValue);
         const timeToUpdate = getSecondsUntilUpdate(dayjsInstance) * 1000;
 
         this.currentTimer = this.ngZone.runOutsideAngular(() => {
             if (typeof window !== 'undefined') {
-                return window.setTimeout(() => {
+                const timerId = window.setTimeout(() => {
+                    if (this.currentTimer !== timerId) {
+                        return; // Another timer was created
+                    }
                     this.lastText = this.formatFn(dayjs(this.lastValue));
                     this.currentTimer = null;
                     this.ngZone.run(() => this.cdRef.markForCheck());
                 }, timeToUpdate);
+                return timerId;
             } else {
                 return null;
             }
         });
     }

Use ArtemisServerDateService for timer intervals

The suggestion to use server time is correct, but instead of passing server time as a parameter, use the already injected ArtemisServerDateService:

 function getSecondsUntilUpdate(dayjsInstance: dayjs.Dayjs) {
-    const howOld = Math.abs(dayjs().diff(dayjsInstance, 'minute'));
+    const howOld = Math.abs(this.serverDateService.now().diff(dayjsInstance, 'minute'));
🔗 Analysis chain

Line range hint 89-93: Verify timer intervals with server time

The getSecondsUntilUpdate function uses client-side time (dayjs()) to calculate update intervals. This should be updated to use server time for consistency.

 function getSecondsUntilUpdate(dayjsInstance: dayjs.Dayjs) {
-    const howOld = Math.abs(dayjs().diff(dayjsInstance, 'minute'));
+    // TODO: Pass serverTime as parameter
+    const howOld = Math.abs(serverTime.diff(dayjsInstance, 'minute'));

Let's verify the usage of this function:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for references to getSecondsUntilUpdate to ensure we can safely modify its signature
rg "getSecondsUntilUpdate" --type ts

Length of output: 287


Script:

#!/bin/bash
# Search for server time related patterns
rg -i "serverTime|server[._]time" --type ts -A 2

# Search for time sync or server clock patterns
rg -i "time[._]sync|clock[._]sync" --type ts -A 2

Length of output: 2139

🧹 Nitpick comments (3)
src/test/javascript/spec/helpers/mocks/service/mock-artemis-server-date.service.ts (1)

3-7: Enhance mock service with configurable time control

The current implementation always returns the actual current time, which might not be suitable for all test scenarios. Consider adding the ability to set a specific time for more deterministic tests.

 export class MockArtemisServerDateService {
+    private mockDate?: dayjs.Dayjs;
+
+    setMockDate(date: dayjs.Dayjs): void {
+        this.mockDate = date;
+    }
+
     now(): dayjs.Dayjs {
-        return dayjs();
+        return this.mockDate || dayjs();
     }
 }
src/test/javascript/spec/pipe/artemis-time-ago.pipe.spec.ts (1)

Line range hint 47-58: Add test coverage for edge cases

The test suite should include additional scenarios to ensure robust handling of various time differences.

Consider adding tests for:

  • Different time zones
  • Date transitions (day/month/year boundaries)
  • Invalid date inputs
  • Extreme time differences
src/main/webapp/app/shared/pipes/artemis-time-ago.pipe.ts (1)

28-30: Consider caching server time for performance

The format method calls serverDateService.now() on every invocation, which could lead to unnecessary server calls. Consider caching the server time and updating it periodically.

+    private lastServerTime: dayjs.Dayjs;
+    private readonly SERVER_TIME_UPDATE_INTERVAL = 60000; // 1 minute
+
+    private updateServerTime(): void {
+        this.lastServerTime = this.serverDateService.now();
+    }
+
     format(date: dayjs.Dayjs) {
-        return date.locale(this.lastLocale).from(this.serverDateService.now(), this.lastOmitSuffix);
+        return date.locale(this.lastLocale).from(this.lastServerTime, this.lastOmitSuffix);
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 599c92e and 6708a73.

📒 Files selected for processing (3)
  • src/main/webapp/app/shared/pipes/artemis-time-ago.pipe.ts (2 hunks)
  • src/test/javascript/spec/helpers/mocks/service/mock-artemis-server-date.service.ts (1 hunks)
  • src/test/javascript/spec/pipe/artemis-time-ago.pipe.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/test/javascript/spec/helpers/mocks/service/mock-artemis-server-date.service.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/pipe/artemis-time-ago.pipe.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/shared/pipes/artemis-time-ago.pipe.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

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis

Copy link

@vinceclifford vinceclifford left a comment

Choose a reason for hiding this comment

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

Tested on TS3, works as expected.

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: Work In Progress
Development

Successfully merging this pull request may close these issues.

Exercises: Submission time should be calculated using server time
2 participants