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

Leaderboard: Custom Sliding Time Window #100

Merged
merged 16 commits into from
Sep 22, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions server/application-server/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,19 @@ paths:
tags:
- leaderboard
operationId: getLeaderboard
parameters:
- name: after
in: query
required: false
schema:
type: string
format: date-time
- name: before
in: query
required: false
schema:
type: string
format: date-time
responses:
"200":
description: OK
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package de.tum.in.www1.hephaestus.leaderboard;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
Expand All @@ -18,7 +21,8 @@ public LeaderboardController(LeaderboardService leaderboardService) {
}

@GetMapping
public ResponseEntity<List<LeaderboardEntry>> getLeaderboard() {
return ResponseEntity.ok(leaderboardService.createLeaderboard());
public ResponseEntity<List<LeaderboardEntry>> getLeaderboard(@RequestParam Optional<OffsetDateTime> after,
@RequestParam Optional<OffsetDateTime> before) {
return ResponseEntity.ok(leaderboardService.createLeaderboard(after, before));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -36,14 +37,17 @@ public LeaderboardService(UserService userService) {
this.userService = userService;
}

public List<LeaderboardEntry> createLeaderboard() {
public List<LeaderboardEntry> createLeaderboard(Optional<OffsetDateTime> after, Optional<OffsetDateTime> before) {
logger.info("Creating leaderboard dataset");

List<User> users = userService.getAllUsers();
logger.info("Leaderboard has " + users.size() + " users");

OffsetDateTime cutOffTime = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * timeframe)
.toInstant().atOffset(ZoneOffset.UTC);
OffsetDateTime afterCutOff = after.isPresent() ? after.get()
: new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * timeframe).toInstant()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Maybe we should round to the beginning of the day?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Or what happens with 2024-09-10? I guess it will use midnight, then it might be important for the after case. If you for example use 2024-09-15 as before I think it should get all timestamps before the end of day. So actually we would need to round up?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If no timestamp is provided, it should default to midnight, yes.

While I personally find different default timestamps for before and after confusing, I do see why this would be expected behavior for users. Will change it 👍

Copy link
Contributor Author

@GODrums GODrums Sep 21, 2024

Choose a reason for hiding this comment

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

Had a look through Java best practices and found this sheet: https://i.sstatic.net/WyAl2.png

Equivalently to your idea, after and before are now only dates (LocalDate - without timestamp) with an interpretation as the start and end of the day on the server respectively. Also looks much cleaner in the URL (example: http://localhost:4200/?after=2024-09-21&before=2024-09-23).

Implemented this change in b76ed6d.

.atOffset(ZoneOffset.UTC);

logger.info("Leaderboard has " + users.size() + " users with cut-off time " + afterCutOff + " and before time "
+ before);

List<LeaderboardEntry> leaderboard = users.stream().map(user -> {
if (user.getType() != UserType.USER) {
Expand All @@ -55,8 +59,8 @@ public List<LeaderboardEntry> createLeaderboard() {
Set<PullRequestReviewDTO> commentSet = new HashSet<>();

user.getReviews().stream()
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think user.getReviews could already support querying by timeframe.

Copy link
Contributor Author

@GODrums GODrums Sep 20, 2024

Choose a reason for hiding this comment

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

So if I understand your idea correctly, you would like to do the filtering in the SQL-Query already?

That's a great idea for performance improvements, I will take a look at it.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I tried out a Query like this:

SELECT u
FROM User u
JOIN FETCH u.pullRequests 
JOIN FETCH u.issueComments
JOIN FETCH u.reviewComments
JOIN FETCH u.reviews re
WHERE re.createdAt between :after and :before
OR re.updatedAt between :after and :before

but it doesn't seem to return any results, most likely I'm missing something regarding the format conversion.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Managed to find the correct SQL query to filter the dates.
With 63c434d, we now filter directly in the DB.

.filter(review -> (review.getCreatedAt() != null && review.getCreatedAt().isAfter(cutOffTime))
|| (review.getUpdatedAt() != null && review.getUpdatedAt().isAfter(cutOffTime)))
.filter(review -> isInTimeframe(review.getCreatedAt(), afterCutOff, before)
|| isInTimeframe(review.getUpdatedAt(), afterCutOff, before))
.forEach(review -> {
if (review.getPullRequest().getAuthor().getLogin().equals(user.getLogin())) {
return;
Expand Down Expand Up @@ -99,6 +103,10 @@ public List<LeaderboardEntry> createLeaderboard() {
return leaderboard;
}

private boolean isInTimeframe(OffsetDateTime date, OffsetDateTime after, Optional<OffsetDateTime> before) {
return date != null && (before.isPresent() && date.isAfter(before.get()) || date.isBefore(after));
}

/**
* Calculates the score for a given pull request.
* Possible values: 1, 3, 7, 17, 33.
Expand Down
21 changes: 17 additions & 4 deletions webapp/src/app/core/modules/openapi/api/leaderboard.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,25 @@ export class LeaderboardService implements LeaderboardServiceInterface {
}

/**
* @param after
* @param before
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getLeaderboard(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<LeaderboardEntry>>;
public getLeaderboard(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<LeaderboardEntry>>>;
public getLeaderboard(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<LeaderboardEntry>>>;
public getLeaderboard(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getLeaderboard(after?: string, before?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<LeaderboardEntry>>;
public getLeaderboard(after?: string, before?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<LeaderboardEntry>>>;
public getLeaderboard(after?: string, before?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<LeaderboardEntry>>>;
public getLeaderboard(after?: string, before?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {

let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (after !== undefined && after !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>after, 'after');
}
if (before !== undefined && before !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>before, 'before');
}

let localVarHeaders = this.defaultHeaders;

Expand Down Expand Up @@ -144,6 +156,7 @@ export class LeaderboardService implements LeaderboardServiceInterface {
return this.httpClient.request<Array<LeaderboardEntry>>('get', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ export interface LeaderboardServiceInterface {
/**
*
*
* @param after
* @param before
*/
getLeaderboard(extraHttpRequestParams?: any): Observable<Array<LeaderboardEntry>>;
getLeaderboard(after?: string, before?: string, extraHttpRequestParams?: any): Observable<Array<LeaderboardEntry>>;

}
15 changes: 12 additions & 3 deletions webapp/src/app/home/home.component.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Component, inject } from '@angular/core';
import { Component, computed, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { injectQuery } from '@tanstack/angular-query-experimental';
import { LeaderboardService } from 'app/core/modules/openapi/api/leaderboard.service';
import { LeaderboardComponent } from 'app/home/leaderboard/leaderboard.component';
import { lastValueFrom } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';

@Component({
selector: 'app-home',
Expand All @@ -13,9 +15,16 @@ import { lastValueFrom } from 'rxjs';
export class HomeComponent {
leaderboardService = inject(LeaderboardService);

// timeframe for leaderboard
// example: 2024-09-19T10:15:30+01:00
GODrums marked this conversation as resolved.
Show resolved Hide resolved
private readonly route = inject(ActivatedRoute);
private queryParams = toSignal(this.route.queryParamMap, { requireSync: true });
protected after = computed(() => this.queryParams().get('after')?.replace(' ', '+') ?? undefined);
protected before = computed(() => this.queryParams().get('before')?.replace(' ', '+') ?? undefined);

query = injectQuery(() => ({
queryKey: ['leaderboard'],
queryFn: async () => lastValueFrom(this.leaderboardService.getLeaderboard()),
queryKey: ['leaderboard', { after: this.after, before: this.before }],
GODrums marked this conversation as resolved.
Show resolved Hide resolved
queryFn: async () => lastValueFrom(this.leaderboardService.getLeaderboard(this.after(), this.before())),
gcTime: Infinity
GODrums marked this conversation as resolved.
Show resolved Hide resolved
}));
}