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 all 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
- name: before
in: query
required: false
schema:
type: string
format: date
responses:
"200":
description: OK
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package de.tum.in.www1.hephaestus.codereview.user;

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

Expand Down Expand Up @@ -39,4 +40,12 @@ SELECT new UserDTO(u.id, u.login, u.email, u.name, u.url)
JOIN FETCH u.reviews
""")
List<User> findAllWithRelations();

@Query("""
SELECT u
FROM User u
JOIN FETCH u.reviews re
WHERE re.createdAt BETWEEN :after AND :before
""")
List<User> findAllInTimeframe(@Param("after") OffsetDateTime after, @Param("before") OffsetDateTime before);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package de.tum.in.www1.hephaestus.codereview.user;

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

Expand Down Expand Up @@ -31,4 +32,9 @@ public List<User> getAllUsers() {
logger.info("Getting all users");
return userRepository.findAll().stream().toList();
}

public List<User> getAllUsersInTimeframe(OffsetDateTime after, OffsetDateTime before) {
logger.info("Getting all users in timeframe between " + after + " and " + before);
return userRepository.findAllInTimeframe(after, before);
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package de.tum.in.www1.hephaestus.leaderboard;

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

import org.springframework.format.annotation.DateTimeFormat;
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 +22,9 @@ public LeaderboardController(LeaderboardService leaderboardService) {
}

@GetMapping
public ResponseEntity<List<LeaderboardEntry>> getLeaderboard() {
return ResponseEntity.ok(leaderboardService.createLeaderboard());
public ResponseEntity<List<LeaderboardEntry>> getLeaderboard(
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Optional<LocalDate> after,
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Optional<LocalDate> before) {
return ResponseEntity.ok(leaderboardService.createLeaderboard(after, before));
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package de.tum.in.www1.hephaestus.leaderboard;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
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,16 +38,20 @@ public LeaderboardService(UserService userService) {
this.userService = userService;
}

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

List<User> users = userService.getAllUsers();
logger.info("Leaderboard has " + users.size() + " users");
LocalDateTime afterCutOff = after.isPresent() ? after.get().atStartOfDay()
: LocalDate.now().minusDays(timeframe).atStartOfDay();
Optional<LocalDateTime> beforeCutOff = before.map(date -> date.plusDays(1).atStartOfDay());

OffsetDateTime cutOffTime = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * timeframe)
.toInstant().atOffset(ZoneOffset.UTC);
List<User> users = userService.getAllUsersInTimeframe(afterCutOff.atOffset(ZoneOffset.UTC),
beforeCutOff.map(b -> b.atOffset(ZoneOffset.UTC)).orElse(OffsetDateTime.now()));

logger.info("Found " + users.size() + " users for the leaderboard");

List<LeaderboardEntry> leaderboard = users.stream().map(user -> {
// ignore non-users, e.g. bots
if (user.getType() != UserType.USER) {
return null;
}
Expand All @@ -55,12 +61,11 @@ 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
Collaborator 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
Collaborator 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
Collaborator 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)))
.forEach(review -> {
if (review.getPullRequest().getAuthor().getLogin().equals(user.getLogin())) {
return;
}

PullRequestReviewDTO reviewDTO = new PullRequestReviewDTO(review.getId(), review.getCreatedAt(),
review.getUpdatedAt(), review.getSubmittedAt(), review.getState());

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>>;

}
16 changes: 12 additions & 4 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,15 @@ import { lastValueFrom } from 'rxjs';
export class HomeComponent {
leaderboardService = inject(LeaderboardService);

// timeframe for leaderboard
// example: 2024-09-19
private readonly route = inject(ActivatedRoute);
private queryParams = toSignal(this.route.queryParamMap, { requireSync: true });
protected after = computed(() => this.queryParams().get('after') ?? undefined);
protected before = computed(() => this.queryParams().get('before') ?? undefined);

query = injectQuery(() => ({
queryKey: ['leaderboard'],
queryFn: async () => lastValueFrom(this.leaderboardService.getLeaderboard()),
gcTime: Infinity
queryKey: ['leaderboard', { after: this.after(), before: this.before() }],
queryFn: async () => lastValueFrom(this.leaderboardService.getLeaderboard(this.after(), this.before()))
}));
}