Files
mtusi2026lab7/scripts/health-convergence.ts

76 lines
2.2 KiB
TypeScript

export function freshSecretsAfterSeal(
contents: string[],
sealedAt: number,
now: number,
maxAgeMilliseconds: number,
) {
return (
contents.length === 3 &&
[sealedAt, now, maxAgeMilliseconds].every(Number.isFinite) &&
sealedAt >= 0 &&
now >= sealedAt &&
maxAgeMilliseconds > 0 &&
contents.every((content) => {
const value = content.trim();
if (
content.length > 128 ||
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(
value,
)
)
return false;
const timestamp = Date.parse(value),
age = now - timestamp;
return (
Number.isFinite(age) &&
age >= 0 &&
age <= maxAgeMilliseconds &&
timestamp > sealedAt
);
})
);
}
export function createHealthConvergence(
ports: {
read: () => Promise<string>;
now: () => number;
sleep: (milliseconds: number) => Promise<void>;
},
budgetMilliseconds: number,
pollMilliseconds: number,
) {
if (
[ports?.read, ports?.now, ports?.sleep].some((p) => typeof p !== "function")
)
throw Error("HEALTH_PORTS_REQUIRED");
if (
!Number.isSafeInteger(budgetMilliseconds) ||
!Number.isSafeInteger(pollMilliseconds) ||
pollMilliseconds <= 0 ||
budgetMilliseconds < pollMilliseconds
)
throw Error("HEALTH_LIMITS_INVALID");
return async () => {
const started = ports.now();
if (!Number.isFinite(started) || started < 0)
throw Error("HEALTH_CLOCK_INVALID");
let reads = 0;
for (;;) {
const state = await ports.read();
reads++;
const elapsedMilliseconds = ports.now() - started;
if (!Number.isFinite(elapsedMilliseconds) || elapsedMilliseconds < 0)
throw Error("HEALTH_CLOCK_INVALID");
if (!["healthy", "starting", "unhealthy"].includes(state))
throw Error("BAO_HEALTH_INVALID");
if (state === "healthy" && elapsedMilliseconds <= budgetMilliseconds)
return { elapsedMilliseconds, reads };
if (elapsedMilliseconds >= budgetMilliseconds)
throw Error("BAO_HEALTH_NOT_CONVERGED");
await ports.sleep(
Math.min(pollMilliseconds, budgetMilliseconds - elapsedMilliseconds),
);
}
};
}