1
0
Fork 0
polaris-task-force/tests/int/friday-ops-notice.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

324 lines
13 KiB
TypeScript

import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Campaign, Map as MissionMap, Mission, User } from "@/payload-types";
import {
getFridayClaimant,
hasMissionOnFriday,
isNoticeDue,
noticeToken,
upcomingFridayRange,
} from "@/lib/intelligence/fridayOpsNotice";
let payload: Payload;
const RUN = `fon-${Date.now().toString(36)}`;
// Hermetic window: 2027-01-13 is a Wednesday far enough out that the shared
// dev database holds no real missions on its Friday (2027-01-15). All fixtures
// are explicit UTC instants so the suite behaves identically on any machine
// timezone (January 2027 is EST, UTC-5: Eastern midnight = 05:00Z).
const WEDNESDAY = new Date("2027-01-13T17:00:00Z"); // Wed 12:00 PM ET
// Wed 8:00 PM ET — already Thursday 01:00 UTC, the instant that broke the
// old server-local window math on the UTC deploy container.
const WEDNESDAY_EVENING = new Date("2027-01-14T01:00:00Z");
const TUESDAY = new Date("2027-01-12T17:00:00Z"); // Tue 12:00 PM ET
const FRIDAY = new Date("2027-01-15T17:00:00Z"); // Fri 12:00 PM ET
const FRIDAY_EVENING = new Date("2027-01-16T01:00:00Z"); // Fri 8:00 PM ET
const SATURDAY = new Date("2027-01-17T01:00:00Z"); // Sat 8:00 PM ET
const FRIDAY_SLOT_START = "2027-01-15T05:00:00.000Z"; // Fri 00:00 EST
const FRIDAY_SLOT_END = "2027-01-16T04:59:59.999Z"; // Fri 23:59:59.999 EST
describe("Friday open-slot notice", () => {
let mapId: number;
let campaignId: number;
let authorId: number;
let zeusId: number;
let superuserId: number;
const missionIds: number[] = [];
const userIds: number[] = [];
const roleIds: number[] = [];
beforeAll(async () => {
payload = await getTestPayload();
// Sweep leftovers from crashed earlier runs: a stray Concept mission in
// the fixture window would flip the first hasMissionOnFriday assertion.
const stale = await payload.find({
collection: "missions",
overrideAccess: true,
depth: 0,
limit: 100,
where: { codeName: { like: "fon-" } },
});
for (const doc of stale.docs) {
await payload.delete({ collection: "missions", id: doc.id, overrideAccess: true }).catch(() => {});
}
const map = (await payload.create({
collection: "maps",
data: { name: `${RUN} Map`, worldSizeWidth: 8192, worldSizeHeight: 8192, basemapMode: "image" },
overrideAccess: true,
depth: 0,
})) as unknown as MissionMap;
mapId = map.id;
const campaign = (await payload.create({
collection: "campaigns",
data: { name: `${RUN} Campaign`, summary: "Friday notice test campaign", status: "concept", campaignMode: "custom" },
overrideAccess: true,
depth: 0,
})) as unknown as Campaign;
campaignId = campaign.id;
const author = (await payload.create({
collection: "users",
data: {
username: `${RUN}-author`,
discordUsername: `${RUN}-author`,
displayName: "AUTHOR",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
authorId = author.id;
userIds.push(authorId);
const zeus = (await payload.create({
collection: "users",
data: {
username: `${RUN}-zeus`,
discordUsername: `${RUN}-zeus`,
displayName: "ZEUS",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
zeusId = zeus.id;
userIds.push(zeusId);
const superRole = (await payload.create({
collection: "roles",
data: { name: `FON Superuser ${RUN}`, slug: "", isSuperuser: true },
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
roleIds.push(superRole.id);
const superuser = (await payload.create({
collection: "users",
data: {
username: `${RUN}-su`,
discordUsername: `${RUN}-su`,
displayName: "SU",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
roleDocs: [superRole.id],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
superuserId = superuser.id;
userIds.push(superuserId);
});
afterAll(async () => {
for (const id of missionIds) {
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
}
await payload
.delete({ collection: "campaigns", id: campaignId, overrideAccess: true })
.catch(() => {});
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
// User deletion trips FK constraints unless the hook-provisioned
// personal bank account and profile are removed first.
for (const uid of userIds) {
const accounts = await payload
.find({
collection: "bank-accounts",
where: { ownerUser: { equals: uid } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const account of accounts?.docs ?? []) {
await payload
.delete({ collection: "bank-accounts", id: account.id, overrideAccess: true })
.catch(() => {});
}
const profiles = await payload
.find({
collection: "profiles",
where: { user: { equals: uid } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const profile of profiles?.docs ?? []) {
await payload
.delete({ collection: "profiles", id: profile.id, overrideAccess: true })
.catch(() => {});
}
await payload.delete({ collection: "users", id: uid, overrideAccess: true }).catch(() => {});
}
for (const rid of roleIds) {
await payload.delete({ collection: "roles", id: rid, overrideAccess: true }).catch(() => {});
}
});
const makeMission = async (
label: string,
start: Date,
status: Mission["ownershipAndStatus"]["status"] = "Scheduled",
creatorId?: number,
): Promise<Mission> => {
const mission = (await payload.create({
collection: "missions",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Friday notice test mission",
operationType: "side",
classification: {
map: mapId,
missionType: "PvE",
campaign: campaignId,
startDateTime: start.toISOString(),
estimatedDuration: 60,
},
ownershipAndStatus: {
authors: [authorId],
status,
visibility: "unit",
},
missionRoles: {
maxPlayers: 16,
},
gameDetails: {
serverDetails: {
serverIp: "127.0.0.1",
serverPort: 2302,
},
},
briefing: [],
...(creatorId ? { createdBy: creatorId } : {}),
},
overrideAccess: true,
depth: 0,
})) as unknown as Mission;
missionIds.push(mission.id);
return mission;
};
it("is due on Wednesdays at 8 PM Eastern, until the ET day rolls over", () => {
// 2026-09-16 is a Wednesday in EDT (UTC-4); January is EST (UTC-5).
expect(isNoticeDue(new Date("2026-09-17T00:30:00Z"))).toBe(true); // Wed 20:30 ET
expect(isNoticeDue(new Date("2026-09-17T03:59:00Z"))).toBe(true); // Wed 23:59 ET
expect(isNoticeDue(new Date("2026-09-15T20:30:00Z"))).toBe(false); // Tue 16:30 ET
expect(isNoticeDue(new Date("2026-09-16T16:00:00Z"))).toBe(false); // Wed 12:00 ET
expect(isNoticeDue(new Date("2026-09-16T23:59:00Z"))).toBe(false); // Wed 19:59 ET
expect(isNoticeDue(new Date("2026-09-17T00:00:00Z"))).toBe(true); // Wed 20:00 ET sharp
expect(isNoticeDue(new Date("2026-09-17T04:00:00Z"))).toBe(false); // Thu 00:00 ET
expect(isNoticeDue(new Date("2026-01-15T01:00:00Z"))).toBe(true); // Wed 20:00 ET (EST)
});
it("targets Friday 00:00-23:59:59.999 Eastern regardless of server timezone", () => {
const fromWednesday = upcomingFridayRange(WEDNESDAY);
expect(fromWednesday.start.toISOString()).toBe(FRIDAY_SLOT_START);
expect(fromWednesday.end.toISOString()).toBe(FRIDAY_SLOT_END);
expect(fromWednesday.epoch).toBe(Math.floor(fromWednesday.start.getTime() / 1000));
// Earlier in the week still lands on the same Friday.
expect(upcomingFridayRange(TUESDAY).start).toEqual(fromWednesday.start);
// Regression (prod incident 2026-10-07): Wed 8 PM ET is Thursday UTC on
// the UTC deploy container; the slot must stay THIS week's Eastern Friday,
// and an op starting Friday 8 PM ET — the exact instant that fell outside
// the old server-local window — must count as inside it.
const fromWednesdayEvening = upcomingFridayRange(WEDNESDAY_EVENING);
expect(fromWednesdayEvening.start).toEqual(fromWednesday.start);
expect(FRIDAY_EVENING >= fromWednesdayEvening.start).toBe(true);
expect(FRIDAY_EVENING <= fromWednesdayEvening.end).toBe(true);
// On the Friday itself (Eastern) that day is still the slot, so the
// notice keeps tracking late claims; Saturday rolls to the next Friday.
expect(upcomingFridayRange(FRIDAY).start).toEqual(fromWednesday.start);
expect(upcomingFridayRange(SATURDAY).start.toISOString()).toBe("2027-01-22T05:00:00.000Z");
});
it("builds a stable per-Friday dedup token", () => {
expect(noticeToken(WEDNESDAY)).toBe(noticeToken(TUESDAY));
expect(noticeToken(WEDNESDAY)).toBe(`<t:${upcomingFridayRange(WEDNESDAY).epoch}:D>`);
// Stable through the op day, so claims made after Thursday ET midnight
// still match the notice posted on Wednesday.
expect(noticeToken(FRIDAY)).toBe(noticeToken(WEDNESDAY));
expect(noticeToken(SATURDAY)).not.toBe(noticeToken(WEDNESDAY));
});
it("treats the Friday slot as open only when a non-cancelled mission starts that Friday", async () => {
await expect(hasMissionOnFriday(payload, WEDNESDAY)).resolves.toBe(false);
const concept = await makeMission("concept-friday", FRIDAY_EVENING, "Concept");
await expect(hasMissionOnFriday(payload, WEDNESDAY)).resolves.toBe(true);
// Same answer when asked at Wed 8 PM ET (= Thursday UTC): a Friday-evening
// op holds the slot on any server timezone.
await expect(hasMissionOnFriday(payload, WEDNESDAY_EVENING)).resolves.toBe(true);
await makeMission("cancelled-friday", FRIDAY_EVENING, "Cancelled");
await expect(hasMissionOnFriday(payload, WEDNESDAY)).resolves.toBe(true);
await payload.delete({ collection: "missions", id: concept.id, overrideAccess: true });
await expect(hasMissionOnFriday(payload, WEDNESDAY)).resolves.toBe(false);
const saturday = await makeMission("saturday-mission", SATURDAY);
await expect(hasMissionOnFriday(payload, WEDNESDAY)).resolves.toBe(false);
await payload.delete({ collection: "missions", id: saturday.id, overrideAccess: true });
});
it("credits the earliest non-superuser creator as the claimant", async () => {
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toBeNull();
const zeusMission = await makeMission("zeus-claim", FRIDAY_EVENING, "Scheduled", zeusId);
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toEqual({ userName: "ZEUS" });
// A Friday-evening claim is still credited when checked at Wed 8 PM ET
// (= Thursday UTC on the deploy container).
await expect(getFridayClaimant(payload, WEDNESDAY_EVENING)).resolves.toEqual({
userName: "ZEUS",
});
await makeMission("su-claim", FRIDAY_EVENING, "Scheduled", superuserId);
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toEqual({ userName: "ZEUS" });
await payload.delete({ collection: "missions", id: zeusMission.id, overrideAccess: true });
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toBeNull();
const first = await makeMission("zeus-first", FRIDAY_EVENING, "Scheduled", zeusId);
const second = await makeMission("zeus-second", FRIDAY_EVENING, "Scheduled", zeusId);
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toEqual({ userName: "ZEUS" });
expect(first.createdAt <= second.createdAt).toBe(true);
await payload.delete({ collection: "missions", id: first.id, overrideAccess: true });
await payload.delete({ collection: "missions", id: second.id, overrideAccess: true });
const claimer = await makeMission("zeus-cancelled", FRIDAY_EVENING, "Scheduled", zeusId);
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toEqual({ userName: "ZEUS" });
await payload.update({
collection: "missions",
id: claimer.id,
data: { ownershipAndStatus: { status: "Cancelled" } },
overrideAccess: true,
});
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toBeNull();
});
});