Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pm-stack/aggregator/scripts/collect-fleet-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,7 @@ async function collectAaSection(generatedAt: string): Promise<AaFeedSection> {
return withIndex;
}

async function main(): Promise<void> {
export async function main(): Promise<void> {
const now = new Date();
const sectionStatuses: NonNullable<FleetFeed["meta"]>["sections"] = {};
const markSection = (
Expand Down
4 changes: 2 additions & 2 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1052,7 +1052,7 @@ async function runAnomalyDetectors(args: {
}
}

async function main(): Promise<number> {
export async function main(): Promise<number> {
const started = Date.now();
const tickAt = new Date(started).toISOString();

Expand Down Expand Up @@ -1318,4 +1318,4 @@ async function main(): Promise<number> {
return 0;
}

process.exit(await main());
if (import.meta.main) process.exit(await main());
90 changes: 90 additions & 0 deletions pm-stack/aggregator/src/pm-core-scheduler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* In-process PM-core job scheduling (#8570, first consolidation slice).
*
* The jobs are injected so the scheduler owns cadence and single-flight
* semantics without owning provider or feed logic. Audit records are
* write-only: the scheduler reports each attempt to the caller, but never
* reads an audit file as a freshness source.
*/

export const QUOTA_CADENCE_MS = 15 * 60_000;
export const FLEET_FEED_CADENCE_MS = 5 * 60_000;

export type SchedulerJobName = "quota" | "fleet-feed";

export interface SchedulerAudit {
job: SchedulerJobName;
startedAt: string;
finishedAt: string;
status: "ok" | "error";
error?: string;
}

export interface PmCoreScheduler {
start(): void;
stop(): void;
runNow(job: SchedulerJobName): Promise<void>;
running(job: SchedulerJobName): boolean;
}

type Timer = ReturnType<typeof setInterval>;
type Job = () => Promise<void> | void;

export function createPmCoreScheduler(options: {
runQuota: Job;
runFleetFeed: Job;
writeAudit: (record: SchedulerAudit) => Promise<void> | void;
now?: () => Date;
setInterval?: (callback: () => void, delayMs: number) => Timer;
clearInterval?: (timer: Timer) => void;
}): PmCoreScheduler {
const now = options.now ?? (() => new Date());
const setTimer = options.setInterval ?? ((callback, delayMs) => setInterval(callback, delayMs));
const clearTimer = options.clearInterval ?? ((timer) => clearInterval(timer));
const jobs: Record<SchedulerJobName, Job> = {
quota: options.runQuota,
"fleet-feed": options.runFleetFeed,
};
const cadence: Record<SchedulerJobName, number> = {
quota: QUOTA_CADENCE_MS,
"fleet-feed": FLEET_FEED_CADENCE_MS,
};
const active = new Set<SchedulerJobName>();
const timers = new Map<SchedulerJobName, Timer>();

async function runNow(job: SchedulerJobName): Promise<void> {
if (active.has(job)) return;
active.add(job);
const startedAt = now().toISOString();
try {
await jobs[job]();
await options.writeAudit({ job, startedAt, finishedAt: now().toISOString(), status: "ok" });
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
await options.writeAudit({
job,
startedAt,
finishedAt: now().toISOString(),
status: "error",
error: message,
});
} finally {
active.delete(job);
}
}

return {
start() {
if (timers.size > 0) return;
for (const job of Object.keys(jobs) as SchedulerJobName[]) {
timers.set(job, setTimer(() => void runNow(job), cadence[job]));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle audit-write failures in scheduled callbacks

If writeAudit rejects because its destination is unavailable or full, runNow catches the initial failure but then awaits another write to the same failing sink, allowing that rejection to escape. The interval callback discards the returned promise without a rejection handler, so an audit-storage failure becomes an unhandled rejection in the hosting process instead of an isolated scheduler error. Handle audit failures separately and attach a rejection handler to timer-triggered runs so failure of the write-only audit sink cannot disrupt both jobs.

Useful? React with 👍 / 👎.

}
},
stop() {
for (const timer of timers.values()) clearTimer(timer);
timers.clear();
},
runNow,
running: (job) => active.has(job),
};
}
86 changes: 86 additions & 0 deletions pm-stack/aggregator/test/pm-core-scheduler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { describe, expect, test } from "bun:test";
import {
createPmCoreScheduler,
FLEET_FEED_CADENCE_MS,
QUOTA_CADENCE_MS,
type SchedulerAudit,
} from "../src/pm-core-scheduler.ts";

describe("pm-core scheduler (#8570)", () => {
test("registers the quota and fleet-feed cadences without reading audit state", () => {
const timers: number[] = [];
const audits: SchedulerAudit[] = [];
const scheduler = createPmCoreScheduler({
runQuota: () => {},
runFleetFeed: () => {},
writeAudit: (record) => {
audits.push(record);
},
setInterval: (_callback, delayMs) => {
timers.push(delayMs);
return delayMs as unknown as ReturnType<typeof setInterval>;
},
clearInterval: () => {},
});

scheduler.start();
scheduler.start();
expect(timers).toEqual([QUOTA_CADENCE_MS, FLEET_FEED_CADENCE_MS]);
expect(audits).toEqual([]);
scheduler.stop();
});

test("single-flights a job and writes success audit after it completes", async () => {
let release!: () => void;
let calls = 0;
const audits: SchedulerAudit[] = [];
const scheduler = createPmCoreScheduler({
runQuota: () => {
calls += 1;
return new Promise<void>((resolve) => {
release = resolve;
});
},
runFleetFeed: () => {},
writeAudit: (record) => {
audits.push(record);
},
now: (() => {
let tick = 0;
return () => new Date(`2026-11-23T00:00:0${tick++}Z`);
})(),
});

const first = scheduler.runNow("quota");
const second = scheduler.runNow("quota");
expect(scheduler.running("quota")).toBe(true);
expect(calls).toBe(1);
release();
await Promise.all([first, second]);
expect(scheduler.running("quota")).toBe(false);
expect(audits).toHaveLength(1);
expect(audits[0].status).toBe("ok");
expect(audits[0].job).toBe("quota");
});

test("records a failed job without stopping the other scheduler", async () => {
const audits: SchedulerAudit[] = [];
const scheduler = createPmCoreScheduler({
runQuota: async () => {
throw new Error("provider unavailable");
},
runFleetFeed: () => {},
writeAudit: (record) => {
audits.push(record);
},
});

await scheduler.runNow("quota");
await scheduler.runNow("fleet-feed");
expect(audits.map((audit) => [audit.job, audit.status])).toEqual([
["quota", "error"],
["fleet-feed", "ok"],
]);
expect(audits[0].error).toBe("provider unavailable");
});
});