1
0
Fork 0
polaris-task-force/tests/int/contributions.int.spec.ts
Z8MB1E 938da9bf86 test(vitest): isolate:false shared forks with per-pid template clones + memoized payload boot
Stage 3 of the int-suite speedup (gate G2 showed Vitest 4's pool scheduler
only reuses worker processes between isolate:false tasks, so per-file fork
spawning made clone+boot costs unavoidable at stage 2):

- config: workers branch runs pool=forks with isolate:false, cap 8 via
  VITEST_MAX_FORKS, node default env (jsdom docblocks on DOM specs),
  failure-marker reporter, and idempotent setupFiles chain
- vitest-worker-setup: one template clone PER FORK PROCESS named by pid
  (VITEST_WORKER_ID churns per task, which silently re-cloned per file);
  DATABASE_URI repoint + TEST_PG_POOL_MAX=8 (measured hook deadlocks at 3)
- vitest.setup: once-per-process serial test URI markers; afterEach
  useRealTimers guard (restoreAllMocks omitted: it resurrects vi.mock
  module factories mid-file); logging absorber for fire-and-forget event
  writes that reject after their spec's cleanup deleted fixture users
- helpers/get-test-payload.ts: memoized Payload boot shared across files
  in a fork; codemod converted all 91 self-booting specs mechanically
