feat(minigames): record completed runs in the period ledger
Phase 1 of the minigame periods feature: - Shared server-side recorder (lib/minigames/periods/record.ts) writes one minigame-entries row per completed scored run, lazily creating the anchored period it belongs to (unique startDate makes it race-safe). Failures are swallowed so a ledger hiccup can never break a submission. - Pure anchored-period math (lib/minigames/periods/derive.ts). - Wire the recorder into all five Core submit actions after their profile update: flappy (passes > 0), EOD (win), radio (>= 1 correct message), aim trainer and OPORD (any completed round). - Server-validated durations for every game: flappy and radio watch now report durationMs (with bounds), aim trainer reports its run duration (clamped to the 30s course), EOD derives it from seconds, OPORD from timeMs. - Integration test covering derivation, lazy period creation, pre-anchor null period and the never-throw guarantee.
This commit is contained in:
parent
d4d121b5a7
commit
997ae39a59
11 changed files with 528 additions and 6 deletions
|
|
@ -6,6 +6,7 @@ import { emitGameEvent } from "@/utils/event-log/emit";
|
||||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||||
import { broadcastToUser } from "@/lib/realtime/bus";
|
import { broadcastToUser } from "@/lib/realtime/bus";
|
||||||
import { chipsForXp } from "@/lib/minigames/chips";
|
import { chipsForXp } from "@/lib/minigames/chips";
|
||||||
|
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
|
||||||
|
|
||||||
interface ActionResult<T = undefined> {
|
interface ActionResult<T = undefined> {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
|
|
@ -230,6 +231,18 @@ export async function submitEodResult(input: {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (input.won) {
|
||||||
|
await recordMinigameEntry({
|
||||||
|
payload,
|
||||||
|
userId: Number(user.id),
|
||||||
|
game: "eod",
|
||||||
|
score,
|
||||||
|
durationMs: input.seconds * 1000,
|
||||||
|
mode: difficulty,
|
||||||
|
meta: { flags: input.flags, seconds: input.seconds },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import { emitGameEvent } from "@/utils/event-log/emit";
|
||||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||||
import { broadcastToUser } from "@/lib/realtime/bus";
|
import { broadcastToUser } from "@/lib/realtime/bus";
|
||||||
import { chipsForXp } from "@/lib/minigames/chips";
|
import { chipsForXp } from "@/lib/minigames/chips";
|
||||||
|
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
|
||||||
|
|
||||||
interface ActionResult<T = undefined> {
|
interface ActionResult<T = undefined> {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
|
|
@ -23,6 +24,8 @@ export interface FlappyStats {
|
||||||
|
|
||||||
const PASSES_PER_XP = 15;
|
const PASSES_PER_XP = 15;
|
||||||
const MAX_PASSES_PER_GAME = 5000;
|
const MAX_PASSES_PER_GAME = 5000;
|
||||||
|
// A maximal run (5000 passes) is a few hours at most; reject absurd durations.
|
||||||
|
const MAX_FLAPPY_DURATION_MS = 6 * 60 * 60 * 1000;
|
||||||
|
|
||||||
async function authenticate() {
|
async function authenticate() {
|
||||||
const payloadConfig = await config;
|
const payloadConfig = await config;
|
||||||
|
|
@ -43,6 +46,7 @@ async function authenticate() {
|
||||||
|
|
||||||
export async function submitFlappyScore(input: {
|
export async function submitFlappyScore(input: {
|
||||||
passes: number;
|
passes: number;
|
||||||
|
durationMs: number;
|
||||||
}): Promise<ActionResult<FlappyStats>> {
|
}): Promise<ActionResult<FlappyStats>> {
|
||||||
try {
|
try {
|
||||||
const { payload, user } = await authenticate();
|
const { payload, user } = await authenticate();
|
||||||
|
|
@ -54,6 +58,14 @@ export async function submitFlappyScore(input: {
|
||||||
if (passes > MAX_PASSES_PER_GAME) {
|
if (passes > MAX_PASSES_PER_GAME) {
|
||||||
return { success: false, error: "Score too large." };
|
return { success: false, error: "Score too large." };
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
typeof input.durationMs !== "number" ||
|
||||||
|
!Number.isFinite(input.durationMs) ||
|
||||||
|
input.durationMs <= 0 ||
|
||||||
|
input.durationMs > MAX_FLAPPY_DURATION_MS
|
||||||
|
) {
|
||||||
|
return { success: false, error: "Invalid run duration." };
|
||||||
|
}
|
||||||
|
|
||||||
const profileRes = await payload.find({
|
const profileRes = await payload.find({
|
||||||
collection: "profiles",
|
collection: "profiles",
|
||||||
|
|
@ -121,6 +133,14 @@ export async function submitFlappyScore(input: {
|
||||||
targetId: user.id as number,
|
targetId: user.id as number,
|
||||||
data: { passes, xpEarned: runXp, bestScore, totalPasses, flappyXp },
|
data: { passes, xpEarned: runXp, bestScore, totalPasses, flappyXp },
|
||||||
});
|
});
|
||||||
|
await recordMinigameEntry({
|
||||||
|
payload,
|
||||||
|
userId: Number(user.id),
|
||||||
|
game: "flappy",
|
||||||
|
score: passes,
|
||||||
|
durationMs: input.durationMs,
|
||||||
|
meta: { xpEarned: runXp },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,7 @@ import {
|
||||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||||
import { broadcastToUser } from "@/lib/realtime/bus";
|
import { broadcastToUser } from "@/lib/realtime/bus";
|
||||||
|
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
|
||||||
|
|
||||||
interface ActionResult<T = undefined> {
|
interface ActionResult<T = undefined> {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
|
|
@ -214,6 +215,17 @@ export async function submitOpordRecallResult(
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await recordMinigameEntry({
|
||||||
|
payload,
|
||||||
|
userId: Number(user.id),
|
||||||
|
game: "opord",
|
||||||
|
score,
|
||||||
|
accuracy,
|
||||||
|
durationMs: Math.round(timeMs),
|
||||||
|
mode: input.difficulty,
|
||||||
|
meta: { correct, total: tier.questionCount },
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
|
|
|
||||||
|
|
@ -6,11 +6,13 @@ import { emitGameEvent } from "@/utils/event-log/emit";
|
||||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||||
import { broadcastToUser } from "@/lib/realtime/bus";
|
import { broadcastToUser } from "@/lib/realtime/bus";
|
||||||
import { chipsForXp } from "@/lib/minigames/chips";
|
import { chipsForXp } from "@/lib/minigames/chips";
|
||||||
|
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
|
||||||
import {
|
import {
|
||||||
isAimTrainerDifficulty,
|
isAimTrainerDifficulty,
|
||||||
calculateAimTrainerAccuracy,
|
calculateAimTrainerAccuracy,
|
||||||
calculateAimTrainerScore,
|
calculateAimTrainerScore,
|
||||||
calculateAimTrainerXp,
|
calculateAimTrainerXp,
|
||||||
|
COURSE_DURATION_MS,
|
||||||
MAX_SHOTS_FIRED,
|
MAX_SHOTS_FIRED,
|
||||||
MAX_HITS,
|
MAX_HITS,
|
||||||
MAX_DESPAWNED_TARGETS,
|
MAX_DESPAWNED_TARGETS,
|
||||||
|
|
@ -45,8 +47,13 @@ export interface AimTrainerResultInput {
|
||||||
civilianHits: number;
|
civilianHits: number;
|
||||||
shotsFired: number;
|
shotsFired: number;
|
||||||
despawnedUnhitTargets: number;
|
despawnedUnhitTargets: number;
|
||||||
|
/** Wall-clock run duration reported by the client; the course is 30s long. */
|
||||||
|
durationMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Allow for a backgrounded tab throttling rAF past the nominal course length.
|
||||||
|
const AIM_DURATION_GRACE_MS = 60_000;
|
||||||
|
|
||||||
async function authenticate() {
|
async function authenticate() {
|
||||||
const payloadConfig = await config;
|
const payloadConfig = await config;
|
||||||
const payload = await getPayload({ config: payloadConfig });
|
const payload = await getPayload({ config: payloadConfig });
|
||||||
|
|
@ -106,6 +113,22 @@ export async function submitAimTrainerResult(
|
||||||
return { success: false, error: "Too many despawned targets." };
|
return { success: false, error: "Too many despawned targets." };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const reportedDuration = input.durationMs;
|
||||||
|
if (
|
||||||
|
reportedDuration != null &&
|
||||||
|
(!Number.isFinite(reportedDuration) ||
|
||||||
|
reportedDuration < 0 ||
|
||||||
|
reportedDuration > COURSE_DURATION_MS + AIM_DURATION_GRACE_MS)
|
||||||
|
) {
|
||||||
|
return { success: false, error: "Invalid result." };
|
||||||
|
}
|
||||||
|
const runDurationMs = Math.min(
|
||||||
|
typeof reportedDuration === "number" && reportedDuration > 0
|
||||||
|
? Math.round(reportedDuration)
|
||||||
|
: COURSE_DURATION_MS,
|
||||||
|
COURSE_DURATION_MS,
|
||||||
|
);
|
||||||
|
|
||||||
const profileRes = await payload.find({
|
const profileRes = await payload.find({
|
||||||
collection: "profiles",
|
collection: "profiles",
|
||||||
where: { user: { equals: user.id as number } },
|
where: { user: { equals: user.id as number } },
|
||||||
|
|
@ -231,6 +254,17 @@ export async function submitAimTrainerResult(
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await recordMinigameEntry({
|
||||||
|
payload,
|
||||||
|
userId: Number(user.id),
|
||||||
|
game: "qualification",
|
||||||
|
score,
|
||||||
|
accuracy,
|
||||||
|
durationMs: runDurationMs,
|
||||||
|
mode: input.difficulty,
|
||||||
|
meta: { civilianHits },
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
|
|
@ -247,8 +281,7 @@ export async function submitAimTrainerResult(
|
||||||
score,
|
score,
|
||||||
accuracy,
|
accuracy,
|
||||||
},
|
},
|
||||||
};
|
}; } catch (error) {
|
||||||
} catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : "Unknown error";
|
const message = error instanceof Error ? error.message : "Unknown error";
|
||||||
if (message === "Unauthorized") {
|
if (message === "Unauthorized") {
|
||||||
return { success: false, error: "You must be logged in." };
|
return { success: false, error: "You must be logged in." };
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import { emitGameEvent } from "@/utils/event-log/emit";
|
||||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||||
import { broadcastToUser } from "@/lib/realtime/bus";
|
import { broadcastToUser } from "@/lib/realtime/bus";
|
||||||
import { chipsForXp } from "@/lib/minigames/chips";
|
import { chipsForXp } from "@/lib/minigames/chips";
|
||||||
|
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
|
||||||
|
|
||||||
interface ActionResult<T = undefined> {
|
interface ActionResult<T = undefined> {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
|
|
@ -38,6 +39,9 @@ const SPRINT_MESSAGE_COUNT = 10;
|
||||||
const MAX_WATCH_MESSAGES = 30;
|
const MAX_WATCH_MESSAGES = 30;
|
||||||
const MAX_SCORE_PER_GAME = 5000;
|
const MAX_SCORE_PER_GAME = 5000;
|
||||||
const MAX_SPRINT_TIME_MS = 600_000;
|
const MAX_SPRINT_TIME_MS = 600_000;
|
||||||
|
// Watch rounds run against a 60s clock; allow generous grace for throttled tabs.
|
||||||
|
const MAX_WATCH_TIME_MS = 120_000;
|
||||||
|
const WATCH_DURATION_FALLBACK_MS = 60_000;
|
||||||
|
|
||||||
type RadioMode = "sprint" | "watch";
|
type RadioMode = "sprint" | "watch";
|
||||||
|
|
||||||
|
|
@ -112,6 +116,19 @@ export async function submitRadioResult(input: {
|
||||||
) {
|
) {
|
||||||
return { success: false, error: "Invalid result." };
|
return { success: false, error: "Invalid result." };
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
input.mode === "watch" &&
|
||||||
|
sprintTime != null &&
|
||||||
|
(typeof sprintTime !== "number" || !Number.isFinite(sprintTime) || sprintTime < 0 || sprintTime > MAX_WATCH_TIME_MS)
|
||||||
|
) {
|
||||||
|
return { success: false, error: "Invalid result." };
|
||||||
|
}
|
||||||
|
const runDurationMs =
|
||||||
|
input.mode === "sprint"
|
||||||
|
? Math.round(sprintTime as number)
|
||||||
|
: typeof sprintTime === "number" && Number.isFinite(sprintTime) && sprintTime > 0
|
||||||
|
? Math.round(sprintTime)
|
||||||
|
: WATCH_DURATION_FALLBACK_MS;
|
||||||
|
|
||||||
const profileRes = await payload.find({
|
const profileRes = await payload.find({
|
||||||
collection: "profiles",
|
collection: "profiles",
|
||||||
|
|
@ -253,6 +270,22 @@ export async function submitRadioResult(input: {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (input.correctMessages >= 1) {
|
||||||
|
await recordMinigameEntry({
|
||||||
|
payload,
|
||||||
|
userId: Number(user.id),
|
||||||
|
game: "radio",
|
||||||
|
score,
|
||||||
|
accuracy: input.accuracy,
|
||||||
|
durationMs: runDurationMs,
|
||||||
|
mode: input.mode,
|
||||||
|
meta: {
|
||||||
|
messageCount: input.messageCount,
|
||||||
|
correctMessages: input.correctMessages,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
|
|
|
||||||
|
|
@ -427,6 +427,7 @@ export function FlappyBird({
|
||||||
flockTimer: 480,
|
flockTimer: 480,
|
||||||
});
|
});
|
||||||
const submittingRef = useRef(false);
|
const submittingRef = useRef(false);
|
||||||
|
const runStartedAtRef = useRef(0);
|
||||||
const statsRef = useRef<FlappyStats>(serverStats);
|
const statsRef = useRef<FlappyStats>(serverStats);
|
||||||
|
|
||||||
const [phase, setPhase] = useState<Phase>("ready");
|
const [phase, setPhase] = useState<Phase>("ready");
|
||||||
|
|
@ -465,7 +466,7 @@ export function FlappyBird({
|
||||||
}, [setPhaseSafe]);
|
}, [setPhaseSafe]);
|
||||||
|
|
||||||
const handleGameOver = useCallback(
|
const handleGameOver = useCallback(
|
||||||
async (finalScore: number) => {
|
async (finalScore: number, durationMs: number) => {
|
||||||
if (submittingRef.current) return;
|
if (submittingRef.current) return;
|
||||||
if (expiredRef.current) {
|
if (expiredRef.current) {
|
||||||
setLastRun({
|
setLastRun({
|
||||||
|
|
@ -486,7 +487,7 @@ export function FlappyBird({
|
||||||
}
|
}
|
||||||
submittingRef.current = true;
|
submittingRef.current = true;
|
||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
const res = await submitFlappyScore({ passes: finalScore });
|
const res = await submitFlappyScore({ passes: finalScore, durationMs });
|
||||||
submittingRef.current = false;
|
submittingRef.current = false;
|
||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
if (res.success && res.data) {
|
if (res.success && res.data) {
|
||||||
|
|
@ -531,6 +532,7 @@ export function FlappyBird({
|
||||||
const g = gameRef.current;
|
const g = gameRef.current;
|
||||||
g.birdY = START_Y;
|
g.birdY = START_Y;
|
||||||
g.birdVy = FLAP_VY;
|
g.birdVy = FLAP_VY;
|
||||||
|
runStartedAtRef.current = performance.now();
|
||||||
setPhaseSafe("playing");
|
setPhaseSafe("playing");
|
||||||
playFlap();
|
playFlap();
|
||||||
} else if (p === "playing") {
|
} else if (p === "playing") {
|
||||||
|
|
@ -560,7 +562,10 @@ export function FlappyBird({
|
||||||
const g = gameRef.current;
|
const g = gameRef.current;
|
||||||
setPhaseSafe("over");
|
setPhaseSafe("over");
|
||||||
playHit();
|
playHit();
|
||||||
handleGameOverRef.current(g.score);
|
const startedAt = runStartedAtRef.current;
|
||||||
|
const durationMs =
|
||||||
|
startedAt > 0 ? Math.max(1, Math.round(performance.now() - startedAt)) : 1;
|
||||||
|
handleGameOverRef.current(g.score, durationMs);
|
||||||
};
|
};
|
||||||
|
|
||||||
const step = (now: number) => {
|
const step = (now: number) => {
|
||||||
|
|
|
||||||
|
|
@ -482,6 +482,7 @@ export function AimTrainerGame({
|
||||||
civilianHits: game.civilianHits,
|
civilianHits: game.civilianHits,
|
||||||
shotsFired: game.shotsFired,
|
shotsFired: game.shotsFired,
|
||||||
despawnedUnhitTargets: game.despawnedUnhitTargets,
|
despawnedUnhitTargets: game.despawnedUnhitTargets,
|
||||||
|
durationMs: Math.max(1, Math.round(performance.now() - game.startedAt)),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -391,7 +391,7 @@ export function RadioTraffic({
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const elapsedMs = resultMode === "sprint" ? performance.now() - roundStartedAtRef.current : undefined;
|
const elapsedMs = performance.now() - roundStartedAtRef.current;
|
||||||
void recordResult(finalResults, resultMode, elapsedMs, incorrectMessages);
|
void recordResult(finalResults, resultMode, elapsedMs, incorrectMessages);
|
||||||
},
|
},
|
||||||
[recordResult, setPhaseSafe],
|
[recordResult, setPhaseSafe],
|
||||||
|
|
|
||||||
84
src/lib/minigames/periods/derive.ts
Normal file
84
src/lib/minigames/periods/derive.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
/**
|
||||||
|
* Pure anchored-period math for minigame scoring periods.
|
||||||
|
*
|
||||||
|
* No Payload import: safe for the client and for unit tests. Periods are fixed
|
||||||
|
* `periodLengthDays`-long blocks anchored at the `minigame-rules.anchorDate`.
|
||||||
|
* Period `index` 0 starts exactly at the anchor. Instants before the anchor
|
||||||
|
* have no period (`null`).
|
||||||
|
*/
|
||||||
|
|
||||||
|
const DAY_MS = 86_400_000;
|
||||||
|
|
||||||
|
const MONTHS = [
|
||||||
|
"Jan",
|
||||||
|
"Feb",
|
||||||
|
"Mar",
|
||||||
|
"Apr",
|
||||||
|
"May",
|
||||||
|
"Jun",
|
||||||
|
"Jul",
|
||||||
|
"Aug",
|
||||||
|
"Sep",
|
||||||
|
"Oct",
|
||||||
|
"Nov",
|
||||||
|
"Dec",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export interface DerivedPeriod {
|
||||||
|
/** Zero-based period number; 0 is the first period at the anchor. */
|
||||||
|
index: number;
|
||||||
|
/** Inclusive UTC start instant. */
|
||||||
|
startDate: Date;
|
||||||
|
/** Exclusive UTC end instant (the instant the next period begins). */
|
||||||
|
endDate: Date;
|
||||||
|
/** Human label, e.g. "Oct 12 to Oct 25, 2026". */
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const utcDate = (ms: number): { month: number; day: number; year: number } => {
|
||||||
|
const d = new Date(ms);
|
||||||
|
return { month: d.getUTCMonth(), day: d.getUTCDate(), year: d.getUTCFullYear() };
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Label a period by its inclusive start and inclusive last day. */
|
||||||
|
export function formatPeriodLabel(startMs: number, endMs: number): string {
|
||||||
|
const start = utcDate(startMs);
|
||||||
|
// `endMs` is exclusive, so the last covered instant is endMs - 1ms.
|
||||||
|
const end = utcDate(endMs - 1);
|
||||||
|
const sameYear = start.year === end.year;
|
||||||
|
const startText = sameYear
|
||||||
|
? `${MONTHS[start.month]} ${start.day}`
|
||||||
|
: `${MONTHS[start.month]} ${start.day}, ${start.year}`;
|
||||||
|
return `${startText} to ${MONTHS[end.month]} ${end.day}, ${end.year}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derive the anchored period containing `instant`.
|
||||||
|
* Returns `null` for instants before the anchor or when inputs are unusable.
|
||||||
|
*/
|
||||||
|
export function derivePeriodForInstant(
|
||||||
|
anchor: Date,
|
||||||
|
periodLengthDays: number,
|
||||||
|
instant: Date,
|
||||||
|
): DerivedPeriod | null {
|
||||||
|
const anchorMs = anchor.getTime();
|
||||||
|
const instantMs = instant.getTime();
|
||||||
|
const lengthMs = periodLengthDays * DAY_MS;
|
||||||
|
if (!Number.isFinite(anchorMs) || !Number.isFinite(instantMs) || !(lengthMs > 0)) return null;
|
||||||
|
if (instantMs < anchorMs) return null;
|
||||||
|
|
||||||
|
const index = Math.floor((instantMs - anchorMs) / lengthMs);
|
||||||
|
const startMs = anchorMs + index * lengthMs;
|
||||||
|
const endMs = startMs + lengthMs;
|
||||||
|
return {
|
||||||
|
index,
|
||||||
|
startDate: new Date(startMs),
|
||||||
|
endDate: new Date(endMs),
|
||||||
|
label: formatPeriodLabel(startMs, endMs),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Exclusive end instant of the period with the given 0-based index. */
|
||||||
|
export function periodStartForIndex(anchor: Date, periodLengthDays: number, index: number): Date {
|
||||||
|
return new Date(anchor.getTime() + index * periodLengthDays * DAY_MS);
|
||||||
|
}
|
||||||
151
src/lib/minigames/periods/record.ts
Normal file
151
src/lib/minigames/periods/record.ts
Normal file
|
|
@ -0,0 +1,151 @@
|
||||||
|
import type { Payload } from "payload";
|
||||||
|
import { derivePeriodForInstant, periodStartForIndex } from "./derive";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Single write path for the `minigame-entries` append-only ledger.
|
||||||
|
*
|
||||||
|
* Called by the five Core minigame submit actions AFTER their profile update,
|
||||||
|
* so a completed, scored run is always recorded (and never allowed to break
|
||||||
|
* the game submission: every failure is swallowed and logged).
|
||||||
|
*
|
||||||
|
* The period is resolved lazily: the first entry in an anchored period creates
|
||||||
|
* that period (idempotently; a unique `startDate` guards concurrent writers),
|
||||||
|
* so the ledger has a period reference even before the period tick has ever
|
||||||
|
* run. Phase 2's close pipeline then closes it at its end boundary.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const DEFAULT_PERIOD_LENGTH_DAYS = 14;
|
||||||
|
|
||||||
|
export interface RecordMinigameEntryInput {
|
||||||
|
payload: Payload;
|
||||||
|
userId: number;
|
||||||
|
/** Registry key (minigames.key), e.g. "flappy". */
|
||||||
|
game: string;
|
||||||
|
score: number;
|
||||||
|
durationMs: number;
|
||||||
|
accuracy?: number | null;
|
||||||
|
mode?: string | null;
|
||||||
|
meta?: Record<string, unknown> | null;
|
||||||
|
/** Injectable clock, for tests. */
|
||||||
|
now?: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ResolvedRules {
|
||||||
|
enabled: boolean;
|
||||||
|
anchorDate: Date | null;
|
||||||
|
periodLengthDays: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolveRules = async (payload: Payload): Promise<ResolvedRules> => {
|
||||||
|
try {
|
||||||
|
const rules = await payload.findGlobal({
|
||||||
|
slug: "minigame-rules",
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
const anchorRaw = rules?.anchorDate;
|
||||||
|
const anchorDate = anchorRaw ? new Date(anchorRaw) : null;
|
||||||
|
const periodLengthDays =
|
||||||
|
typeof rules?.periodLengthDays === "number" && rules.periodLengthDays > 0
|
||||||
|
? rules.periodLengthDays
|
||||||
|
: DEFAULT_PERIOD_LENGTH_DAYS;
|
||||||
|
return {
|
||||||
|
enabled: rules?.enabled !== false,
|
||||||
|
anchorDate: anchorDate && Number.isFinite(anchorDate.getTime()) ? anchorDate : null,
|
||||||
|
periodLengthDays,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { enabled: false, anchorDate: null, periodLengthDays: DEFAULT_PERIOD_LENGTH_DAYS };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const findPeriodIdByStart = async (payload: Payload, startIso: string): Promise<number | null> => {
|
||||||
|
const res = await payload.find({
|
||||||
|
collection: "minigame-periods",
|
||||||
|
where: { startDate: { equals: startIso } },
|
||||||
|
limit: 1,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
return res.docs[0]?.id ?? null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Find or lazily create the anchored period containing `instant`. */
|
||||||
|
export const ensurePeriodForInstant = async (
|
||||||
|
payload: Payload,
|
||||||
|
rules: ResolvedRules,
|
||||||
|
instant: Date,
|
||||||
|
): Promise<number | null> => {
|
||||||
|
if (!rules.enabled || !rules.anchorDate) return null;
|
||||||
|
const derived = derivePeriodForInstant(rules.anchorDate, rules.periodLengthDays, instant);
|
||||||
|
if (!derived) return null;
|
||||||
|
|
||||||
|
const startIso = derived.startDate.toISOString();
|
||||||
|
const existingId = await findPeriodIdByStart(payload, startIso);
|
||||||
|
if (existingId != null) return existingId;
|
||||||
|
|
||||||
|
let previousPeriodId: number | null = null;
|
||||||
|
if (derived.index > 0) {
|
||||||
|
const prevStart = periodStartForIndex(
|
||||||
|
rules.anchorDate,
|
||||||
|
rules.periodLengthDays,
|
||||||
|
derived.index - 1,
|
||||||
|
).toISOString();
|
||||||
|
previousPeriodId = await findPeriodIdByStart(payload, prevStart);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const created = await payload.create({
|
||||||
|
collection: "minigame-periods",
|
||||||
|
data: {
|
||||||
|
startDate: startIso,
|
||||||
|
endDate: derived.endDate.toISOString(),
|
||||||
|
label: derived.label,
|
||||||
|
status: "open",
|
||||||
|
previousPeriod: previousPeriodId,
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
});
|
||||||
|
return created.id;
|
||||||
|
} catch {
|
||||||
|
// Lost a race to another writer; the unique startDate means ours is there.
|
||||||
|
return findPeriodIdByStart(payload, startIso);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function recordMinigameEntry(input: RecordMinigameEntryInput): Promise<void> {
|
||||||
|
const { payload } = input;
|
||||||
|
try {
|
||||||
|
const instant = input.now ?? new Date();
|
||||||
|
const rules = await resolveRules(payload);
|
||||||
|
const periodId = await ensurePeriodForInstant(payload, rules, instant);
|
||||||
|
|
||||||
|
const durationMs =
|
||||||
|
Number.isFinite(input.durationMs) && input.durationMs >= 0 ? Math.round(input.durationMs) : 0;
|
||||||
|
|
||||||
|
await payload.create({
|
||||||
|
collection: "minigame-entries",
|
||||||
|
data: {
|
||||||
|
user: input.userId,
|
||||||
|
game: input.game,
|
||||||
|
mode: input.mode ?? null,
|
||||||
|
score: input.score,
|
||||||
|
accuracy: input.accuracy ?? null,
|
||||||
|
durationMs,
|
||||||
|
period: periodId,
|
||||||
|
meta: input.meta ?? null,
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Never fail the player's submission because the ledger hiccuped.
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
try {
|
||||||
|
payload.logger.error(`[Minigames] Failed to record ${input.game} entry: ${message}`);
|
||||||
|
} catch {
|
||||||
|
// ignore logging failures
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
170
tests/int/minigame-entries.int.spec.ts
Normal file
170
tests/int/minigame-entries.int.spec.ts
Normal file
|
|
@ -0,0 +1,170 @@
|
||||||
|
import { getPayload, Payload } from "payload";
|
||||||
|
import config from "@/payload.config";
|
||||||
|
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
import type { User } from "@/payload-types";
|
||||||
|
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
|
||||||
|
import { derivePeriodForInstant } from "@/lib/minigames/periods/derive";
|
||||||
|
|
||||||
|
const ANCHOR = "2026-10-12T00:00:00.000Z";
|
||||||
|
const RUN = `mg-${Date.now().toString(36)}`;
|
||||||
|
|
||||||
|
let payload: Payload;
|
||||||
|
let userId: number;
|
||||||
|
let originalRules: Record<string, unknown> | null = null;
|
||||||
|
|
||||||
|
const entryPeriodId = (entry: { period?: unknown }): number | null => {
|
||||||
|
const period = entry.period;
|
||||||
|
if (period == null) return null;
|
||||||
|
return typeof period === "object" ? (period as { id: number }).id : (period as number);
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("Minigame entry recording + anchored periods", () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
const payloadConfig = await config;
|
||||||
|
payload = await getPayload({ config: payloadConfig });
|
||||||
|
|
||||||
|
originalRules = (await payload.findGlobal({
|
||||||
|
slug: "minigame-rules",
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})) as unknown as Record<string, unknown> | null;
|
||||||
|
|
||||||
|
await payload.updateGlobal({
|
||||||
|
slug: "minigame-rules",
|
||||||
|
data: { enabled: true, anchorDate: ANCHOR, periodLengthDays: 14 },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const user = (await payload.create({
|
||||||
|
collection: "users",
|
||||||
|
data: {
|
||||||
|
username: `${RUN}-player`,
|
||||||
|
discordUsername: `${RUN}-player`,
|
||||||
|
displayName: "MG PLAYER",
|
||||||
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||||
|
password: "Test123",
|
||||||
|
roles: ["user"],
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as User;
|
||||||
|
userId = user.id;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (!originalRules) return;
|
||||||
|
await payload
|
||||||
|
.updateGlobal({
|
||||||
|
slug: "minigame-rules",
|
||||||
|
data: {
|
||||||
|
enabled: Boolean(originalRules.enabled),
|
||||||
|
anchorDate: originalRules.anchorDate as string,
|
||||||
|
periodLengthDays: (originalRules.periodLengthDays as number) ?? 14,
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("derives anchored period indexes, labels and pre-anchor nulls", () => {
|
||||||
|
const anchor = new Date(ANCHOR);
|
||||||
|
|
||||||
|
const period0 = derivePeriodForInstant(anchor, 14, new Date(ANCHOR));
|
||||||
|
expect(period0?.index).toBe(0);
|
||||||
|
expect(period0?.label).toBe("Oct 12 to Oct 25, 2026");
|
||||||
|
|
||||||
|
const period1 = derivePeriodForInstant(anchor, 14, new Date("2026-10-26T00:00:00.000Z"));
|
||||||
|
expect(period1?.index).toBe(1);
|
||||||
|
expect(period1?.label).toBe("Oct 26 to Nov 8, 2026");
|
||||||
|
|
||||||
|
expect(
|
||||||
|
derivePeriodForInstant(anchor, 14, new Date("2026-10-11T23:59:59.999Z")),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lazily creates the anchored period and links entries to it", async () => {
|
||||||
|
await recordMinigameEntry({
|
||||||
|
payload,
|
||||||
|
userId,
|
||||||
|
game: "flappy",
|
||||||
|
score: 7,
|
||||||
|
durationMs: 12_000,
|
||||||
|
now: new Date("2026-10-14T12:00:00.000Z"),
|
||||||
|
});
|
||||||
|
await recordMinigameEntry({
|
||||||
|
payload,
|
||||||
|
userId,
|
||||||
|
game: "eod",
|
||||||
|
score: 300,
|
||||||
|
durationMs: 45_000,
|
||||||
|
mode: "perimeter",
|
||||||
|
now: new Date("2026-10-15T08:00:00.000Z"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const entries = await payload.find({
|
||||||
|
collection: "minigame-entries",
|
||||||
|
where: {
|
||||||
|
and: [
|
||||||
|
{ user: { equals: userId } },
|
||||||
|
{ game: { in: ["flappy", "eod"] } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
sort: "createdAt",
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
expect(entries.docs.length).toBe(2);
|
||||||
|
|
||||||
|
const periodIds = new Set(entries.docs.map(entryPeriodId));
|
||||||
|
expect(periodIds.size).toBe(1);
|
||||||
|
const periodId = [...periodIds][0];
|
||||||
|
expect(periodId).toBeTruthy();
|
||||||
|
|
||||||
|
const period = await payload.findByID({
|
||||||
|
collection: "minigame-periods",
|
||||||
|
id: periodId as number,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
expect(period.label).toBe("Oct 12 to Oct 25, 2026");
|
||||||
|
expect(period.status).toBe("open");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("records entries before the anchor with no period", async () => {
|
||||||
|
await recordMinigameEntry({
|
||||||
|
payload,
|
||||||
|
userId,
|
||||||
|
game: "opord",
|
||||||
|
score: 5,
|
||||||
|
durationMs: 30_000,
|
||||||
|
now: new Date("2026-10-01T00:00:00.000Z"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await payload.find({
|
||||||
|
collection: "minigame-entries",
|
||||||
|
where: {
|
||||||
|
and: [{ user: { equals: userId } }, { game: { equals: "opord" } }],
|
||||||
|
},
|
||||||
|
limit: 1,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
expect(res.docs.length).toBe(1);
|
||||||
|
expect(entryPeriodId(res.docs[0])).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never throws when recording fails", async () => {
|
||||||
|
// A non-existent user id violates the FK; the recorder must swallow it.
|
||||||
|
await expect(
|
||||||
|
recordMinigameEntry({
|
||||||
|
payload,
|
||||||
|
userId: 999_999_999,
|
||||||
|
game: "flappy",
|
||||||
|
score: 1,
|
||||||
|
durationMs: 1_000,
|
||||||
|
now: new Date("2026-10-14T12:00:00.000Z"),
|
||||||
|
}),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue