perf(medications): one compliance round trip and a memoised formatter hot path

Intl.DateTimeFormat instances are memoised per locale, timezone and
options signature — construction dominated the 365-day ledger build and
the hot path drops about fivefold. A batched GET /api/medications/compliance
serves every card from one request through the same per-medication cache
cells the detail page reads, replacing the per-card fan-out; the list
response stays untouched so the due line never waits on a ledger build.
The medications and compliance buckets serve stale-while-revalidate,
interactive writes evict while background bulk sync marks stale, the
per-id route defers ownership and schedule reads until a cache miss,
and the card body reserves constant slots for the status and cycle
lines so late data stops shifting the layout.
This commit is contained in:
Marc-André Bombeck committed 2026-06-11 21:17:17 +02:00
1 parent 23f7c74c04
commit b346e78cc7
36 files changed
+1453 -500

No files matched your search

+51
View File
@@ -213,6 +213,57 @@ describe("invalidateUserMedications", () => {
caches.medicationCompliance.get(`${USER_B}|med-1|compliance`),
).not.toBeNull();
});
it("marks the SWR buckets stale by default — background sync posture", async () => {
await primeAllCaches();
invalidateUserMedications(USER_A);
// v1.16.8 — the default (bulk sync / cron) path marks stale: the
// entries are gone for plain `get()` (asserted above) but stay
// serveable for the `cachedSwr` readers (medications list, both
// compliance routes, the dashboard snapshot), so a high-frequency
// iOS sync never busts every card into an inline cold rebuild.
expect(caches.medications.getAllowStale(USER_A)).toEqual({
value: { m: 1 },
stale: true,
});
expect(
caches.medicationCompliance.getAllowStale(`${USER_A}|med-1|compliance`),
).toEqual({ value: { mc: 1 }, stale: true });
expect(
caches.analytics.getAllowStale(dashboardSnapshotCacheKey(USER_A)),
).toEqual({ value: { snap: 1 }, stale: true });
// User B stays fresh.
expect(caches.medications.getAllowStale(USER_B)).toEqual({
value: { m: 2 },
stale: false,
});
});
it("hard-evicts the SWR buckets with { evict: true } — interactive write posture", async () => {
await primeAllCaches();
invalidateUserMedications(USER_A, { evict: true });
// v1.16.8 — an interactive take / skip / CRUD write must NOT leave a
// stale-serveable body behind: the SWR readers would hand the user
// back the pre-write card rates. The evict drops the entries.
expect(caches.medications.getAllowStale(USER_A)).toBeNull();
expect(
caches.medicationCompliance.getAllowStale(`${USER_A}|med-1|compliance`),
).toBeNull();
expect(
caches.analytics.getAllowStale(dashboardSnapshotCacheKey(USER_A)),
).toBeNull();
// User B stays warm; the non-SWR buckets evict as before.
expect(caches.medications.getAllowStale(USER_B)).not.toBeNull();
expect(
caches.medicationCompliance.getAllowStale(`${USER_B}|med-1|compliance`),
).not.toBeNull();
expect(caches.medicationsIntake.get(`${USER_A}|compliance|30`)).toBeNull();
expect(caches.achievements.get(USER_A)).toBeNull();
});
});
describe("invalidateUserDashboardWidgets", () => {
+39 -12
View File
@@ -117,24 +117,51 @@ export function invalidateUserMood(userId: string): void {
* Invalidate every cache that may reflect a user's medication state.
*
* Covers the medications cache, the medication-intake compliance cache
* (cached daily), and achievement progress.
* (cached daily), the per-medication compliance payload, and achievement
* progress.
*
* v1.16.8 — `evict` splits the SWR buckets (medications, the
* per-medication compliance payload, analytics) by write origin, the
* `invalidateUserMeasurements` pattern. Interactive writes (a card take /
* skip, a CRUD edit, an intake edit / delete / purge / import) pass
* `{ evict: true }`: the user must see their own action on the very next
* read, and a stale-serveable entry would hand back the pre-write body.
* Background paths (the iOS bulk-intake sync, the auto-miss cron, slot
* dedup) keep the default mark-stale so a high-frequency sync never busts
* the buckets into inline cold-rebuild storms — the `cachedSwr` readers
* serve the prior payload while one coalesced recompute warms each cell.
*/
export function invalidateUserMedications(userId: string): void {
caches.medications.deleteByPrefix(userId);
export function invalidateUserMedications(
userId: string,
opts?: { evict?: boolean },
): void {
if (opts?.evict) {
caches.medications.deleteByPrefix(userId);
// v1.15.20 — the per-medication compliance payload is cached 15 min;
// an interactive intake / medication / schedule write must flush it
// so the card rates and the heatmap reflect the action on the next
// read.
caches.medicationCompliance.deleteByPrefix(`${userId}|`);
// v1.4.38 W-F — `/api/dashboard/summary` lives under the analytics
// cache and reads `medicationIntakeEvent` for both today's compliance
// tally and the 365-day streak feed. A taken / skipped event must
// evict the user-bucket so the next iOS poll reflects the change.
caches.analytics.deleteByPrefix(`${userId}|`);
} else {
// Mark-stale collapses the fresh TTL to "now": the SWR readers (the
// medications list, both compliance routes, the dashboard snapshot)
// serve the prior value while a single background recompute warms a
// fresh one; the plain `cached` readers in the analytics bucket see
// a clean miss — identical to the old evict for those keys.
caches.medications.markStaleByPrefix(userId);
caches.medicationCompliance.markStaleByPrefix(`${userId}|`);
caches.analytics.markStaleByPrefix(`${userId}|`);
}
caches.medicationsIntake.deleteByPrefix(`${userId}|`);
// v1.15.20 — the per-medication compliance payload is cached 15 min;
// every intake / medication / schedule write must flush it so the card
// rates and the heatmap reflect the action on the next read.
caches.medicationCompliance.deleteByPrefix(`${userId}|`);
caches.achievements.deleteByPrefix(userId);
// v1.4.36 W1 — medication writes change the MEDICATION_COMPLIANCE
// target rollup (compliance7 / compliance30 / consistency strip).
caches.insightsTargets.deleteByPrefix(userId);
// v1.4.38 W-F — `/api/dashboard/summary` lives under the analytics
// cache and reads `medicationIntakeEvent` for both today's compliance
// tally and the 365-day streak feed. A taken / skipped event must
// evict the user-bucket so the next iOS poll reflects the change.
caches.analytics.deleteByPrefix(`${userId}|`);
}
/**
+22
View File
@@ -363,10 +363,22 @@ export const caches = {
ttlMs: 60_000,
staleTtlMs: 600_000,
}),
/**
* v1.16.8 — stale-while-revalidate on the list bucket. The 60 s fresh
* TTL meant every visit minutes apart paid the full cold list build
* (five parallel reads + the next-due engine per medication). The list
* GET reads via `cachedSwr` now: inside the 10-minute stale window the
* prior list serves immediately while one background recompute warms a
* fresh one. Interactive writes hard-evict the bucket through
* `invalidateUserMedications({ evict: true })`, so the window only
* bounds wall-clock drift (`todayEventCount`, `nextDueAt`), never
* user-action staleness.
*/
medications: new ServerCache<unknown>({
name: "medications",
maxEntries: 1000,
ttlMs: 60_000,
staleTtlMs: 600_000,
}),
achievements: new ServerCache<unknown>({
name: "achievements",
@@ -405,11 +417,21 @@ export const caches = {
* `invalidateUserMedications`, so the 15-minute TTL only bounds
* wall-clock drift (a dose flipping overdue), never user-action
* staleness. Sized for a few hundred users × a handful of meds.
*
* v1.16.8 — stale-while-revalidate. Both compliance routes (the per-id
* detail read and the batched card read) consume via `cachedSwr`:
* inside the 10-minute stale window an expired cell serves the prior
* payload immediately while one coalesced rebuild warms it. Interactive
* intake / medication writes hard-evict (the user must see their own
* dose on the next read); background sync paths (iOS bulk intake, the
* auto-miss cron, slot dedup) mark stale so a high-frequency sync never
* busts every card into an inline cold rebuild.
*/
medicationCompliance: new ServerCache<unknown>({
name: "medicationCompliance",
maxEntries: 2000,
ttlMs: 900_000,
staleTtlMs: 600_000,
}),
moodAnalytics: new ServerCache<unknown>({
name: "moodAnalytics",
+240
View File
@@ -0,0 +1,240 @@
/**
* The full compliance computation for one medication, shared by
* `GET /api/medications/[id]/compliance` (detail page, full payload incl.
* the 90-day heatmap) and `GET /api/medications/compliance` (the batched
* card read). Lifted out of the per-id route so the server cache can wrap
* one canonical builder from both entry points: ONE bounded intake-event
* read (only the columns the math consumes, floored at the 366-day fetch
* window) feeds ONE shared band-expansion pass
* (`buildMedicationComplianceBundle`) that serves the 7-/30-day blocks,
* the cadence-scaled display rows AND the 90-day heatmap.
*/
import { prisma } from "@/lib/db";
import {
buildComplianceMedicationContext,
buildMedicationComplianceBundle,
lastNonSkippedTakenAt,
type ComplianceDisplay,
type ComplianceResult,
type DailyComplianceEntry,
} from "@/lib/analytics/compliance";
import type { DoseHistoryRow } from "@/lib/medications/scheduling/dose-history";
import { userDayKey } from "@/lib/tz/format";
const DAY_MS = 24 * 60 * 60 * 1000;
/**
* Lower bound for the intake-event read. The widest window any served
* block needs is the 365-day display rung; one extra day absorbs the
* inclusive-boundary edge so the ledger's own 365-day clamp never sits
* on a half-fetched day.
*/
const EVENT_FETCH_WINDOW_DAYS = 366;
/** The cached response body (the exact public wire shape). */
export interface CompliancePayload {
compliance7: ComplianceResult;
compliance30: ComplianceResult;
dailyCompliance: Record<string, DailyComplianceEntry>;
complianceDisplay: ComplianceDisplay;
}
/** The medication slice the payload builder consumes. */
export interface ComplianceMedicationInput {
id: string;
createdAt: Date;
startsOn: Date | null;
endsOn: Date | null;
oneShot: boolean;
schedules: Parameters<typeof buildMedicationComplianceBundle>[1];
/** v1.16.3 — archived schedule eras for era-aware compliance. */
scheduleRevisions?: Parameters<
typeof buildComplianceMedicationContext
>[0]["scheduleRevisions"];
}
/**
* One canonical cache key per `(user, medication, timezone)` cell. The
* key carries the timezone the payload was bucketed in: day keys, the
* heatmap, and the overdue cut all derive from `userTz`, so a timezone
* change must miss the old entry instead of serving day buckets computed
* for the previous zone until the TTL lapses. The `${userId}|` prefix is
* what `invalidateUserMedications` sweeps.
*/
export function complianceCacheKey(
userId: string,
medicationId: string,
userTz: string,
): string {
return `${userId}|${medicationId}|compliance|${userTz}`;
}
/**
* v1.15.18 — fold one dose-history ledger row into a per-day heatmap entry.
*
* Slot rows contribute to `expected` / `expectedCount` (the day's due-slot
* count): a taken slot adds to `taken` and its timing bucket; a missed slot
* stays uncounted in `taken`; a skipped slot lands in `skipped`; an upcoming
* slot is still due but not yet acted on. An ad-hoc row is a real off-schedule
* take — it counts as `taken` AND adds its own `expected` slot (so the
* heatmap's `missed = expected − taken − skipped` math stays non-negative) and
* reads on-time (a logged dose colours green).
*/
function bucketLedgerRow(
entry: DailyComplianceEntry,
row: DoseHistoryRow,
): void {
switch (row.status) {
case "taken_on_time":
entry.expected++;
entry.expectedCount++;
entry.taken++;
entry.onTime++;
break;
case "taken_late":
entry.expected++;
entry.expectedCount++;
entry.taken++;
entry.late++;
break;
case "missed":
entry.expected++;
entry.expectedCount++;
break;
case "skipped":
entry.expected++;
entry.expectedCount++;
entry.skipped++;
break;
case "upcoming":
// A future / still-takeable slot is due but not yet acted on. It counts
// toward the day's expected/due grid but not toward taken or missed.
entry.expected++;
entry.expectedCount++;
break;
case "ad_hoc":
// An off-schedule take: a real taken dose with no scheduled slot. Count
// it as taken + its own expected slot so the heatmap missed math holds.
entry.expected++;
entry.expectedCount++;
entry.taken++;
entry.onTime++;
break;
}
}
export async function buildCompliancePayload(
medication: ComplianceMedicationInput,
userId: string,
userTz: string,
): Promise<CompliancePayload> {
// v1.15.9 — pin a single `now` and thread it into every cadence
// computation so no block can straddle a day boundary on a slow request.
const now = new Date();
const createdAt = medication.createdAt;
const fetchFrom = new Date(
Math.max(
createdAt.getTime(),
now.getTime() - EVENT_FETCH_WINDOW_DAYS * DAY_MS,
),
);
const events = await prisma.medicationIntakeEvent.findMany({
// v1.7.0 sync — exclude tombstoned rows from the compliance read.
// Bounded to the 366-day fetch window: every served block is a suffix
// of the 365-day ledger window, so older rows can never change the
// response.
where: {
medicationId: medication.id,
userId,
deletedAt: null,
scheduledFor: { gte: fetchFrom },
},
orderBy: { scheduledFor: "desc" },
select: {
takenAt: true,
skipped: true,
scheduledFor: true,
// v1.15.9 — a forgotten dose the auto-miss cron flipped counts as a
// miss, not a neutral skip.
autoMissed: true,
// v1.15.20 — pinned takes bind by anchor in the unified ledger so the
// % agrees with the history view on a "zugeordnet" dose (taken-late).
attributionSource: true,
},
});
// v1.7.0 SB-SCHED-2 — thread the medication context so the denominator
// routes through the canonical engine (RRULE / rolling / one-shot / PRN /
// cyclic). `lastIntakeAt` is the latest non-skipped takenAt inside the
// fetch window (rolling cadences re-anchor on it).
const lastIntakeAt = lastNonSkippedTakenAt(events);
const medicationContext = buildComplianceMedicationContext(
medication,
lastIntakeAt,
userTz,
);
// ONE shared expansion pass for every served block (the v1.15.20
// performance fix): bands + ledger + timeline are minted once over the
// widest window and each sub-window is a tally over the same rows.
const bundle = buildMedicationComplianceBundle(
events,
medication.schedules,
medicationContext,
now,
);
// v1.15.18 — the heatmap / line-chart daily map is bucketed from the ONE
// unified dose-history ledger (the same bands the % + the history view
// read), so the per-day timing split (on-time / late) and the per-day
// missed marks can never disagree with the headline rate. The 90-day
// window is carved out of the shared ledger by `row.at`; the window
// floor clamps to the medication's creation so pre-existence days never
// mint phantom slots.
const heatmapFrom = new Date(
Math.max(now.getTime() - 90 * DAY_MS, createdAt.getTime()),
);
const dailyCompliance: Record<string, DailyComplianceEntry> = {};
const byDay = new Map<string, DailyComplianceEntry>();
const ensureDay = (key: string): DailyComplianceEntry => {
let entry = byDay.get(key);
if (!entry) {
entry = {
expected: 0,
expectedCount: 0,
due: false,
taken: 0,
skipped: 0,
onTime: 0,
late: 0,
veryLate: 0,
early: 0,
};
byDay.set(key, entry);
}
return entry;
};
// Bucket each ledger row into its user-tz day. A slot row buckets on its
// anchor; an ad-hoc row on its real take time.
for (const row of bundle.ledgerRows) {
if (row.at.getTime() < heatmapFrom.getTime()) continue;
const key = userDayKey(row.at, userTz);
const entry = ensureDay(key);
bucketLedgerRow(entry, row);
}
for (const [key, entry] of byDay) {
entry.due = entry.expectedCount > 0;
dailyCompliance[key] = entry;
}
return {
compliance7: bundle.compliance7,
compliance30: bundle.compliance30,
dailyCompliance,
complianceDisplay: bundle.complianceDisplay,
};
}
+35
View File
@@ -507,6 +507,19 @@ const medicationComplianceResponse = z
"Adherence read for a single medication. `compliance30` is the authoritative 30-day taken-vs-expected summary; `dailyCompliance` is the per-day grid for the history glyph track. The graded raw→week→month→year series used elsewhere for AI prompts does NOT apply here — this response is never downsampled.",
});
const medicationComplianceSummaryEntry = z
.object({
medicationId: z.string(),
compliance7: complianceResult,
compliance30: complianceResult,
complianceDisplay,
})
.meta({
id: "MedicationComplianceSummaryEntry",
description:
"Compact per-medication adherence row for the batched card read: the 7-/30-day summaries plus the cadence-scaled display block. The per-day `dailyCompliance` grid is NOT on this shape — read the per-medication `/compliance` endpoint for the history glyph track.",
});
// v1.16.5 — schedule-era management (the Zeitplan-tab history timeline).
// Archived eras come from two provenances: the wholesale-replace write
// path (`ARCHIVED`, immutable) and the user-entered pre-tracking flow
@@ -856,6 +869,28 @@ export const medicationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/medications/compliance": {
get: {
tags: ["Medications"],
summary: "Batched adherence read for every medication of the caller",
description:
"Returns one compact adherence row per medication the caller owns (active + paused), ordered by `createdAt DESC` — the single round trip the medication cards consume instead of fanning out one `/api/medications/{id}/compliance` request per card. Each row carries the 7-/30-day summaries and the cadence-scaled display block; the per-day grid stays on the per-medication endpoint. Pure computation — no writes. Served through the same per-medication server cache as the per-id read, so the two endpoints warm each other.",
responses: {
"200": {
description: "One adherence row per medication.",
content: {
"application/json": {
schema: dataEnvelope(
z.array(medicationComplianceSummaryEntry),
"ListMedicationComplianceResponse",
),
},
},
},
...stdResponses,
},
},
},
"/api/medications/{id}/compliance": {
get: {
tags: ["Medications"],
+16 -2
View File
@@ -12,11 +12,20 @@ import { apiGet } from "@/lib/api/api-fetch";
* puts `/api/medications` (the response carries the per-medication
* `nextDueAt` due times) in flight while the navigation commits.
*
* v1.16.8 — the batched card-compliance read
* (`/api/medications/compliance`) prefetches alongside the list, so the
* compliance bars + the status line resolve in the same paint as the
* cards instead of swapping in late. Two independent requests on
* purpose: the list response must stay fast (the due line never waits
* on a compliance ledger build), and the compliance prefetch rides the
* same server-side cache cells the page query would warm anyway.
*
* The 15 s prefetch window only bounds how old a cache entry may be
* before an intent re-fires the request — the mounted page query rides
* the provider-default `staleTime` (5 min) and consumes whatever this
* prefetch parked. The server caches the list 60 s per user, so even a
* missed window stays cheap.
* prefetch parked. The server caches both reads per user (60 s list /
* 15 min compliance, each with an SWR window), so even a missed window
* stays cheap.
*/
export const MEDICATIONS_LIST_STALE_TIME_MS = 15_000;
@@ -26,6 +35,11 @@ export function prefetchMedicationsList(queryClient: QueryClient): void {
queryFn: () => apiGet("/api/medications"),
staleTime: MEDICATIONS_LIST_STALE_TIME_MS,
});
void queryClient.prefetchQuery({
queryKey: queryKeys.medicationComplianceSummary(),
queryFn: () => apiGet("/api/medications/compliance"),
staleTime: MEDICATIONS_LIST_STALE_TIME_MS,
});
}
/**
@@ -0,0 +1,61 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { apiGet } from "@/lib/api/api-fetch";
import { queryKeys } from "@/lib/query-keys";
import type { ComplianceDisplay } from "@/lib/analytics/compliance";
/**
* One batched-summary row — the compact slice of the per-medication
* compliance payload the cards render (rates, streak, the cadence-scaled
* display block with `currentDose` / `currentCycle`). The heavy
* `dailyCompliance` heatmap stays on the per-id endpoint the detail page
* reads.
*/
export interface MedicationComplianceSummaryEntry {
medicationId: string;
compliance7: { rate: number; streak: number };
compliance30: { rate: number };
complianceDisplay?: ComplianceDisplay;
}
/**
* v1.16.8 — the per-card compliance read, batched.
*
* Every medication card used to fire its own
* `GET /api/medications/{id}/compliance` (N+1 over the grid, ~1 s cold
* each). All cards now share ONE `GET /api/medications/compliance`
* round trip under a single query key; each card `select`s its own row,
* so a grid of mounted cards collapses into one request and one cache
* entry. The key rides the `["medications"]` prefix, so every intake /
* CRUD mutation that invalidates `medicationDependentKeys` refreshes it.
*
* Lives in one shared hook (not per-card `useQuery` calls) so the two
* card variants can never register the same key with diverging fetch
* shapes.
*/
export function useMedicationComplianceSummary(medicationId: string): {
data: MedicationComplianceSummaryEntry | null | undefined;
} {
const { data } = useQuery({
queryKey: queryKeys.medicationComplianceSummary(),
queryFn: async () => {
try {
return await apiGet<MedicationComplianceSummaryEntry[]>(
"/api/medications/compliance",
);
} catch {
return null;
}
},
// Dose actions invalidate the key explicitly through
// `medicationDependentKeys`; a shorter window would only re-fire the
// batch on every list visit. Matches the reminder-thresholds query
// the cards mount alongside.
staleTime: 5 * 60 * 1000,
select: (rows: MedicationComplianceSummaryEntry[] | null) =>
rows?.find((row) => row.medicationId === medicationId) ?? null,
});
return { data };
}
+12
View File
@@ -16,6 +16,18 @@ export const medicationKeys = {
*/
medicationCompliance: (medicationId: string) =>
["medications", medicationId, "compliance"] as const,
/**
* v1.16.8 — the batched card-compliance read
* (`GET /api/medications/compliance`, one round trip for every card on
* the medications page). Replaces the per-card fan-out over the per-id
* endpoint; `medicationCompliance(id)` above stays for the detail page,
* which needs the per-id payload's heatmap grid. Rides under the
* `["medications"]` prefix so every intake / CRUD mutation reaches it
* through `medicationDependentKeys`. The static second segment cannot
* collide with `medicationDetail(id)` — ids are cuids.
*/
medicationComplianceSummary: () =>
["medications", "compliance-summary"] as const,
medicationCadence: (medicationId: string) =>
["medications", medicationId, "cadence"] as const,
medicationGlp1Details: (medicationId: string) =>
+185
View File
@@ -0,0 +1,185 @@
/**
* v1.16.8 — memoised `Intl.DateTimeFormat` construction.
*
* Constructing a formatter dominates the CPU cost of the wall-clock
* helpers (band expansion calls them in a tight loop), so the memo must
* (a) return byte-identical output to a freshly constructed formatter
* for every timezone / option shape the tz helpers use, and (b) actually
* share one instance per signature.
*/
import { describe, it, expect, beforeEach } from "vitest";
import {
getDateTimeFormat,
__resetIntlCacheForTests,
__intlCacheSizeForTests,
} from "../intl-cache";
import { wallClockInTz } from "../wall-clock";
import { formatInUserTz, userDayKey, isValidTimezone } from "../format";
import { getUserTodayBounds, localHmAsUtc } from "../local-day";
const ZONES = [
"UTC",
"Europe/Berlin",
"America/New_York",
"Asia/Tokyo",
"Pacific/Kiritimati", // +14, no DST
"America/St_Johns", // -03:30 fractional offset
];
// Instants chosen to straddle DST transitions and a midnight boundary.
const INSTANTS = [
new Date("2026-01-15T03:30:00Z"),
new Date("2026-03-29T01:30:00Z"), // EU spring-forward window
new Date("2026-06-10T23:45:00Z"),
new Date("2026-10-25T01:30:00Z"), // EU fall-back window
];
beforeEach(() => {
__resetIntlCacheForTests();
});
describe("getDateTimeFormat", () => {
it("matches a freshly constructed formatter across zones and option shapes", () => {
const optionShapes: Omit<Intl.DateTimeFormatOptions, "timeZone">[] = [
{
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
weekday: "short",
},
{
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
},
{ hour: "2-digit", minute: "2-digit", hour12: false },
];
for (const tz of ZONES) {
for (const options of optionShapes) {
const memoised = getDateTimeFormat("en-CA", tz, options);
const fresh = new Intl.DateTimeFormat("en-CA", {
...options,
timeZone: tz,
});
for (const instant of INSTANTS) {
expect(memoised.format(instant)).toBe(fresh.format(instant));
expect(memoised.formatToParts(instant)).toEqual(
fresh.formatToParts(instant),
);
}
}
}
});
it("returns the same instance for the same (locale, timeZone, options) signature", () => {
const options = {
hour: "2-digit",
minute: "2-digit",
hour12: false,
} as const;
const a = getDateTimeFormat("en-GB", "Europe/Berlin", options);
const b = getDateTimeFormat("en-GB", "Europe/Berlin", options);
expect(a).toBe(b);
// A structurally equal but distinct options object still hits the
// same cache cell (signature-keyed, not identity-keyed).
const c = getDateTimeFormat("en-GB", "Europe/Berlin", {
hour: "2-digit",
minute: "2-digit",
hour12: false,
} as const);
expect(c).toBe(a);
});
it("splits cells on locale, timezone, and options", () => {
const options = {
hour: "2-digit",
minute: "2-digit",
hour12: false,
} as const;
const base = getDateTimeFormat("en-GB", "Europe/Berlin", options);
expect(getDateTimeFormat("en-US", "Europe/Berlin", options)).not.toBe(base);
expect(getDateTimeFormat("en-GB", "Asia/Tokyo", options)).not.toBe(base);
expect(
getDateTimeFormat("en-GB", "Europe/Berlin", {
hour: "2-digit",
minute: "2-digit",
hour12: true,
} as const),
).not.toBe(base);
expect(__intlCacheSizeForTests()).toBe(4);
});
it("throws on an invalid timezone without caching the failure", () => {
expect(() => getDateTimeFormat("en-US", "Not/AZone", {})).toThrow();
expect(__intlCacheSizeForTests()).toBe(0);
});
});
describe("memoised consumers stay output-identical to the pre-memo helpers", () => {
it("wallClockInTz decomposes DST-transition instants correctly", () => {
// 2026-03-29 01:30 UTC = 03:30 CEST (the EU spring-forward morning).
const parts = wallClockInTz(new Date("2026-03-29T01:30:00Z"), "Europe/Berlin");
expect(parts).toEqual({
year: 2026,
month: 3,
day: 29,
hour: 3,
minute: 30,
second: 0,
weekday: 0,
});
// Same instant read from Tokyo.
const tokyo = wallClockInTz(new Date("2026-03-29T01:30:00Z"), "Asia/Tokyo");
expect(tokyo).toEqual({
year: 2026,
month: 3,
day: 29,
hour: 10,
minute: 30,
second: 0,
weekday: 0,
});
});
it("formatInUserTz keeps every shape stable across repeat (memo-warm) calls", () => {
const instant = new Date("2026-06-10T23:45:00Z");
for (let i = 0; i < 2; i++) {
expect(formatInUserTz(instant, "Europe/Berlin", "iso-with-offset")).toBe(
"2026-06-11T01:45:00+02:00",
);
expect(formatInUserTz(instant, "Europe/Berlin", "wall-clock")).toBe(
"01:45",
);
expect(formatInUserTz(instant, "Europe/Berlin", "date")).toBe(
"2026-06-11",
);
expect(userDayKey(instant, "America/New_York")).toBe("2026-06-10");
}
});
it("getUserTodayBounds + localHmAsUtc agree with the wall-clock read", () => {
const now = new Date("2026-06-10T23:45:00Z"); // 01:45 on the 11th in Berlin
const { start, end } = getUserTodayBounds(now, "Europe/Berlin");
expect(start.toISOString()).toBe("2026-06-10T22:00:00.000Z");
expect(end.toISOString()).toBe("2026-06-11T21:59:59.999Z");
const eight = localHmAsUtc(now, "Europe/Berlin", 8, 0);
expect(eight.toISOString()).toBe("2026-06-11T06:00:00.000Z");
});
it("isValidTimezone accepts real zones and rejects junk through the memo", () => {
expect(isValidTimezone("Europe/Berlin")).toBe(true);
expect(isValidTimezone("Pacific/Kiritimati")).toBe(true);
expect(isValidTimezone("Not/AZone")).toBe(false);
expect(isValidTimezone("")).toBe(false);
});
});
+36 -27
View File
@@ -12,8 +12,35 @@
* lookup.
*/
import { getDateTimeFormat } from "./intl-cache";
export const DEFAULT_TIMEZONE = "Europe/Berlin";
/**
* Hoisted option constants so the formatter memo's WeakMap signature
* lookup hits the same object identity on every call — see
* `./intl-cache`. `WALL_CLOCK_PARTS_OPTIONS` is shared by
* `wallClockParts` AND `tzOffsetMinutes`, so both resolve to the SAME
* memoised formatter per timezone.
*/
const VALIDATION_OPTIONS: Omit<Intl.DateTimeFormatOptions, "timeZone"> = {};
const HOUR_MINUTE_OPTIONS: Omit<Intl.DateTimeFormatOptions, "timeZone"> = {
hour: "2-digit",
minute: "2-digit",
hour12: false,
};
const WALL_CLOCK_PARTS_OPTIONS: Omit<Intl.DateTimeFormatOptions, "timeZone"> = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
};
/**
* Validate a timezone string by asking `Intl.DateTimeFormat` to use it.
* Returns `true` if the runtime accepts the zone, `false` otherwise.
@@ -24,7 +51,10 @@ export function isValidTimezone(tz: string): boolean {
return false;
}
try {
new Intl.DateTimeFormat("en-US", { timeZone: tz });
// The memo only caches successful constructions, so probing an
// invalid zone through it cannot poison the formatter map — and a
// valid zone leaves its formatter warm for the real callers.
getDateTimeFormat("en-US", tz, VALIDATION_OPTIONS);
return true;
} catch {
return false;
@@ -133,12 +163,9 @@ export function formatInUserTz(
case "iso-with-offset":
return formatIsoWithOffset(date, safeTz);
case "wall-clock":
return new Intl.DateTimeFormat("en-GB", {
timeZone: safeTz,
hour: "2-digit",
minute: "2-digit",
hour12: false,
}).format(date);
return getDateTimeFormat("en-GB", safeTz, HOUR_MINUTE_OPTIONS).format(
date,
);
case "datetime": {
const parts = wallClockParts(date, safeTz);
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;
@@ -171,16 +198,7 @@ interface WallClockParts {
}
function wallClockParts(date: Date, tz: string): WallClockParts {
const fmt = new Intl.DateTimeFormat("en-CA", {
timeZone: tz,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
});
const fmt = getDateTimeFormat("en-CA", tz, WALL_CLOCK_PARTS_OPTIONS);
const parts = fmt.formatToParts(date);
const get = (type: Intl.DateTimeFormatPartTypes): string =>
parts.find((p) => p.type === type)?.value ?? "00";
@@ -223,16 +241,7 @@ function formatIsoWithOffset(date: Date, tz: string): string {
* difference between the wall-clock parts and the UTC parts.
*/
function tzOffsetMinutes(date: Date, tz: string): number {
const fmt = new Intl.DateTimeFormat("en-CA", {
timeZone: tz,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
});
const fmt = getDateTimeFormat("en-CA", tz, WALL_CLOCK_PARTS_OPTIONS);
const parts = fmt.formatToParts(date);
const get = (type: Intl.DateTimeFormatPartTypes): number =>
Number(parts.find((p) => p.type === type)?.value ?? "0");
+77
View File
@@ -0,0 +1,77 @@
/**
* Module-level memo for `Intl.DateTimeFormat` construction.
*
* Constructing a formatter resolves locale + timezone data on every call
* and dominates the CPU cost of the wall-clock helpers (~10x the
* `format` / `formatToParts` call it feeds). The instances are stateless
* for `format` / `formatToParts`, so one shared formatter per
* `(locale, timeZone, options)` signature is safe to hand to every
* caller — compliance band expansion, rollups, the dose-history ledger
* and the export formatters all hit the same small set of signatures.
*
* `timeZone` is a first-class key segment (not folded into `options`) so
* call sites can hoist their options object to a module constant; a
* WeakMap memoises that constant's serialised signature, leaving a warm
* lookup as two string concats + one Map get.
*/
const formatterCache = new Map<string, Intl.DateTimeFormat>();
/**
* Hard cap. The realistic population is bounded (valid IANA zones × a
* handful of option shapes), but the timezone segment is user-supplied
* upstream of validation in `isValidTimezone`, so the memo carries a
* safety valve: on overflow the whole map resets and re-warms.
*/
const MAX_FORMATTERS = 1000;
const signatureByOptions = new WeakMap<
Omit<Intl.DateTimeFormatOptions, "timeZone">,
string
>();
function optionsSignature(
options: Omit<Intl.DateTimeFormatOptions, "timeZone">,
): string {
const memoised = signatureByOptions.get(options);
if (memoised !== undefined) return memoised;
const record = options as Record<string, unknown>;
const signature = Object.keys(record)
.sort()
.map((key) => `${key}=${String(record[key])}`)
.join(",");
signatureByOptions.set(options, signature);
return signature;
}
/**
* Shared, memoised `Intl.DateTimeFormat`. Throws (like the constructor)
* on an invalid `timeZone` — failures are never cached, so
* `isValidTimezone` can probe through this without poisoning the map.
*/
export function getDateTimeFormat(
locale: string,
timeZone: string | undefined,
options: Omit<Intl.DateTimeFormatOptions, "timeZone"> = {},
): Intl.DateTimeFormat {
const key = `${locale}|${timeZone ?? ""}|${optionsSignature(options)}`;
const hit = formatterCache.get(key);
if (hit) return hit;
const formatter = new Intl.DateTimeFormat(
locale,
timeZone === undefined ? options : { ...options, timeZone },
);
if (formatterCache.size >= MAX_FORMATTERS) formatterCache.clear();
formatterCache.set(key, formatter);
return formatter;
}
/** Test-only escape hatch — clear the memo between assertions. */
export function __resetIntlCacheForTests(): void {
formatterCache.clear();
}
/** Test-only introspection — current memo population. */
export function __intlCacheSizeForTests(): number {
return formatterCache.size;
}
+22 -11
View File
@@ -18,6 +18,8 @@
* staying in lock-step; keeping them as separate definitions made
* silent drift a real failure mode.
*/
import { getDateTimeFormat } from "./intl-cache";
export interface WallClockParts {
year: number;
/** 1–12 (January = 1, December = 12). */
@@ -42,6 +44,23 @@ const WEEKDAY_MAP: Record<string, number> = {
Sat: 6,
};
/**
* Hoisted so the formatter memo's WeakMap signature lookup hits the same
* object identity on every call — a warm `wallClockInTz` no longer pays
* `Intl.DateTimeFormat` construction (the dominant cost of the band
* expansion + rollup paths that call this in a tight loop).
*/
const WALL_CLOCK_OPTIONS: Omit<Intl.DateTimeFormatOptions, "timeZone"> = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
weekday: "short",
};
export function wallClockInTz(
date: Date,
tz: string | undefined,
@@ -57,17 +76,9 @@ export function wallClockInTz(
weekday: date.getDay(),
};
}
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: tz,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
weekday: "short",
}).formatToParts(date);
const parts = getDateTimeFormat("en-US", tz, WALL_CLOCK_OPTIONS).formatToParts(
date,
);
const get = (type: Intl.DateTimeFormatPartTypes): string =>
parts.find((p) => p.type === type)?.value ?? "0";
let hour = Number(get("hour"));