- pinned opt-outs (own boot + comments): game-structures-labor-route,
  mission-reminder, notification-inbox-scope (jwtSign writes leak into
  the shared instance's auth state across files)
- promotion-nominations: create the superuser before its rank ladder so
  the Users-hook Recruit rank gets leading orderable tokens (its
  top-of-ladder guard needs Col to remain ladder-max on fresh clones);
  operation-economy: itemType-scope the market-state assertion (asset
  and resource ids collide as bare integers under per-fork databases)

Gate G3: 5 consecutive full green runs (149/149 files), warm wall 53-65s
vs 598s baseline (~10x), zero clone residue after green runs. Vitest 4
note: globalTeardown config no longer exists; teardown returns from
globalSetup.
2026-10-21 12:54:30 -04:00

357 lines
12 KiB
TypeScript

import { getTestPayload } from "../helpers/get-test-payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Mission, User } from "@/payload-types";
import {
expireQueuedEntriesForMission,
getContributionLeaderboard,
getContributionSummary,
grantQueuedEntriesForMission,
recordContribution,
revokeEntry,
} from "@/lib/contributions";
import { createMissionMarker } from "@/lib/intelligence/missionMap";
type Payload = Awaited<ReturnType<typeof getTestPayload>>;
describe("Contribution / XP service", () => {
let payload: Payload;
const RUN = `contrib-${Date.now().toString(36)}`;
let mapId: number;
let mission: Mission;
let contributor: User;
let other: User;
const userIds: number[] = [];
const makeUser = async (username: string): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: username,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const makeMission = async (label: string): Promise<Mission> =>
(await payload.create({
collection: "missions",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Contribution test mission",
operationType: "main",
createdBy: contributor.id,
classification: {
map: mapId,
missionType: "PvE",
startDateTime: new Date(Date.now() + 2 * 86_400_000).toISOString(),
estimatedDuration: 60,
planningMapEnabled: true,
},
ownershipAndStatus: { authors: [contributor.id], status: "Scheduled", visibility: "unit" },
briefing: [],
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
missionRoles: { maxPlayers: 32, providedRoles: [] },
},
overrideAccess: true,
depth: 1,
})) as unknown as Mission;
const bucketFor = async (userId: number): Promise<number> => {
const res = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
select: { progression: { contributions: { xpEarned: true } } },
});
return res.docs[0]?.progression?.contributions?.xpEarned ?? 0;
};
const makeMarker = async (label: string) =>
createMissionMarker(
payload,
mission,
{ shape: "icon", markerType: "b_inf", color: "Default", position: [100, 100] },
contributor.id,
);
beforeAll(async () => {
payload = await getTestPayload();
const map = await payload.create({
collection: "maps",
data: {
name: `${RUN} Map`,
worldSizeWidth: 4096,
worldSizeHeight: 4096,
basemapMode: "image",
},
overrideAccess: true,
depth: 0,
});
mapId = map.id;
contributor = await makeUser(`${RUN}-contributor`);
other = await makeUser(`${RUN}-other`);
mission = await makeMission("Op");
});
afterAll(async () => {
if (!payload) return;
for (const userId of userIds) {
await payload
.delete({
collection: "contribution-entries",
where: { user: { equals: userId } },
overrideAccess: true,
})
.catch(() => {});
}
if (mission) {
await payload
.delete({ collection: "missions", id: mission.id, overrideAccess: true })
.catch(() => {});
}
for (const id of userIds) {
for (const collection of ["profiles"] as const) {
const docs = await payload
.find({ collection, where: { user: { equals: id } }, depth: 0, overrideAccess: true })
.catch(() => null);
for (const doc of docs?.docs ?? []) {
await payload.delete({ collection, id: doc.id, overrideAccess: true }).catch(() => {});
}
}
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
});
it("grants an instant manual contribution and bumps the profile bucket", async () => {
const before = await bucketFor(contributor.id);
const result = await recordContribution(payload, {
userId: contributor.id,
type: "manual",
sourceCollection: "manual",
sourceId: contributor.id,
summary: "Helped organize the unit event",
pointsOverride: 7,
dedupeSuffix: "event-1",
});
expect(result.status).toBe("granted");
expect(result.points).toBe(7);
expect(await bucketFor(contributor.id)).toBe(before + 7);
});
it("is idempotent: the same contribution cannot be counted twice", async () => {
const input = {
userId: contributor.id,
type: "manual" as const,
sourceCollection: "manual" as const,
sourceId: contributor.id,
summary: "Duplicate guard",
pointsOverride: 3,
dedupeSuffix: "dup-key",
};
const first = await recordContribution(payload, input);
const second = await recordContribution(payload, input);
expect(second.entryId).toBe(first.entryId);
const count = await payload.count({
collection: "contribution-entries",
where: { idempotencyKey: { equals: `manual:manual:${contributor.id}:dup-key` } },
overrideAccess: true,
});
expect(count.totalDocs).toBe(1);
});
it("queues marker XP and does not grant it until the mission completes", async () => {
const marker = await makeMarker("queue");
const before = await bucketFor(contributor.id);
const result = await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: marker.id,
missionId: mission.id,
summary: `Placed a planning marker on "${mission.name}"`,
});
expect(result.status).toBe("queued");
expect(await bucketFor(contributor.id)).toBe(before);
const sweep = await grantQueuedEntriesForMission(payload, mission.id);
expect(sweep.granted).toBeGreaterThanOrEqual(1);
expect(await bucketFor(contributor.id)).toBe(before + 2);
});
it("revokes queued XP when the marker is gone at completion", async () => {
const marker = await makeMarker("vanishes");
await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: marker.id,
missionId: mission.id,
summary: `Placed a planning marker on "${mission.name}"`,
});
await payload.delete({
collection: "mission-map-markers",
id: marker.id,
overrideAccess: true,
});
const before = await bucketFor(contributor.id);
const sweep = await grantQueuedEntriesForMission(payload, mission.id);
expect(sweep.revoked).toBeGreaterThanOrEqual(1);
expect(await bucketFor(contributor.id)).toBe(before);
});
it("expires queued XP when the mission is cancelled", async () => {
const marker = await makeMarker("cancelled");
await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: marker.id,
missionId: mission.id,
summary: `Placed a planning marker on "${mission.name}"`,
});
const expired = await expireQueuedEntriesForMission(payload, mission.id);
expect(expired).toBeGreaterThanOrEqual(1);
const res = await payload.find({
collection: "contribution-entries",
where: {
and: [
{ sourceId: { equals: marker.id } },
{ sourceCollection: { equals: "mission-map-markers" } },
],
},
depth: 0,
overrideAccess: true,
});
expect(res.docs[0]?.status).toBe("expired");
});
it("pulls granted XP back on revocation", async () => {
const grant = await recordContribution(payload, {
userId: contributor.id,
type: "manual",
sourceCollection: "manual",
sourceId: contributor.id,
summary: "To be revoked",
pointsOverride: 9,
dedupeSuffix: "revoke-me",
});
const before = await bucketFor(contributor.id);
await revokeEntry(payload, grant.entryId as number, { reason: "Reversed by staff." });
expect(await bucketFor(contributor.id)).toBe(before - 9);
});
it("enforces the per-mission marker cap", async () => {
const capMission = await makeMission("Cap");
const capMarker = await createMissionMarker(
payload,
capMission,
{ shape: "icon", markerType: "b_inf", color: "Default", position: [100, 100] },
contributor.id,
);
let granted = 0;
// Cap is 10 per user per mission; the 11th attempt is skipped.
for (let i = 0; i < 11; i += 1) {
const result = await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: capMarker.id + 1000 + i,
missionId: capMission.id,
summary: "cap probe",
});
if (result.status === "queued") granted += 1;
}
expect(granted).toBe(10);
await payload
.delete({ collection: "missions", id: capMission.id, overrideAccess: true })
.catch(() => {});
});
it("preserves other progression fields when updating the bucket", async () => {
// Seed unrelated progression data on the other user's profile.
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: other.id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const profileId = profileRes.docs[0]!.id;
await payload.update({
collection: "profiles",
id: profileId,
data: { progression: { minigames: { flappyBird: { gamesPlayed: 5 } }, scoreboard: { infantryKills: 3 } } },
overrideAccess: true,
});
await recordContribution(payload, {
userId: other.id,
type: "manual",
sourceCollection: "manual",
sourceId: other.id,
summary: "Merge safety check",
pointsOverride: 4,
dedupeSuffix: "merge-safety",
});
const after = await payload.findByID({
collection: "profiles",
id: profileId,
depth: 0,
overrideAccess: true,
});
expect(after.progression?.minigames?.flappyBird?.gamesPlayed).toBe(5);
expect(after.progression?.scoreboard?.infantryKills).toBe(3);
expect(after.progression?.contributions?.xpEarned).toBe(4);
});
it("aggregates the leaderboard from granted entries", async () => {
const board = await getContributionLeaderboard(payload, { limit: 25 });
const row = board.find((entry) => entry.userId === contributor.id);
expect(row).toBeDefined();
expect(row!.points).toBeGreaterThan(0);
});
it("hides non-granted rows from non-owners in the summary", async () => {
const summary = await getContributionSummary(payload, contributor.id, {
isOwner: false,
limit: 50,
});
expect(summary.rows.every((row) => row.status === "granted")).toBe(true);
expect(summary.granted).toBeGreaterThan(0);
});
it("exposes a user's own rows (including queued) to the owner", async () => {
const marker = await makeMarker("owner-view");
await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: marker.id,
missionId: mission.id,
summary: "owner visibility",
});
const summary = await getContributionSummary(payload, contributor.id, {
isOwner: true,
limit: 100,
});
expect(summary.queued).toBeGreaterThan(0);
expect(summary.rows.some((row) => row.status === "queued")).toBe(true);
// Keep the shared mission clean for any later sweeps.
await expireQueuedEntriesForMission(payload, mission.id);
});
});