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:
Tiel Coder
2026-11-18 05:17:11 +00:00
parent 6a778aa2f6
commit 8fb6459b0d
5 changed files with 306 additions and 0 deletions
+88
View File
@@ -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");
});
});
+70
View File
@@ -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),
};
});
}