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
32 changes: 24 additions & 8 deletions apps/server/src/handler/analysis/analysisConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,19 +263,35 @@ const teamLowerBound = 3300; // Total 3468 as of 2024 season
const swrConstant = 300;
const ttlConstant = 200;

// Caching this for later
const allTeamNumbers = (async () => {
return (await prismaClient.team.findMany()).map((team) => team.number);
})();
const allTournaments = (async () => {
// Keep the catalog snapshots process-local, but do not query PostgreSQL at
// import time or initiate a query until a caller actually needs the data.
function lazyCatalog<T>(load: () => Promise<T[]>): () => Promise<T[]> {
let snapshot: Promise<T[]> | undefined;

return () => {
snapshot ??= load().catch((error) => {
snapshot = undefined;
throw error;
});
return snapshot;
};
}

const getAllTeamNumbers = lazyCatalog(async () => {
return (await prismaClient.team.findMany({ select: { number: true } })).map(
(team) => team.number,
);
});
const getAllTournaments = lazyCatalog(async () => {
return (
await prismaClient.tournament.findMany({
select: { key: true },
orderBy: [
{ date: "asc" }, // Most recent last
],
})
).map((tnmt) => tnmt.key);
})();
});

const multiplerBaseAnalysis = 4;
export {
Expand All @@ -300,8 +316,8 @@ export {
swrConstant,
ttlConstant,
metricsToNumber,
allTeamNumbers,
allTournaments,
getAllTeamNumbers,
getAllTournaments,
breakdownPos,
breakdownNeg,
breakdownToEnum,
Expand Down
6 changes: 5 additions & 1 deletion apps/server/src/handler/analysis/analysisFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
createKey: (
params: z.infer<T>,
) => Promise<CreateKeyResult> | CreateKeyResult;
loadTeamDependencies?: () => Promise<number[]>;
}
| {
shouldCache: false;
Expand Down Expand Up @@ -117,17 +118,20 @@
if (!cacheRow) {
const result = await config.calculateAnalysis(passedArgs, context);
const rounded = roundAllNumbers(result);
const dependencies = config.loadTeamDependencies
? await config.loadTeamDependencies()
: (teamDependencies ?? []);

await kv.set(key, JSON.stringify(rounded));
try {
await prismaClient.cachedAnalysis.create({
data: {
key,
teamDependencies: teamDependencies ?? [],
teamDependencies: dependencies,
tournamentDependencies: tournamentDependencies ?? [],
},
});
} catch (e: any) {

Check warning on line 134 in apps/server/src/handler/analysis/analysisFunction.ts

View workflow job for this annotation

GitHub Actions / Server unit and static checks

Unexpected any. Specify a different type
if (e?.code !== "P2002") throw e;
// Ignore duplicate key; another request already created the row
}
Expand Down
5 changes: 5 additions & 0 deletions apps/server/src/handler/analysis/analysisHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@
calculateAnalysis: (
params: AnalysisHandlerParams<T, U, V>,
ctx: AnalysisContext,
) => Promise<any>;

Check warning on line 45 in apps/server/src/handler/analysis/analysisHandler.ts

View workflow job for this annotation

GitHub Actions / Server unit and static checks

Unexpected any. Specify a different type
usesDataSource: boolean;
} & (
| {
shouldCache: true;
usesViewerTeam?: true;
createKey: (
params: AnalysisHandlerParams<T, U, V>,
) => Promise<CreateKeyResult> | CreateKeyResult;
Expand Down Expand Up @@ -110,6 +111,10 @@
);
}

if (args.usesViewerTeam) {
keyFragments.push(`viewer-team=${req.user.teamNumber ?? "none"}`);
}

const key = [
"analysis",
analysisCacheVersion,
Expand Down Expand Up @@ -149,7 +154,7 @@
tournamentDependencies: tournamentDeps ?? [],
},
});
} catch (e: any) {

Check warning on line 157 in apps/server/src/handler/analysis/analysisHandler.ts

View workflow job for this annotation

GitHub Actions / Server unit and static checks

Unexpected any. Specify a different type
if (e?.code !== "P2002") throw e;
// Ignore duplicate key; another request already created the row
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import prismaClient from "../../../prismaClient.js";
import {
accuracyToPercentageInterpolated,
accuracyToPercentage,
allTeamNumbers,
getAllTeamNumbers,
autoEnd,
endgameToPoints,
Metric,
Expand Down Expand Up @@ -74,10 +74,10 @@ const config = {
const metric = args.metric;
return {
key: ["averageAllTeamFast", String(metric)],
teamDependencies: await allTeamNumbers,
tournamentDependencies: [],
};
},
loadTeamDependencies: getAllTeamNumbers,
calculateAnalysis: async (
args: { metric: Metric },
ctx: { user: { teamSourceRule: unknown; tournamentSourceRule: unknown } },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
Metric,
metricToEvent,
minActionDuration,
allTournaments,
getAllTournaments,
accuracyToPercentage,
} from "../analysisConstants.js";
import { EndgameClimb, AutoClimb, Prisma, Event, $Enums } from "@lovat/db";
Expand Down Expand Up @@ -100,7 +100,7 @@ const config: AnalysisFunctionConfig<typeof argsSchema, z.ZodType> = {
},
});

