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: Add science events to user data export #8861

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

Conversation

N0W0RK
Copy link

@N0W0RK N0W0RK commented Jun 23, 2024

Checklist

General

  • I tested all changes and their related features with all corresponding user types on a test server.
  • This is a small issue that I tested locally and was confirmed by another developer on a test server.
  • I chose a title conforming to the naming conventions for pull requests.

Server

  • Important: I implemented the changes with a very good performance and prevented too many (unnecessary) database calls.
  • I strictly followed the server coding and design guidelines.
  • I added multiple integration tests (Spring) related to the features (with a high test coverage).
  • I documented the Java code using JavaDoc style.

Motivation and Context

Due to GDPR regulations, all personal data has to be made available to the end user if requested. This was not the case for the science events collected.

Description

This PR adds a new DataExportScienceEventService responsible for exporting all science events associated with a user.
All science events are exported as a single csv containing a timestamp, an event type and the associated resource.
Closes #8655

Steps for Testing

Prerequisites:

  • The Science feature enabled
  • 1 Student with science data collection enabled
  • 1 Lecture Unit
  • 1 Exercise (of any type)
  • When Developing locally line 66-71 in DataExportScheduleService have to be commented out or removed.
  1. Log in to Artemis
  2. Navigate to a course with the above mentioned prerequisites.
  3. Open a Lecture and note the rough time.
  4. Open a Lecture unit and note the rough time.
  5. Open an Exercise and note the rough time.
  6. Navigate to Privacy (bottom of the screen)
  7. Scroll to the bottom of the page
  8. Click on Data Export
  9. Click on Request Data Export
  10. Enter user login.
  11. Click Request Data Export
  12. In the testing environment the export should be created after 1-2 minutes.
  13. After beeing notified, that the export is ready, click the link in the notfication or your emails.
  14. Select Download data export
  15. Extract the downloaded ZIP folder.
  16. Ensure that the timestamps in science_ecents.csv coincide with the times noted down.

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
  • I (as a reviewer) confirm that the server changes (in particular related to database calls) are implemented with a very good performance

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Test Coverage

Class/File Line Coverage Confirmation (assert/expect)
DataExportScienceEventService.java 100%
DataExportCreationService.java 92%

Summary by CodeRabbit

  • New Features

    • Added the ability to export science event data to CSV files.
  • Bug Fixes

    • Adjusted scheduling for data export creation and deletion to run every minute.
  • Tests

    • Enhanced test coverage for science event data export functionality, including CSV export validation.

These updates improve data export capabilities and ensure timely data management for users.

@github-actions github-actions bot added tests server Pull requests that update Java code. (Added Automatically!) labels Jun 23, 2024
@github-actions github-actions bot added the config-change Pull requests that change the config in a way that they require a deployment via Ansible. label Jun 23, 2024
Adds new DataExportScienceEventService.
Ammends DataExportCreationService and ScienceEventRepository with necessary functionality
Tests if necessary CSV is present.
@N0W0RK N0W0RK force-pushed the feature/general/export-science-events branch from 0d68c78 to 30bb32d Compare June 23, 2024 23:38
@N0W0RK N0W0RK marked this pull request as ready for review June 23, 2024 23:39
@N0W0RK N0W0RK requested a review from a team as a code owner June 23, 2024 23:39
Copy link

coderabbitai bot commented Jun 23, 2024

Walkthrough

The changes introduce a comprehensive system for exporting science events as part of user data. This includes repository and service modifications for handling science events, updates to export creation services for CSV generation, and scheduled tasks for data exports.

Changes

Files/Modules Change Summary
.../repository/science/ScienceEventRepository.java Added method findAllByIdentity for retrieving science events by user identity.
.../service/export/DataExportCreationService.java Integrated DataExportScienceEventService for handling science event exports.
.../service/export/DataExportScienceEventService.java New service for creating CSV export files of science events.
.../exercise/ExerciseUtilService.java Added createScienceEvent method for creating science events in tests.
.../science/ScienceUtilService.java New utility service for creating and comparing science events in tests.
.../service/DataExportCreationServiceTest.java Added methods for generating and asserting science events in CSV export tests.
.../service/scheduled/DataExportScheduleService.java Changed scheduling cron expression for data export tasks.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DataExportCreationService
    participant DataExportScienceEventService
    participant ScienceEventRepository
    participant CSVFile

    User->>DataExportCreationService: Request data export
    DataExportCreationService->>DataExportScienceEventService: Create science event export
    DataExportScienceEventService->>ScienceEventRepository: findAllByIdentity(identity)
    ScienceEventRepository-->>DataExportScienceEventService: Return ScienceEvents
    DataExportScienceEventService->>CSVFile: Write ScienceEvents to CSV
    CSVFile -->> User: Provide data export
Loading

Assessment against linked issues

