unit(D2): idempotent instance generator (16-week window) on cron route
Service instance generation (ARCHITECTURE §5.1): for each active service, plan instances in the rolling window and upsert on (service_id, starts_at). onConflictDoNothing makes the whole thing idempotent — a re-run creates 0 rows, cancelled/published instances are never touched, past instances are never deleted. - src/domain/instances.ts: pure planInstances() + windowTarget(); DST-safe instants via localToUtc, no DB imports. - src/domain/instances.test.ts: 7 tests (window boundary, DST-safe instants, determinism, biweekly phase, monthly-nth, windowTarget). - src/db/instances.ts: generateInstances() idempotent upsert; occurs_on stored as zoned midnight (no UTC-midnight shift). - src/app/api/dev/cron/instances/route.ts: GET drives the daily job. No schema change (service_instances unique index predates this unit; slot materialization stays deferred to D3). Verified: run twice -> 0 created, count unchanged; published instances byte-identical; generated instances stored as DST-safe UTC instants.
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Service instances — unit D2 (ARCHITECTURE §5.1).
|
||||
*
|
||||
* `generateInstances()` is the daily cron job. For each active service it plans
|
||||
* the instances in the rolling window and upserts them on the
|
||||
* `(service_id, starts_at)` key. `onConflictDoNothing` makes the whole thing
|
||||
* idempotent:
|
||||
*
|
||||
* - a re-run finds the existing row and leaves it untouched,
|
||||
* - a `cancelled` instance stays cancelled (never regenerated),
|
||||
* - a `published` instance is never modified here,
|
||||
* - past instances fall outside the window and are never deleted.
|
||||
*
|
||||
* Slot materialization from role requirements is D3; this unit only owns the
|
||||
* instance rows.
|
||||
*/
|
||||
|
||||
import { and, count, eq, gte } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { services, serviceInstances } from "@/db/schema";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
import { localToUtc } from "@/lib/tz";
|
||||
import {
|
||||
planInstances,
|
||||
windowTarget,
|
||||
INSTANCE_WINDOW_WEEKS,
|
||||
type ServicePlanInput,
|
||||
} from "@/domain/instances";
|
||||
|
||||
export interface GenerateOptions {
|
||||
/** Reference "now". Defaults to the real clock; injectable for tests. */
|
||||
now?: Date;
|
||||
/** Rolling window in weeks (default 16). */
|
||||
windowWeeks?: number;
|
||||
}
|
||||
|
||||
export interface GenerateResult {
|
||||
created: number;
|
||||
windowWeeks: number;
|
||||
from: string;
|
||||
to: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotent instance generation. Returns the number of instances created on
|
||||
* this run (0 on a clean re-run). See module doc for the invariants.
|
||||
*/
|
||||
export async function generateInstances(opts: GenerateOptions = {}): Promise<GenerateResult> {
|
||||
const now = opts.now ?? new Date();
|
||||
const windowWeeks = opts.windowWeeks ?? INSTANCE_WINDOW_WEEKS;
|
||||
const target = windowTarget(now, windowWeeks);
|
||||
|
||||
const active = await db.select().from(services).where(eq(services.active, true));
|
||||
|
||||
let created = 0;
|
||||
for (const service of active) {
|
||||
const plan: ServicePlanInput = {
|
||||
rrule: service.rrule!,
|
||||
startTimeLocal: service.startTimeLocal,
|
||||
timezone: service.timezone!,
|
||||
durationMinutes: service.durationMinutes,
|
||||
};
|
||||
|
||||
for (const inst of planInstances(plan, now, target)) {
|
||||
// onConflictDoNothing + returning() yields only the rows this run
|
||||
// actually inserted, so `created` counts genuine additions.
|
||||
const [row] = await db
|
||||
.insert(serviceInstances)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
serviceId: service.id,
|
||||
occursOn: localToUtc(inst.occursOn, "00:00", service.timezone),
|
||||
startsAt: inst.startsAt,
|
||||
endsAt: inst.endsAt,
|
||||
status: "draft",
|
||||
})
|
||||
.onConflictDoNothing({
|
||||
target: [serviceInstances.serviceId, serviceInstances.startsAt],
|
||||
})
|
||||
.returning();
|
||||
if (row) created++;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
created,
|
||||
windowWeeks,
|
||||
from: now.toISOString(),
|
||||
to: target.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Count instances for a service within the rolling window (audit helper). */
|
||||
export async function countInstances(serviceId: string, now?: Date): Promise<number> {
|
||||
const start = (now ?? new Date()).toISOString();
|
||||
const [row] = await db
|
||||
.select({ count: count() })
|
||||
.from(serviceInstances)
|
||||
.where(
|
||||
and(
|
||||
eq(serviceInstances.serviceId, serviceId),
|
||||
gte(serviceInstances.startsAt, new Date(start)),
|
||||
),
|
||||
);
|
||||
return Number(row?.count ?? 0);
|
||||
}
|
||||
Reference in New Issue
Block a user