Skip to content
Open
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
Binary file modified .DS_Store
Binary file not shown.
124 changes: 91 additions & 33 deletions backend/src/analytics/analytics.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@ interface UserPuzzleEngagement {
lastSolved?: Date;
}

export interface PaginatedUserPuzzleHistory {
items: Record<string, UserPuzzleEngagement>;
total: number;
page: number;
limit: number;
}

const DEFAULT_PAGE = 1;
const DEFAULT_LIMIT = 20;
const MAX_LIMIT = 100;

const PUZZLE_KEY = (puzzleId: string) => `analytics:puzzle:${puzzleId}`;
const USER_PUZZLE_KEY = (userId: string, puzzleId: string) =>
`analytics:user:${userId}:puzzle:${puzzleId}`;
Expand Down Expand Up @@ -121,11 +132,7 @@ export class AnalyticsService {
* fans out the write fire-and-forget so a configured Redis still
* receives solves from non-awaiting callers.
*/
recordPuzzleSolve(
userId: string,
puzzleId: string,
solveTime: number,
): void {
recordPuzzleSolve(userId: string, puzzleId: string, solveTime: number): void {
this.logger.log(
`Recording solve: User ${userId}, Puzzle ${puzzleId}, Time ${solveTime}`,
);
Expand Down Expand Up @@ -232,7 +239,7 @@ export class AnalyticsService {
*/
getMostSolvedPuzzles(
limit?: number,
): Promise<Array<{ puzzleId: string; solveCount: number }>> {
): Array<{ puzzleId: string; solveCount: number }> {
this.logger.log('Fetching most solved puzzles...');
const sortedPuzzles = Array.from(this.puzzleStats.entries())
.map(([puzzleId, stats]) => ({
Expand Down Expand Up @@ -276,33 +283,10 @@ export class AnalyticsService {
}
}

getAverageSolveTime(puzzleId: string): number {
this.logger.log(`Fetching average solve time for puzzle ${puzzleId}...`);
const stats = this.puzzleStats.get(puzzleId);
if (stats && stats.solveCount > 0) {
return stats.totalSolveTime / stats.solveCount;
}
return 0;
}

async getAverageSolveTimeAsync(puzzleId: string): Promise<number> {
if (!this.usingRedis || !this.redis) {
return this.getAverageSolveTime(puzzleId);
}
try {
const raw = await this.redis.hgetall(PUZZLE_KEY(puzzleId));
const solveCount = Number(raw?.solveCount ?? 0);
const totalSolveTime = Number(raw?.totalSolveTime ?? 0);
return solveCount > 0 ? totalSolveTime / solveCount : 0;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.logger.warn(
`Redis read failed for analytics (falling back to in-memory): ${message}`,
);
return this.getAverageSolveTime(puzzleId);
}
}

/**
* Synchronous read of a single user's full history from the in-memory
* mirror only. Kept for existing callers; not paginated.
*/
getUserPuzzleStats(userId: string): Map<string, UserPuzzleEngagement> {
this.logger.log(`Fetching puzzle history for user ${userId}...`);
return (
Expand All @@ -311,6 +295,10 @@ export class AnalyticsService {
);
}

/**
* Async read of a single user's full history. Redis-authoritative when
* configured, falling back to the in-memory mirror on failure.
*/
async getUserPuzzleStatsAsync(
userId: string,
): Promise<Map<string, UserPuzzleEngagement>> {
Expand All @@ -337,6 +325,76 @@ export class AnalyticsService {
}
}

/**
* Paginated view of a user's puzzle history, sorted by most recently
* solved first. Built on top of `getUserPuzzleStatsAsync` so it shares
* the same Redis-first / in-memory-fallback semantics rather than
* duplicating the read path.
*
* `page` is 1-indexed. `limit` is clamped to [1, MAX_LIMIT] to prevent
* a caller from requesting the entire history in one shot.
*/
async getUserPuzzleHistoryPaginated(
userId: string,
page: number = DEFAULT_PAGE,
limit: number = DEFAULT_LIMIT,
): Promise<PaginatedUserPuzzleHistory> {
const safePage =
Number.isFinite(page) && page > 0 ? Math.floor(page) : DEFAULT_PAGE;
const safeLimit =
Number.isFinite(limit) && limit > 0
? Math.min(Math.floor(limit), MAX_LIMIT)
: DEFAULT_LIMIT;

const fullHistory = await this.getUserPuzzleStatsAsync(userId);

const sortedEntries = Array.from(fullHistory.entries()).sort(
([, a], [, b]) => {
const aTime = a.lastSolved ? a.lastSolved.getTime() : 0;
const bTime = b.lastSolved ? b.lastSolved.getTime() : 0;
return bTime - aTime; // most recent first
},
);

const total = sortedEntries.length;
const start = (safePage - 1) * safeLimit;
const pageEntries = sortedEntries.slice(start, start + safeLimit);

const items: Record<string, UserPuzzleEngagement> = {};
for (const [puzzleId, stats] of pageEntries) {
items[puzzleId] = stats;
}

return { items, total, page: safePage, limit: safeLimit };
}

getAverageSolveTime(puzzleId: string): number {
this.logger.log(`Fetching average solve time for puzzle ${puzzleId}...`);
const stats = this.puzzleStats.get(puzzleId);
if (stats && stats.solveCount > 0) {
return stats.totalSolveTime / stats.solveCount;
}
return 0;
}

async getAverageSolveTimeAsync(puzzleId: string): Promise<number> {
if (!this.usingRedis || !this.redis) {
return this.getAverageSolveTime(puzzleId);
}
try {
const raw = await this.redis.hgetall(PUZZLE_KEY(puzzleId));
const solveCount = Number(raw?.solveCount ?? 0);
const totalSolveTime = Number(raw?.totalSolveTime ?? 0);
return solveCount > 0 ? totalSolveTime / solveCount : 0;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.logger.warn(
`Redis read failed for analytics (falling back to in-memory): ${message}`,
);
return this.getAverageSolveTime(puzzleId);
}
}

seedData(): void {
this.logger.log('Seeding initial analytics data...');
// Seed directly to memory to keep the test/dev hot path deterministic;
Expand Down
Loading