const tournamentIndex = await allTournaments;
const tournamentIndex = await getAllTournaments();
const finalResults: Record<string, Record<string, number>> = {};

for (const metric of args.metrics) {
Expand Down
10 changes: 6 additions & 4 deletions apps/server/src/handler/analysis/teamLookUp/breakdownDetails.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { analysisReportsSql } from "../reportReliability.js";
import z from "zod";
import {
allTeamNumbers,
allTournaments,
getAllTeamNumbers,
getAllTournaments,
breakdownNeg,
breakdownPos,
dashboardToServer,
Expand All @@ -23,6 +23,8 @@ export const breakdownDetails = createAnalysisHandler({
},
usesDataSource: true,
shouldCache: true,
// Only the viewer's own team can see scout names.
usesViewerTeam: true,
createKey: async ({ params }) => {
return {
key: [
Expand Down Expand Up @@ -69,11 +71,11 @@ export const breakdownDetails = createAnalysisHandler({
queryStr,
dataSourceRuleToArray(
parseStoredSourceRule(z.number(), ctx.user.teamSourceRule),
await allTeamNumbers,
await getAllTeamNumbers(),
),
dataSourceRuleToArray(
parseStoredSourceRule(z.string(), ctx.user.tournamentSourceRule),
await allTournaments,
await getAllTournaments(),
),
);

Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/handler/analysis/teamLookUp/getNotes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export const getNotes = createAnalysisHandler({
},
usesDataSource: true,
shouldCache: true,
// Only the viewer's own team can see scout names.
usesViewerTeam: true,
createKey: async ({ params }) => {
return {
key: ["getNotes", params.team.toString()],
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/handler/manager/settings/addTeamSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Response } from "express";
import prismaClient from "../../../prismaClient.js";
import z from "zod";
import { AuthenticatedRequest } from "../../../lib/middleware/requireAuth.js";
import { allTeamNumbers } from "../../analysis/analysisConstants.js";
import { getAllTeamNumbers } from "../../analysis/analysisConstants.js";
import { arrayToRule } from "../../../lib/migrateDataSources.js";

export const addTeamSource = async (
Expand Down Expand Up @@ -58,7 +58,7 @@ export const addTeamSource = async (
data: {
teamSourceRule: arrayToRule<number>(
params.data.teamSource,
await allTeamNumbers,
await getAllTeamNumbers(),
),
},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Response } from "express";
import prismaClient from "../../../prismaClient.js";
import z from "zod";
import { AuthenticatedRequest } from "../../../lib/middleware/requireAuth.js";
import { allTournaments } from "../../analysis/analysisConstants.js";
import { getAllTournaments } from "../../analysis/analysisConstants.js";
import { arrayToRule } from "../../../lib/migrateDataSources.js";

export const addTournamentSource = async (
Expand Down Expand Up @@ -31,7 +31,7 @@ export const addTournamentSource = async (
data: {
tournamentSourceRule: arrayToRule<string>(
params.data.tournamentSource,
await allTournaments,
await getAllTournaments(),
),
},
});
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/handler/manager/settings/getTeamSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
dataSourceRuleToArray,
} from "../../analysis/dataSourceRule.js";
import z from "zod";
import { allTeamNumbers } from "../../analysis/analysisConstants.js";
import { getAllTeamNumbers } from "../../analysis/analysisConstants.js";

export const getTeamSource = async (
req: AuthenticatedRequest,
Expand Down Expand Up @@ -34,7 +34,7 @@ export const getTeamSource = async (
} else {
res
.status(200)
.send(dataSourceRuleToArray(teamSourceRule, await allTeamNumbers));
.send(dataSourceRuleToArray(teamSourceRule, await getAllTeamNumbers()));
}
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
parseStoredSourceRule,
dataSourceRuleToArray,
} from "../../analysis/dataSourceRule.js";
import { allTournaments } from "../../analysis/analysisConstants.js";
import { getAllTournaments } from "../../analysis/analysisConstants.js";
import z from "zod";

export const getTournamentSource = async (
Expand All @@ -17,7 +17,7 @@ export const getTournamentSource = async (
.send(
dataSourceRuleToArray(
parseStoredSourceRule(z.string(), req.user.tournamentSourceRule),
await allTournaments,
await getAllTournaments(),
),
);
}
Expand Down
11 changes: 7 additions & 4 deletions apps/server/src/handler/manager/settings/updateSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { AuthenticatedRequest } from "../../../lib/middleware/requireAuth.js";

import { arrayToRule } from "../../../lib/migrateDataSources.js";
import {
allTeamNumbers,
allTournaments,
getAllTeamNumbers,
getAllTournaments,
} from "../../analysis/analysisConstants.js";

export const updateSettings = async (
Expand All @@ -33,10 +33,13 @@ export const updateSettings = async (
id: req.user.id,
},
data: {
teamSourceRule: arrayToRule(params.teamSource, await allTeamNumbers),
teamSourceRule: arrayToRule(
params.teamSource,
await getAllTeamNumbers(),
),
tournamentSourceRule: arrayToRule(
params.tournamentSource,
await allTournaments,
await getAllTournaments(),
),
},
});
Expand Down
75 changes: 75 additions & 0 deletions apps/server/test/analysisCatalog.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { expect, it, vi } from "vitest";
import { testUser } from "./helpers/handlerHarness.js";

const db = vi.hoisted(() => ({
team: { findMany: vi.fn() },
tournament: { findMany: vi.fn() },
cachedAnalysis: { findUnique: vi.fn(), create: vi.fn() },
$queryRawUnsafe: vi.fn(),
get: vi.fn(),
set: vi.fn(),
}));

vi.mock("../src/prismaClient.js", () => ({ default: db }));
vi.mock("../src/redisClient.js", () => ({
kv: { get: db.get, set: db.set },
}));

import {
getAllTeamNumbers,
getAllTournaments,
Metric,
} from "../src/handler/analysis/analysisConstants.js";
import { averageAllTeamFast } from "../src/handler/analysis/coreAnalysis/averageAllTeamFast.js";

it("only checks the registration on a warm population metric cache hit", async () => {
expect(db.team.findMany).not.toHaveBeenCalled();
expect(db.tournament.findMany).not.toHaveBeenCalled();
db.get.mockResolvedValueOnce("1.25");
db.cachedAnalysis.findUnique.mockResolvedValueOnce({ key: "registered" });

expect(
await averageAllTeamFast(testUser, { metric: Metric.driverAbility }),
).toBe(1.25);

expect(db.cachedAnalysis.findUnique).toHaveBeenCalledOnce();
expect(db.team.findMany).not.toHaveBeenCalled();
expect(db.tournament.findMany).not.toHaveBeenCalled();
expect(db.$queryRawUnsafe).not.toHaveBeenCalled();
expect(db.cachedAnalysis.create).not.toHaveBeenCalled();
});

it("loads team dependencies only when registering a computed result and retries catalog failures", async () => {
db.get.mockResolvedValue(null);
db.$queryRawUnsafe.mockResolvedValue([]);
db.team.findMany
.mockRejectedValueOnce(new Error("catalog temporarily unavailable"))
.mockResolvedValueOnce([{ number: 254 }, { number: 8033 }]);

await expect(getAllTeamNumbers()).rejects.toThrow(
"catalog temporarily unavailable",
);
expect(
await averageAllTeamFast(testUser, { metric: Metric.driverAbility }),
).toBe(0);
expect(db.cachedAnalysis.create).toHaveBeenCalledExactlyOnceWith({
data: {
key: expect.stringContaining("averageAllTeamFast"),
teamDependencies: [254, 8033],
tournamentDependencies: [],
},
});
expect(await getAllTeamNumbers()).toEqual([254, 8033]);
expect(db.team.findMany).toHaveBeenCalledTimes(2);
});

it("loads and shares the ordered tournament catalog on demand", async () => {
db.tournament.findMany.mockResolvedValue([{ key: "2026test" }]);
const first = getAllTournaments();
expect(getAllTournaments()).toBe(first);
expect(await first).toEqual(["2026test"]);
expect(db.tournament.findMany).toHaveBeenCalledExactlyOnceWith({
select: { key: true },
orderBy: [{ date: "asc" }],
});
});
2 changes: 2 additions & 0 deletions apps/server/test/analysisEdgeCases.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ const rows = () => [
beforeEach(() => {
vi.resetAllMocks();
db.get.mockResolvedValue(null);
db.team.findMany.mockResolvedValue([]);
db.tournament.findMany.mockResolvedValue([]);
db.teamMatchData.findMany.mockResolvedValue(rows());
db.scoutReport.findUniqueOrThrow.mockResolvedValue(report);
db.$queryRawUnsafe.mockResolvedValue([]);
Expand Down
4 changes: 2 additions & 2 deletions apps/server/test/settings.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ const db = vi.hoisted(() => ({
const send = vi.hoisted(() => vi.fn());
vi.mock("../src/prismaClient.js", () => ({ default: db }));
vi.mock("../src/handler/analysis/analysisConstants.js", () => ({
allTeamNumbers: Promise.resolve([8033, 254, 1678, 971]),
allTournaments: Promise.resolve(["a", "b", "c", "d"]),
getAllTeamNumbers: async () => [8033, 254, 1678, 971],
getAllTournaments: async () => ["a", "b", "c", "d"],
}));
vi.mock("../src/handler/manager/onboarding/resendEmail.js", () => ({
sendVerificationEmail: send,
Expand Down
Loading
Loading