1
0
Fork 0
polaris-task-force/src/scripts/economyTick.ts

66 lines
2.5 KiB
TypeScript

/**
* Economy tick bin — recomputes the supply/demand ledger (market-state).
*
* Run via `bun run payload economy-tick` (external cron). Uses the GameRules
* `tickIntervalHintMinutes` knob to seed a deterministic per-period RNG so a
* retried run inside the same period produces identical drift steps.
*/
import type { SanitizedConfig } from "payload";
import { getPayload } from "payload";
import { createSeededRng, periodSeed } from "@/lib/economy/math";
import { processEconomyTick } from "@/lib/economy/tick";
import { emitEconomyEvents } from "@/lib/economy/events";
import { getEconomySettings } from "@/lib/economy/config";
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
export const script = async (config: SanitizedConfig) => {
const payload = await getPayload({ config });
const log = createBinLogger("economy-tick", payload.logger);
try {
log.info("[Economy Tick] Starting economy tick...");
const now = new Date();
const { enabled, knobs } = await getEconomySettings(payload);
const result = await processEconomyTick(payload, {
now,
rng: createSeededRng(periodSeed(now, knobs.tickIntervalHintMinutes)),
masterGate: enabled,
knobs,
});
if (result.disabled) {
log.info("[Economy Tick] Master gate is off, nothing processed.");
} else {
await emitEconomyEvents(payload, result);
log.info(
`[Economy Tick] Complete. Processed ${result.processed}, skipped ${result.skipped}, ` +
`${result.priceChanges.length} price change(s), ${result.errors} error(s).`,
);
// Notify connected clients so economy-driven views refresh.
const notifyUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
const notifySecret = process.env.GAME_TICK_NOTIFY_SECRET;
if (notifySecret) {
await fetch(`${notifyUrl}/api/game-tick/notify`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-game-tick-secret": notifySecret,
},
body: JSON.stringify({ processedAt: now.toISOString(), source: "economy-tick" }),
}).catch((error: unknown) => {
log.error(`[Economy Tick] Failed to notify app clients: ${errorMessage(error)}`);
});
}
}
process.exit(0);
} catch (error) {
log.error(
`[Economy Tick] Fatal: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
);
process.exit(1);
}
};