Objective Addressed Explanation
Include collected events in user data export (#8655)

Recent review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between dc180cc and dac3b80.

Files selected for processing (1)
  • src/main/java/de/tum/in/www1/artemis/service/scheduled/DataExportScheduleService.java (1 hunks)
Additional context used
Path-based instructions (1)
src/main/java/de/tum/in/www1/artemis/service/scheduled/DataExportScheduleService.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 not posted (1)
src/main/java/de/tum/in/www1/artemis/service/scheduled/DataExportScheduleService.java (1)

65-65: Verify the necessity of the frequent cron schedule.

The cron expression has been changed to run every minute. This could potentially lead to high load on the server and database, especially if the data export process is resource-intensive. It's crucial to ensure that this frequency is necessary and that the system can handle it without performance degradation.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

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

Copy link
Contributor

@Strohgelaender Strohgelaender left a comment

Choose a reason for hiding this comment

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

Your test only test if there exists a science event file in the export, but it does not verify its content. Please also test that the events actually get correctly exported.

@@ -103,7 +103,7 @@ artemis:

scheduling: # these values are cron expressions. To generate one, you can use e.g. https://www.freeformatter.com/cron-expression-generator-quartz.html
programming-exercises-cleanup-time: 0 0 3 * * * # every day at 3am
data-export-creation-time: 0 0 4 * * * # every day at 4am
data-export-creation-time: 0 * * ? * * # every minute
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder to change this after testing.

@N0W0RK N0W0RK force-pushed the feature/general/export-science-events branch from c3aa0a2 to 8723a0a Compare June 25, 2024 02:33
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

JohannesStoehr
JohannesStoehr previously approved these changes Jun 25, 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

@JohannesWt
Copy link
Contributor

Tested on TS5, when clicking on privacy I get the following error.
Screenshot 2024-06-26 at 08 26 41

@N0W0RK
Copy link
Author

N0W0RK commented Jun 26, 2024

There is no privacy policy deployed on the testservers. Therfore when trying to load the policy a not found error is thrown. The data export should still be available.


Duration d = Duration.between(e1.getTimestamp(), e2.getTimestamp());
System.out.println(d.getNano());
if (d.getNano() > 500 && d.getSeconds() >= 0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I think this could be simplified by using the metod d.toMillis().

Copy link
Author

Choose a reason for hiding this comment

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

Working with millis is imo to broad of a timescale. During testing events are generated in a microsecond time frame. In case multiple scienceevents with the same type and resource occur in quick succession (wich i belive could also happen with real world data.) they would not be differentiated. Especially when rounding then leads to to big of a difference.

@N0W0RK N0W0RK force-pushed the feature/general/export-science-events branch from 5efc998 to 24b8bd8 Compare June 27, 2024 13:46
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

coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 27, 2024
Copy link
Contributor

@MaximilianAnzinger MaximilianAnzinger left a comment

Choose a reason for hiding this comment

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

The ArchTest for Logging is failing

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

coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 27, 2024
Sets the cronjob directly in the DataExportScheduleService.
Needs to be reverted before merge.
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

@@ -62,7 +62,7 @@ public DataExportScheduleService(DataExportRepository dataExportRepository, Data
* Created will be all data exports that are in the state REQUESTED OR IN_CREATION
* Deleted will be all data exports that have a creation date older than seven days
*/
@Scheduled(cron = "${artemis.scheduling.data-export-creation-time: 0 0 4 * * *}")
@Scheduled(cron = "0 * * ? * *")
Copy link

Choose a reason for hiding this comment

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

Suggest improvements in resource management and error handling.

The method uses an ExecutorService to manage concurrent tasks, which is a good practice. However, there are a few areas for improvement:

  1. Resource Management: The method should ensure that all resources, especially threads in the ExecutorService, are properly managed. For example, the executor should be shut down in a finally block to ensure it always happens, even if an exception is thrown.
  2. Error Handling: Exceptions thrown by the createDataExport method are not caught, which might lead to unhandled exceptions that could disrupt the scheduling.
  3. Logging: More detailed logging could be beneficial, especially logging the exceptions, to provide better insights during troubleshooting.
-        ExecutorService executor = Executors.newFixedThreadPool(10);
+        ExecutorService executor = Executors.newFixedThreadPool(10); // Consider configuring the thread pool size dynamically based on system properties.
         try {
             dataExportsToBeCreated.forEach(dataExport -> executor.execute(() -> createDataExport(dataExport, successfulDataExports)));
+            executor.shutdown();
+            if (!executor.awaitTermination(60, java.util.concurrent.TimeUnit.MINUTES)) {
+                log.warn("Executor did not terminate in the expected time.");
+                executor.shutdownNow();
+            }
+        } catch (Exception e) {
+            log.error("Error during data export creation.", e);
+        } finally {
+            if (!executor.isShutdown()) {
+                executor.shutdownNow();
+            }
         }
-        executor.shutdown();
-        if (!executor.awaitTermination(60, java.util.concurrent.TimeUnit.MINUTES)) {
-            log.info("Not all pending data exports could be created within 60 minutes.");
-            executor.shutdownNow();
-        }
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
@Scheduled(cron = "0 * * ? * *")
ExecutorService executor = Executors.newFixedThreadPool(10); // Consider configuring the thread pool size dynamically based on system properties.
try {
dataExportsToBeCreated.forEach(dataExport -> executor.execute(() -> createDataExport(dataExport, successfulDataExports)));
executor.shutdown();
if (!executor.awaitTermination(60, java.util.concurrent.TimeUnit.MINUTES)) {
log.warn("Executor did not terminate in the expected time.");
executor.shutdownNow();
}
} catch (Exception e) {
log.error("Error during data export creation.", e);
} finally {
if (!executor.isShutdown()) {
executor.shutdownNow();
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
config-change Pull requests that change the config in a way that they require a deployment via Ansible. ready for review server Pull requests that update Java code. (Added Automatically!) tests
Projects
Status: Ready For Review
Development

Successfully merging this pull request may close these issues.

General: Include collected events in user data export
5 participants