deadhead-space-freight-tycoon/apps/server/src/clock.ts

31 lines
864 B
TypeScript

import type { RealTime } from "@deadhead/sim";
/** The server's only source of "now" (decision 0.5.18), so tests can control time. */
export type Clock = () => RealTime;
export const systemClock: Clock = () => Date.now();
/**
* A clock that runs ahead of (or behind) its base clock by an adjustable offset.
* The test-only clock-offset endpoint moves it; production never does (Step 7.2).
*/
export interface OffsetClock {
now: Clock;
offsetMs(): number;
setOffset(ms: number): void;
/** Converts a time on this clock to the base clock, e.g. for pg-boss timers. */
toBase(time: RealTime): RealTime;
}
export function createOffsetClock(base: Clock): OffsetClock {
let offset = 0;
return {
now: () => base() + offset,
offsetMs: () => offset,
setOffset: (ms) => {
offset = ms;
},
toBase: (time) => time - offset,
};
}