Skip to content

Commit

Permalink
chore(memorystore-valkey-leaderboard): lint
Browse files Browse the repository at this point in the history
  • Loading branch information
cabljac committed Feb 5, 2025
1 parent dd5e8cc commit 240804e
Show file tree
Hide file tree
Showing 15 changed files with 910 additions and 901 deletions.
264 changes: 132 additions & 132 deletions memorystore/valkey/leaderboard/app/src/main/java/app/DataController.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,155 +16,155 @@

package app;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.resps.Tuple;
import java.util.ArrayList;
import java.util.List;

@Controller
public class DataController {

/** Repository for persisting leaderboard entries. */
private final LeaderboardRepository leaderboardRepository;

/** Redis client for caching leaderboard data. */
private final Jedis jedis;

/**
* Constructs a new DataController.
*
* @param redisClient Redis client for caching
* @param repository Repository for persistence
*/
public DataController(final Jedis redisClient,
final LeaderboardRepository repository) {
this.leaderboardRepository = repository;
this.jedis = redisClient;
/** Repository for persisting leaderboard entries. */
private final LeaderboardRepository leaderboardRepository;

/** Redis client for caching leaderboard data. */
private final Jedis jedis;

/**
* Constructs a new DataController.
*
* @param redisClient Redis client for caching
* @param repository Repository for persistence
*/
public DataController(final Jedis redisClient,
final LeaderboardRepository repository) {
this.leaderboardRepository = repository;
this.jedis = redisClient;
}

/**
* Get the leaderboard entries starting from the given position.
*
* @param position The starting position of the entries to search.
* @param orderBy The order of the entries.
* @param pageSize The number of entries to return.
* @param username The username to check the rank of.
* @return The leaderboard entries.
*/
public LeaderboardResponse getLeaderboard(
final long position,
final OrderByType orderBy,
final long pageSize,
final String username) {
String cacheKey = Global.LEADERBOARD_ENTRIES_KEY;
long maxPosition = position + pageSize - 1;

// Initialize the cache if it's empty
boolean cacheUpdated = this.initializeCache();

// Set the cache status for the front end
int cacheStatus = cacheUpdated
? FromCacheType.FROM_DB.getValue()
: FromCacheType.FULL_CACHE.getValue();

// If we have a username, search for the user's rank
if (username != null) {
Long userRank = jedis.zrevrank(cacheKey, username);
if (userRank != null) {
long pos = userRank;
long maxPos = userRank + pageSize - 1;

return new LeaderboardResponse(
getEntries(cacheKey, pos, maxPos, true),
cacheStatus);
}
}

/**
* Get the leaderboard entries starting from the given position.
*
* @param position The starting position of the entries to search.
* @param orderBy The order of the entries.
* @param pageSize The number of entries to return.
* @param username The username to check the rank of.
* @return The leaderboard entries.
*/
public LeaderboardResponse getLeaderboard(
final long position,
final OrderByType orderBy,
final long pageSize,
final String username) {
String cacheKey = Global.LEADERBOARD_ENTRIES_KEY;
long maxPosition = position + pageSize - 1;

// Initialize the cache if it's empty
boolean cacheUpdated = this.initializeCache();

// Set the cache status for the front end
int cacheStatus = cacheUpdated
? FromCacheType.FROM_DB.getValue()
: FromCacheType.FULL_CACHE.getValue();

// If we have a username, search for the user's rank
if (username != null) {
Long userRank = jedis.zrevrank(cacheKey, username);
if (userRank != null) {
long pos = userRank;
long maxPos = userRank + pageSize - 1;

return new LeaderboardResponse(
getEntries(cacheKey, pos, maxPos, true),
cacheStatus);
}
}

// Get the leaderboard entries depending on the order
List<LeaderboardEntry> leaderboardList = getEntries(
cacheKey, position, maxPosition,
orderBy == OrderByType.HIGH_TO_LOW);

return new LeaderboardResponse(leaderboardList, cacheStatus);
// Get the leaderboard entries depending on the order
List<LeaderboardEntry> leaderboardList = getEntries(
cacheKey, position, maxPosition,
orderBy == OrderByType.HIGH_TO_LOW);

return new LeaderboardResponse(leaderboardList, cacheStatus);
}

private List<LeaderboardEntry> getEntries(
final String cacheKey,
final long position,
final long maxPosition,
final boolean isDescending) {
// Define an object
List<Tuple> entries = new ArrayList<>();

// Use zrevrangeWithScores to get the entries in descending order
if (isDescending) {
entries = new ArrayList<>(
jedis.zrevrangeWithScores(cacheKey, position, maxPosition));
}

private List<LeaderboardEntry> getEntries(
final String cacheKey,
final long position,
final long maxPosition,
final boolean isDescending) {
// Define an object
List<Tuple> entries = new ArrayList<>();

// Use zrevrangeWithScores to get the entries in descending order
if (isDescending) {
entries = new ArrayList<>(
jedis.zrevrangeWithScores(cacheKey, position, maxPosition));
}

// If zrangeWithScores is used, the entries are in ascending order
if (!isDescending) {
entries = new ArrayList<>(
jedis.zrangeWithScores(cacheKey, position, maxPosition));
}

List<LeaderboardEntry> newEntries = new ArrayList<>();
for (int i = 0; i < entries.size(); i++) {
Tuple e = entries.get(i);

// Calculate overall position
long overallPosition = position + i;
if (!isDescending) {
overallPosition = jedis.zcard(cacheKey) - overallPosition - 1;
}

newEntries.add(
new LeaderboardEntry(
e.getElement(), e.getScore(), overallPosition
)
);
}

return newEntries;
// If zrangeWithScores is used, the entries are in ascending order
if (!isDescending) {
entries = new ArrayList<>(
jedis.zrangeWithScores(cacheKey, position, maxPosition));
}

private boolean initializeCache() {
if (this.jedis.zcard(Global.LEADERBOARD_ENTRIES_KEY) > 0) {
return false;
}
List<LeaderboardEntry> newEntries = new ArrayList<>();
for (int i = 0; i < entries.size(); i++) {
Tuple e = entries.get(i);

// Calculate overall position
long overallPosition = position + i;
if (!isDescending) {
overallPosition = jedis.zcard(cacheKey) - overallPosition - 1;
}

newEntries.add(
new LeaderboardEntry(
e.getElement(), e.getScore(), overallPosition
)
);
}

return newEntries;
}

List<LeaderboardEntry> entries = this.leaderboardRepository
.getEntries();
private boolean initializeCache() {
if (this.jedis.zcard(Global.LEADERBOARD_ENTRIES_KEY) > 0) {
return false;
}

if (!entries.isEmpty()) {
for (LeaderboardEntry entry : entries) {
this.jedis.zadd(
Global.LEADERBOARD_ENTRIES_KEY,
entry.getScore(),
entry.getUsername());
}
}
List<LeaderboardEntry> entries = this.leaderboardRepository
.getEntries();

return true;
if (!entries.isEmpty()) {
for (LeaderboardEntry entry : entries) {
this.jedis.zadd(
Global.LEADERBOARD_ENTRIES_KEY,
entry.getScore(),
entry.getUsername());
}
}

/**
* Creates or updates a leaderboard entry with the given username and score.
* Only updates the entry if the new score is higher than the current score.
*
* @param username The username of the entry
* @param score The score to set
*/
public void createOrUpdate(final String username, final Double score) {
// See if score is higher than the current score
Double currentScore = this.jedis.zscore(
Global.LEADERBOARD_ENTRIES_KEY, username);
if (currentScore != null && currentScore >= score) {
return;
}

this.leaderboardRepository.update(username, score);
this.jedis.zadd(Global.LEADERBOARD_ENTRIES_KEY, score, username);
return true;
}

/**
* Creates or updates a leaderboard entry with the given username and score.
* Only updates the entry if the new score is higher than the current score.
*
* @param username The username of the entry
* @param score The score to set
*/
public void createOrUpdate(final String username, final Double score) {
// See if score is higher than the current score
Double currentScore = this.jedis.zscore(
Global.LEADERBOARD_ENTRIES_KEY, username);
if (currentScore != null && currentScore >= score) {
return;
}

this.leaderboardRepository.update(username, score);
this.jedis.zadd(Global.LEADERBOARD_ENTRIES_KEY, score, username);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,29 @@

/** Cache state indicator for leaderboard data. */
public enum FromCacheType {
/** Data freshly loaded from database. */
FROM_DB(0),
/** Data served from cache. */
FULL_CACHE(1);
/** Data freshly loaded from database. */
FROM_DB(0),
/** Data served from cache. */
FULL_CACHE(1);

/** Numeric value for the cache state. */
private final int value;
/** Numeric value for the cache state. */
private final int value;

/**
* Constructor.
*
* @param valueParam Numeric value for this state
*/
FromCacheType(final int valueParam) {
this.value = valueParam;
}
/**
* Constructor.
*
* @param valueParam Numeric value for this state
*/
FromCacheType(final int valueParam) {
this.value = valueParam;
}

/**
* Gets the numeric value.
*
* @return The value for this state
*/
public int getValue() {
return value;
}
/**
* Gets the numeric value.
*
* @return The value for this state
*/
public int getValue() {
return value;
}
}
12 changes: 6 additions & 6 deletions memorystore/valkey/leaderboard/app/src/main/java/app/Global.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@

public final class Global {

/** Private constructor to prevent instantiation. */
private Global() {
throw new UnsupportedOperationException();
}
/** Private constructor to prevent instantiation. */
private Global() {
throw new UnsupportedOperationException();
}

/** Key for accessing leaderboard entries in responses. */
public static final String LEADERBOARD_ENTRIES_KEY = "entries";
/** Key for accessing leaderboard entries in responses. */
public static final String LEADERBOARD_ENTRIES_KEY = "entries";
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@
@Controller
public class HomeController {

/**
* Handles requests to the home page.
*
* @param model view model
* @return view name for home page
*/
@GetMapping("/")
public String home(final Model model) {
return "index";
}
/**
* Handles requests to the home page.
*
* @param model view model
* @return view name for home page
*/
@GetMapping("/")
public String home(final Model model) {
return "index";
}
}
Loading

0 comments on commit 240804e

Please sign in to comment.