Skip to content
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
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.patinanetwork.codebloom.common.db.repos.task;

import java.util.List;
import java.util.Optional;
import org.patinanetwork.codebloom.common.db.models.task.BackgroundTask;
import org.patinanetwork.codebloom.common.db.models.task.BackgroundTaskEnum;

Expand All @@ -18,11 +19,11 @@ public interface BackgroundTaskRepository {
*/
void createBackgroundTask(BackgroundTask task);

BackgroundTask getBackgroundTaskById(String id);
Optional<BackgroundTask> getBackgroundTaskById(String id);

List<BackgroundTask> getBackgroundTasksByTaskEnum(BackgroundTaskEnum taskEnum);

BackgroundTask getMostRecentlyCompletedBackgroundTaskByTaskEnum(BackgroundTaskEnum taskEnum);
Optional<BackgroundTask> getMostRecentlyCompletedBackgroundTaskByTaskEnum(BackgroundTaskEnum taskEnum);

/**
* @note - The provided object's methods will be overridden with any returned data from the database.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.sql.DataSource;
import org.patinanetwork.codebloom.common.db.helper.NamedPreparedStatement;
Expand Down Expand Up @@ -61,7 +62,7 @@ public void createBackgroundTask(final BackgroundTask task) {
}

@Override
public BackgroundTask getBackgroundTaskById(final String id) {
public Optional<BackgroundTask> getBackgroundTaskById(final String id) {
String sql = """
SELECT
*
Expand All @@ -76,14 +77,14 @@ public BackgroundTask getBackgroundTaskById(final String id) {
stmt.setObject("id", UUID.fromString(id));
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return parseResultSetToBackgroundTask(rs);
return Optional.of(parseResultSetToBackgroundTask(rs));
}
}
} catch (Exception e) {
throw new RuntimeException("Failed to get background task by ID", e);
}
Comment thread
luoh00 marked this conversation as resolved.

Comment thread
luoh00 marked this conversation as resolved.
return null;
return Optional.empty();
Comment thread
luoh00 marked this conversation as resolved.
Comment thread
luoh00 marked this conversation as resolved.
}

@Override
Expand Down Expand Up @@ -114,7 +115,8 @@ public List<BackgroundTask> getBackgroundTasksByTaskEnum(final BackgroundTaskEnu
}

@Override
public BackgroundTask getMostRecentlyCompletedBackgroundTaskByTaskEnum(final BackgroundTaskEnum taskEnum) {
public Optional<BackgroundTask> getMostRecentlyCompletedBackgroundTaskByTaskEnum(
final BackgroundTaskEnum taskEnum) {
String sql = """
SELECT
*
Expand All @@ -132,14 +134,14 @@ public BackgroundTask getMostRecentlyCompletedBackgroundTaskByTaskEnum(final Bac
stmt.setObject("task", taskEnum.name(), java.sql.Types.OTHER);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return parseResultSetToBackgroundTask(rs);
return Optional.of(parseResultSetToBackgroundTask(rs));
}
}
} catch (Exception e) {
throw new RuntimeException("Failed to get most recently completed background task by task enum", e);
}

return null;
return Optional.empty();
Comment thread
luoh00 marked this conversation as resolved.
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -59,11 +60,13 @@ private void runStartupSynchronization() {

@Scheduled(initialDelay = 1, fixedDelay = 3, timeUnit = TimeUnit.HOURS)
public void updateQuestionBank() {
BackgroundTask recentLeetcodeTask = backgroundTaskRepository.getMostRecentlyCompletedBackgroundTaskByTaskEnum(
BackgroundTaskEnum.LEETCODE_QUESTION_BANK);
if (recentLeetcodeTask != null) {
Optional<BackgroundTask> recentLeetcodeTask =
backgroundTaskRepository.getMostRecentlyCompletedBackgroundTaskByTaskEnum(
BackgroundTaskEnum.LEETCODE_QUESTION_BANK);

if (recentLeetcodeTask.isPresent()) {
if (StandardizedOffsetDateTime.now()
.isBefore(recentLeetcodeTask.getCompletedAt().plusHours(16))) {
.isBefore(recentLeetcodeTask.get().getCompletedAt().plusHours(16))) {
Comment thread
luoh00 marked this conversation as resolved.
log.error("Not time yet to resync question bank");
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.patinanetwork.codebloom.common.components.LeaderboardException;
Expand Down Expand Up @@ -40,7 +41,7 @@ public AddUserMetricsService(
@Scheduled(initialDelay = 0, fixedDelay = 30, timeUnit = TimeUnit.MINUTES)
public void congregateUserMetrics() {
try {
BackgroundTask recentMetricsTask =
Optional<BackgroundTask> recentMetricsTask =
backgroundTaskRepository.getMostRecentlyCompletedBackgroundTaskByTaskEnum(
BackgroundTaskEnum.USER_METRICS);

Comment thread
luoh00 marked this conversation as resolved.
Expand All @@ -50,9 +51,9 @@ public void congregateUserMetrics() {
.atStartOfDay(ZoneOffset.UTC)
.toOffsetDateTime();

if (recentMetricsTask != null
&& recentMetricsTask.getCompletedAt() != null
&& !recentMetricsTask.getCompletedAt().isBefore(midnight)) {
if (recentMetricsTask.isPresent()
&& recentMetricsTask.get().getCompletedAt() != null
&& !recentMetricsTask.get().getCompletedAt().isBefore(midnight)) {
log.info("Skipping user metrics sync because today's snapshot already exists.");
return;
}
Comment thread
luoh00 marked this conversation as resolved.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.*;
Expand Down Expand Up @@ -31,6 +32,10 @@ public BackgroundTaskRepositoryTest(final BackgroundTaskSqlRepository background

@BeforeAll
void createBackgroundTask() {
Optional<BackgroundTask> recentTask = backgroundTaskRepository.getMostRecentlyCompletedBackgroundTaskByTaskEnum(
BackgroundTaskEnum.LEETCODE_QUESTION_BANK);
assertTrue(recentTask.isEmpty());

testTask = BackgroundTask.builder()
.task(BackgroundTaskEnum.LEETCODE_QUESTION_BANK)
.completedAt(StandardizedOffsetDateTime.now())
Expand All @@ -54,9 +59,9 @@ void cleanUp() {
@Test
@Order(1)
void testGetBackgroundTaskById() {
BackgroundTask found = backgroundTaskRepository.getBackgroundTaskById(testTask.getId());
assertNotNull(found);
assertEquals(testTask, found);
Optional<BackgroundTask> found = backgroundTaskRepository.getBackgroundTaskById(testTask.getId());
assertTrue(found.isPresent());
assertEquals(testTask, found.get());
}

@Test
Expand All @@ -73,11 +78,11 @@ void testGetBackgroundTasksByTaskEnum() {
@Test
@Order(3)
void testGetMostRecentlyCompletedBackgroundTaskByTaskEnum() {
BackgroundTask recentTask = backgroundTaskRepository.getMostRecentlyCompletedBackgroundTaskByTaskEnum(
Optional<BackgroundTask> recentTask = backgroundTaskRepository.getMostRecentlyCompletedBackgroundTaskByTaskEnum(
BackgroundTaskEnum.LEETCODE_QUESTION_BANK);
assertNotNull(recentTask);
assertEquals(BackgroundTaskEnum.LEETCODE_QUESTION_BANK, recentTask.getTask());
assertNotNull(recentTask.getCompletedAt());
assertTrue(recentTask.isPresent());
assertEquals(BackgroundTaskEnum.LEETCODE_QUESTION_BANK, recentTask.get().getTask());
assertNotNull(recentTask.get().getCompletedAt());
}

@Test
Expand All @@ -93,10 +98,10 @@ void testUpdateBackgroundTaskById() {
boolean updateResult = backgroundTaskRepository.updateBackgroundTaskById(updatedTask);
assertTrue(updateResult);

BackgroundTask retrieved = backgroundTaskRepository.getBackgroundTaskById(testTask.getId());
assertNotNull(retrieved);
assertEquals(BackgroundTaskEnum.LEETCODE_QUESTION_BANK, retrieved.getTask());
assertEquals(newCompletedAt, retrieved.getCompletedAt());
Optional<BackgroundTask> retrieved = backgroundTaskRepository.getBackgroundTaskById(testTask.getId());
assertTrue(retrieved.isPresent());
assertEquals(BackgroundTaskEnum.LEETCODE_QUESTION_BANK, retrieved.get().getTask());
assertEquals(newCompletedAt, retrieved.get().getCompletedAt());
}

@Test
Expand All @@ -110,18 +115,18 @@ void testCreateAnotherBackgroundTask() {
backgroundTaskRepository.createBackgroundTask(anotherTask);
assertNotNull(anotherTask.getId());

BackgroundTask found = backgroundTaskRepository.getBackgroundTaskById(anotherTask.getId());
assertNotNull(found);
assertEquals(anotherTask.getTask(), found.getTask());
assertEquals(anotherTask, found);
Optional<BackgroundTask> found = backgroundTaskRepository.getBackgroundTaskById(anotherTask.getId());
assertTrue(found.isPresent());
assertEquals(anotherTask.getTask(), found.get().getTask());
assertEquals(anotherTask, found.get());
}

@Test
@Order(6)
void testGetBackgroundTaskByIdNotFound() {
BackgroundTask notFound =
Optional<BackgroundTask> notFound =
backgroundTaskRepository.getBackgroundTaskById(UUID.randomUUID().toString());
assertNull(notFound);
assertTrue(notFound.isEmpty());
}

@Test
Expand All @@ -148,9 +153,10 @@ void testCreateBackgroundTaskWithNullCompletedAt() {
backgroundTaskRepository.createBackgroundTask(taskWithNullCompletedAt);
assertNotNull(taskWithNullCompletedAt.getId());

BackgroundTask retrieved = backgroundTaskRepository.getBackgroundTaskById(taskWithNullCompletedAt.getId());
assertNotNull(retrieved);
assertNotNull(retrieved.getCompletedAt(), "completedAt should be set to current time when null");
Optional<BackgroundTask> retrieved =
backgroundTaskRepository.getBackgroundTaskById(taskWithNullCompletedAt.getId());
assertTrue(retrieved.isPresent());
assertNotNull(retrieved.get().getCompletedAt(), "completedAt should be set to current time when null");
}

@Test
Expand Down Expand Up @@ -224,15 +230,15 @@ void testDeleteBackgroundTaskById() {
backgroundTaskRepository.createBackgroundTask(deletableTask);
assertNotNull(deletableTask.getId());

BackgroundTask found = backgroundTaskRepository.getBackgroundTaskById(deletableTask.getId());
assertNotNull(found);
assertEquals(deletableTask, found);
Optional<BackgroundTask> found = backgroundTaskRepository.getBackgroundTaskById(deletableTask.getId());
assertTrue(found.isPresent());
assertEquals(deletableTask, found.get());

boolean deleted = backgroundTaskRepository.deleteBackgroundTaskById(deletableTask.getId());
assertTrue(deleted);

BackgroundTask deletedTask = backgroundTaskRepository.getBackgroundTaskById(deletableTask.getId());
assertNull(deletedTask);
Optional<BackgroundTask> deletedTask = backgroundTaskRepository.getBackgroundTaskById(deletableTask.getId());
assertTrue(deletedTask.isEmpty());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.patinanetwork.codebloom.scheduled.leetcode;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
Expand All @@ -9,6 +10,7 @@

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
Expand Down Expand Up @@ -46,7 +48,7 @@ void setup() {

when(backgroundTaskRepository.getMostRecentlyCompletedBackgroundTaskByTaskEnum(
BackgroundTaskEnum.LEETCODE_QUESTION_BANK))
.thenReturn(lastSync);
.thenReturn(Optional.of(lastSync));
}

@Test
Expand All @@ -69,17 +71,31 @@ void testSyncCreatesAndDeletesQuestions() {
.acceptanceRate(33.0f)
.build();

when(leetcodeClient.getAllProblems()).thenReturn(List.of(q1, q2));
LeetcodeQuestion q3 = LeetcodeQuestion.builder()
.titleSlug("climbing-stairs")
.questionTitle("Climbing Stairs")
.questionId(3)
.difficulty("Hard")
.link("l3")
.acceptanceRate(12.5f)
.build();

when(leetcodeClient.getAllProblems()).thenReturn(List.of(q1, q2, q3));

QuestionBank existing =
QuestionBank existing1 =
QuestionBank.builder().id("id-existing").questionSlug("two-sum").build();

QuestionBank existing2 = QuestionBank.builder()
.id("id-existing-2")
.questionSlug("climbing-stairs")
.build();

QuestionBank outdated = QuestionBank.builder()
.id("id-outdated")
.questionSlug("old-question")
.build();

when(questionBankRepository.getAllQuestions()).thenReturn(List.of(existing, outdated));
when(questionBankRepository.getAllQuestions()).thenReturn(List.of(existing1, existing2, outdated));

job.updateQuestionBank();

Expand All @@ -88,13 +104,41 @@ void testSyncCreatesAndDeletesQuestions() {
assertEquals("add-two-numbers", createCaptor.getValue().getQuestionSlug());

verify(questionBankRepository, times(1)).deleteQuestionById("id-outdated");

ArgumentCaptor<BackgroundTask> taskCaptor = ArgumentCaptor.forClass(BackgroundTask.class);
verify(backgroundTaskRepository, times(1)).createBackgroundTask(taskCaptor.capture());
assertEquals(
BackgroundTaskEnum.LEETCODE_QUESTION_BANK, taskCaptor.getValue().getTask());
}

@Test
void testUpdateQuestionBankInvalidDifficulty() {
LeetcodeQuestion q1 = LeetcodeQuestion.builder()
.titleSlug("climbing-stairs")
.questionTitle("Climbing Stairs")
.questionId(1)
.difficulty("Very Difficult")
.link("l1")
.acceptanceRate(50.0f)
.build();

when(leetcodeClient.getAllProblems()).thenReturn(List.of(q1));
QuestionBank existing = QuestionBank.builder()
.id("id-existing")
.questionSlug("climbing-stairs")
.build();
QuestionBank outdated = QuestionBank.builder()
.id("id-outdated")
.questionSlug("old-question")
.build();
when(questionBankRepository.getAllQuestions()).thenReturn(List.of(existing, outdated));
assertThrows(
IllegalArgumentException.class,
() -> {
job.updateQuestionBank();
},
"Updating with invalid leetcode question difficulty should throw exception");
}

@Test
void testInit() {
when(env.isDev()).thenReturn(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ void congregateUserMetricsCreatesSnapshotsForCurrentLeaderboard() throws Leaderb
.completedAt(OffsetDateTime.now().minusDays(2))
.build();
when(backgroundTaskRepository.getMostRecentlyCompletedBackgroundTaskByTaskEnum(BackgroundTaskEnum.USER_METRICS))
.thenReturn(lastSync);
.thenReturn(Optional.of(lastSync));

when(leaderboardRepository.getRecentLeaderboardMetadata())
.thenReturn(Optional.of(Leaderboard.builder()
Expand Down Expand Up @@ -97,7 +97,7 @@ void congregateUserMetricsSkipsWhenTodayEstSnapshotAlreadyExists() throws Leader
.completedAt(completedAfterTodayEstMidnight)
.build();
when(backgroundTaskRepository.getMostRecentlyCompletedBackgroundTaskByTaskEnum(BackgroundTaskEnum.USER_METRICS))
.thenReturn(lastSync);
.thenReturn(Optional.of(lastSync));

service.congregateUserMetrics();

Expand Down
Loading