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,15 @@
|
||||
import { generateInstances } from "@/db/instances";
|
||||
|
||||
/**
|
||||
* Daily instance generator (ARCHITECTURE §5.1). Cron `0 6 * * *` (church-local
|
||||
* 06:00, expressed in UTC) calls this. Idempotent — a re-run creates 0 rows.
|
||||
*
|
||||
* GET /api/dev/cron/instances
|
||||
*/
|
||||
export const GET = async () => {
|
||||
const result = await generateInstances();
|
||||
return new Response(JSON.stringify({ result }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { planInstances, windowTarget, INSTANCE_WINDOW_WEEKS } from "./instances";
|
||||
|
||||
const TZ = "America/New_York";
|
||||
|
||||
const weeklyService = {
|
||||
rrule: "FREQ=WEEKLY;BYDAY=SU",
|
||||
startTimeLocal: "09:00",
|
||||
timezone: TZ,
|
||||
durationMinutes: 75,
|
||||
};
|
||||
|
||||
/** YYYY-MM-DD of a UTC instant rendered in the church timezone. */
|
||||
const localDay = (d: Date) =>
|
||||
`${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(
|
||||
d.getUTCDate(),
|
||||
).padStart(2, "0")}`;
|
||||
|
||||
describe("planInstances — window boundary", () => {
|
||||
it("emits exactly the Sundays in [now, now + 3 weeks]", () => {
|
||||
const now = new Date(Date.UTC(2026, 2, 1, 12, 0, 0)); // 2026-03-01 (a Sunday)
|
||||
const target = windowTarget(now, 3);
|
||||
const plan = planInstances(weeklyService, now, target);
|
||||
const days = plan.map((i) => i.occursOn);
|
||||
expect(days).toEqual(["2026-03-01", "2026-03-08", "2026-03-15", "2026-03-22"]);
|
||||
});
|
||||
|
||||
it("endsAt is start + duration", () => {
|
||||
const now = new Date(Date.UTC(2026, 2, 1, 12, 0, 0));
|
||||
const target = windowTarget(now, 1);
|
||||
const [first] = planInstances(weeklyService, now, target);
|
||||
expect((first.endsAt.getTime() - first.startsAt.getTime()) / 60_000).toBe(75);
|
||||
});
|
||||
});
|
||||
|
||||
describe("planInstances — DST-safe instants", () => {
|
||||
it("keeps 9 AM local across the spring-forward Sunday", () => {
|
||||
// 2026-03-01 is EST; 2026-03-08 is the spring-forward Sunday (EDT).
|
||||
const now = new Date(Date.UTC(2026, 2, 1, 12, 0, 0));
|
||||
const target = windowTarget(now, 2);
|
||||
const plan = planInstances(weeklyService, now, target);
|
||||
const before = plan.find((i) => i.occursOn === "2026-03-01")!;
|
||||
const after = plan.find((i) => i.occursOn === "2026-03-08")!;
|
||||
expect(before.startsAt.getUTCHours()).toBe(14); // 09:00 EST (UTC-5)
|
||||
expect(after.startsAt.getUTCHours()).toBe(13); // 09:00 EDT (UTC-4)
|
||||
});
|
||||
});
|
||||
|
||||
describe("planInstances — deterministic (drives idempotent upsert)", () => {
|
||||
it("produces the same instants for identical input", () => {
|
||||
const now = new Date(Date.UTC(2026, 2, 1, 12, 0, 0));
|
||||
const target = windowTarget(now, 2);
|
||||
const a = planInstances(weeklyService, now, target);
|
||||
const b = planInstances(weeklyService, now, target);
|
||||
expect(a.map((i) => i.startsAt.getTime())).toEqual(b.map((i) => i.startsAt.getTime()));
|
||||
expect(a.map((i) => i.occursOn)).toEqual(b.map((i) => i.occursOn));
|
||||
});
|
||||
});
|
||||
|
||||
describe("planInstances — biweekly phase", () => {
|
||||
it("lands every other Sunday on a stable phase", () => {
|
||||
const service = { ...weeklyService, rrule: "FREQ=WEEKLY;INTERVAL=2;BYDAY=SU" };
|
||||
const now = new Date(Date.UTC(2026, 0, 4, 12, 0, 0)); // 2026-01-04 (anchor Sunday)
|
||||
const target = windowTarget(now, 3);
|
||||
const days = planInstances(service, now, target).map((i) => i.occursOn);
|
||||
expect(days).toEqual(["2026-01-04", "2026-01-18"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("planInstances — monthly nth weekday", () => {
|
||||
it("plans the 1st Sunday across a year boundary", () => {
|
||||
const service = { ...weeklyService, rrule: "FREQ=MONTHLY;BYDAY=1SU" };
|
||||
const now = new Date(Date.UTC(2026, 11, 1, 12, 0, 0)); // 2026-12-01
|
||||
const target = windowTarget(now, 10);
|
||||
const days = planInstances(service, now, target).map((i) => i.occursOn);
|
||||
expect(days).toEqual(["2026-12-06", "2027-01-03", "2027-02-07"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("windowTarget", () => {
|
||||
it("defaults to a 16-week window", () => {
|
||||
const now = new Date(Date.UTC(2026, 0, 1, 12, 0, 0));
|
||||
const target = windowTarget(now);
|
||||
expect(INSTANCE_WINDOW_WEEKS).toBe(16);
|
||||
// 16 weeks = 112 days from Jan 1.
|
||||
expect(localDay(target)).toBe("2026-04-23");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Instance planning — unit D2 (ARCHITECTURE §5.1).
|
||||
*
|
||||
* Pure: no DB, no `src/db` imports. `planInstances()` turns a service's
|
||||
* recurrence rule into the list of UTC instants it should occur at inside a
|
||||
* rolling window. The data layer (`src/db/instances.ts`) upserts these; the
|
||||
* cron route drives the upsert daily.
|
||||
*
|
||||
* DST is resolved per instant by `localToUtc`: a 9:00 AM Sunday stays 9:00 AM
|
||||
* local across spring-forward / fall-back, so the stored UTC shifts by an hour
|
||||
* at each transition. We never add 24h to walk a window.
|
||||
*/
|
||||
|
||||
import { expandRRULE } from "./recurrence";
|
||||
import { dateInTimezone, localToUtc } from "@/lib/tz";
|
||||
|
||||
export interface ServicePlanInput {
|
||||
rrule: string;
|
||||
startTimeLocal: string;
|
||||
timezone: string;
|
||||
durationMinutes: number;
|
||||
}
|
||||
|
||||
export interface PlannedInstance {
|
||||
/** Local date, e.g. `2026-03-01` (church timezone). */
|
||||
occursOn: string;
|
||||
/** UTC instant the service starts (DST-safe). */
|
||||
startsAt: Date;
|
||||
/** UTC instant the service ends. */
|
||||
endsAt: Date;
|
||||
}
|
||||
|
||||
/** Default rolling window kept by the cron generator. */
|
||||
export const INSTANCE_WINDOW_WEEKS = 16;
|
||||
|
||||
/**
|
||||
* The far edge of the rolling window: `now` + `weeks` (default 16). Computed in
|
||||
* UTC days — the window edge is approximate, so a DST hour at the boundary is
|
||||
* irrelevant.
|
||||
*/
|
||||
export function windowTarget(now: Date, weeks = INSTANCE_WINDOW_WEEKS): Date {
|
||||
const target = new Date(now);
|
||||
target.setUTCDate(target.getUTCDate() + weeks * 7);
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan every instance of `service` that falls in [now, target]. Local dates
|
||||
* come from `expandRRULE`; instants from `localToUtc`. Deterministic for a
|
||||
* fixed (service, now, target) — re-planning yields the same list, which is
|
||||
* what makes the upsert idempotent.
|
||||
*/
|
||||
export function planInstances(
|
||||
service: ServicePlanInput,
|
||||
now: Date,
|
||||
target: Date,
|
||||
): PlannedInstance[] {
|
||||
const from = dateInTimezone(now, service.timezone);
|
||||
const to = dateInTimezone(target, service.timezone);
|
||||
const durationMs = service.durationMinutes * 60_000;
|
||||
|
||||
return expandRRULE(service.rrule, from, to).map((occursOn) => {
|
||||
const startsAt = localToUtc(occursOn, service.startTimeLocal, service.timezone);
|
||||
return {
|
||||
occursOn,
|
||||
startsAt,
|
||||
endsAt: new Date(startsAt.getTime() + durationMs),
|
||||
};
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user