perf: collapse the medication compliance hot path and the dashboard fan-out

The medication list fired one compliance request per card every 30
seconds, and each request scanned the medication's full intake history
and expanded the recurrence calendar five to six times. The endpoint now
mints bands once per request, serves the sub-windows from that single
ledger, bounds the event read to a year of selected columns and sits
behind a write-invalidated 15-minute server cache; the cards poll at
five minutes. The dashboard drops two redundant checklist queries by
reading counts from the snapshot, the BMI chart derives from the weight
series instead of refetching it, the detail page no longer serialises
behind the auth probe and seeds its query from the list row. Expensive
analytics reads gain a shared per-user rate limit, and the service
worker stops serving cross-version shells, enables navigation preload
and trims caches in one pass.
This commit is contained in:
Marc-André Bombeck committed 2026-06-10 12:55:56 +02:00
1 parent 41ba4c6c17
commit 298e4c34b4
24 files changed
+1483 -319

No files matched your search

@@ -0,0 +1,258 @@
/**
* v1.15.20 — single-pass compliance bundle parity.
*
* `buildMedicationComplianceBundle` replaces the per-medication compliance
* route's five-plus expansion passes (calculateCompliance × 4, the window
* ladder probes, the heatmap mint) with ONE band expansion + ONE cadence
* timeline. These tests pin the bundle's blocks against the historical
* per-window composition so the refactor cannot drift the public payload:
* every block must be deep-equal to what `calculateCompliance` /
* `buildComplianceDisplay` produce for the same fixture.
*/
import { describe, it, expect } from "vitest";
import {
buildComplianceMedicationContext,
buildComplianceLedgerRows,
buildMedicationComplianceBundle,
buildComplianceDisplay,
calculateCompliance,
lastNonSkippedTakenAt,
tallyComplianceFromLedger,
tallyLedgerRows,
type ComplianceSchedule,
} from "../compliance";
const TZ = "UTC";
const DAY_MS = 24 * 60 * 60 * 1000;
/** Deterministic anchor — keeps every window fully in the fixture's hands. */
const NOW = new Date("2026-06-01T12:00:00Z");
function dailySchedule(): ComplianceSchedule {
return {
windowStart: "08:00",
windowEnd: "09:00",
timesOfDay: ["08:00"],
daysOfWeek: null,
rrule: null,
rollingIntervalDays: null,
reminderGraceMinutes: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
};
}
function rollingSchedule(intervalDays: number): ComplianceSchedule {
return {
windowStart: "10:00",
windowEnd: "11:00",
timesOfDay: ["10:00"],
daysOfWeek: null,
rrule: null,
rollingIntervalDays: intervalDays,
reminderGraceMinutes: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
};
}
/** A slot instant `daysAgo` before NOW at the given "HH:mm" (UTC fixture). */
function slotAt(daysAgo: number, hhmm: string): Date {
const day = new Date(NOW.getTime() - daysAgo * DAY_MS);
const [h, m] = hhmm.split(":").map(Number);
const d = new Date(day);
d.setUTCHours(h, m, 0, 0);
return d;
}
interface FixtureEvent {
takenAt: Date | null;
skipped: boolean;
scheduledFor: Date;
autoMissed?: boolean;
}
function dailyFixtureEvents(): FixtureEvent[] {
return [
// Taken on time across several days.
{ takenAt: slotAt(1, "08:05"), skipped: false, scheduledFor: slotAt(1, "08:00") },
{ takenAt: slotAt(2, "08:10"), skipped: false, scheduledFor: slotAt(2, "08:00") },
{ takenAt: slotAt(4, "07:55"), skipped: false, scheduledFor: slotAt(4, "08:00") },
// A deliberate skip (excluded from the denominator).
{ takenAt: null, skipped: true, scheduledFor: slotAt(3, "08:00") },
// A taken-late dose (inside the late tail).
{ takenAt: slotAt(5, "10:30"), skipped: false, scheduledFor: slotAt(5, "08:00") },
// Day 6 has no event → the unfilled slot reads missed.
// An auto-missed forgotten dose.
{
takenAt: null,
skipped: false,
scheduledFor: slotAt(8, "08:00"),
autoMissed: true,
},
];
}
describe("buildMedicationComplianceBundle — parity with the per-window composition", () => {
it("daily medication: every block equals the legacy multi-pass output", () => {
const createdAt = new Date(NOW.getTime() - 40 * DAY_MS);
const schedules = [dailySchedule()];
const events = dailyFixtureEvents();
const ctx = buildComplianceMedicationContext(
{ startsOn: null, endsOn: null, oneShot: false, createdAt },
lastNonSkippedTakenAt(events),
TZ,
);
const bundle = buildMedicationComplianceBundle(events, schedules, ctx, NOW);
expect(bundle.compliance7).toEqual(
calculateCompliance(events, schedules, 7, createdAt, {
now: NOW,
medicationContext: ctx,
}),
);
expect(bundle.compliance30).toEqual(
calculateCompliance(events, schedules, 30, createdAt, {
now: NOW,
medicationContext: ctx,
}),
);
expect(bundle.complianceDisplay).toEqual(
buildComplianceDisplay(events, schedules, ctx, { now: NOW }),
);
// The ledger window clamps to the medication's creation.
expect(bundle.ledgerFrom).toEqual(createdAt);
// One band per daily slot over the 40-day life → 40 or 41 slot rows
// (the boundary day depends on the creation instant vs slot time).
const slotRows = bundle.ledgerRows.filter((r) => r.kind === "slot");
expect(slotRows.length).toBeGreaterThanOrEqual(39);
expect(slotRows.length).toBeLessThanOrEqual(41);
});
it("rolling 35-day medication: display windows + rates match the legacy path", () => {
const createdAt = new Date(NOW.getTime() - 400 * DAY_MS);
const schedules = [rollingSchedule(35)];
const events: FixtureEvent[] = [
{
takenAt: new Date(NOW.getTime() - 25 * DAY_MS),
skipped: false,
scheduledFor: new Date(NOW.getTime() - 25 * DAY_MS),
},
{
takenAt: new Date(NOW.getTime() - 60 * DAY_MS),
skipped: false,
scheduledFor: new Date(NOW.getTime() - 60 * DAY_MS),
},
];
const ctx = buildComplianceMedicationContext(
{
startsOn: new Date(NOW.getTime() - 380 * DAY_MS),
endsOn: null,
oneShot: false,
createdAt,
},
lastNonSkippedTakenAt(events),
TZ,
);
const bundle = buildMedicationComplianceBundle(events, schedules, ctx, NOW);
expect(bundle.compliance7).toEqual(
calculateCompliance(events, schedules, 7, createdAt, {
now: NOW,
medicationContext: ctx,
}),
);
expect(bundle.compliance30).toEqual(
calculateCompliance(events, schedules, 30, createdAt, {
now: NOW,
medicationContext: ctx,
}),
);
expect(bundle.complianceDisplay).toEqual(
buildComplianceDisplay(events, schedules, ctx, { now: NOW }),
);
// A 35-day cadence cannot clear the stability floor on [7, 30].
expect(bundle.complianceDisplay.shortDays).toBeGreaterThan(7);
expect(bundle.complianceDisplay.longDays).toBeGreaterThan(30);
});
it("empty schedule list: zeros short-circuit matches calculateCompliance", () => {
const createdAt = new Date(NOW.getTime() - 10 * DAY_MS);
const ctx = buildComplianceMedicationContext(
{ startsOn: null, endsOn: null, oneShot: false, createdAt },
null,
TZ,
);
const bundle = buildMedicationComplianceBundle([], [], ctx, NOW);
expect(bundle.compliance7).toEqual(
calculateCompliance([], [], 7, createdAt, {
now: NOW,
medicationContext: ctx,
}),
);
expect(bundle.complianceDisplay).toEqual(
buildComplianceDisplay([], [], ctx, { now: NOW }),
);
expect(bundle.ledgerRows).toEqual([]);
});
});
describe("tallyLedgerRows — windowed tallies over one shared ledger", () => {
it("the unwindowed tally equals tallyComplianceFromLedger byte-for-byte", () => {
const createdAt = new Date(NOW.getTime() - 40 * DAY_MS);
const schedules = [dailySchedule()];
const events = dailyFixtureEvents();
const ctx = buildComplianceMedicationContext(
{ startsOn: null, endsOn: null, oneShot: false, createdAt },
lastNonSkippedTakenAt(events),
TZ,
);
const from = new Date(NOW.getTime() - 30 * DAY_MS);
const rows = buildComplianceLedgerRows(events, schedules, ctx, from, NOW, NOW);
expect(tallyLedgerRows(rows)).toEqual(
tallyComplianceFromLedger(events, schedules, ctx, from, NOW, NOW),
);
});
it("a sub-window tally counts only rows inside the window", () => {
const createdAt = new Date(NOW.getTime() - 40 * DAY_MS);
const schedules = [dailySchedule()];
const events = dailyFixtureEvents();
const ctx = buildComplianceMedicationContext(
{ startsOn: null, endsOn: null, oneShot: false, createdAt },
lastNonSkippedTakenAt(events),
TZ,
);
const rows = buildComplianceLedgerRows(
events,
schedules,
ctx,
createdAt,
NOW,
NOW,
);
const wide = tallyLedgerRows(rows);
// 3.5 days reaches back past the day −3 08:00 slot (NOW is 12:00Z, so a
// plain 3-day bound would cut that morning slot off).
const narrow = tallyLedgerRows(rows, {
from: new Date(NOW.getTime() - 3.5 * DAY_MS),
to: NOW,
});
// Days −1 and −2 are taken on time; day −3 is a skip. Everything
// older falls outside the window.
expect(narrow.takenOnTime).toBe(2);
expect(narrow.skipped).toBe(1);
expect(narrow.denominator).toBeLessThan(wide.denominator);
});
});
+326 -1
View File
@@ -36,6 +36,7 @@ import { DOSE_WINDOW_DEFAULTS } from "@/lib/medications/scheduling/dose-window-d
import { normaliseDoseWindows } from "@/lib/medications/scheduling/worker-helpers";
import {
reconstructDoseHistory,
type DoseHistoryRow,
type HistoryIntake,
} from "@/lib/medications/scheduling/dose-history";
import {
@@ -1155,6 +1156,39 @@ export function tallyComplianceFromLedger(
now: Date,
windowConfig?: DoseWindowConfig,
): LedgerComplianceTally {
const rows = buildComplianceLedgerRows(
events,
schedules,
ctx,
from,
to,
now,
windowConfig,
);
return tallyLedgerRows(rows);
}
/**
* Mint the cadence-aware bands over `[from, to]` and reconstruct the ONE
* unified dose-history ledger for them. This is the expansion pass behind
* {@link tallyComplianceFromLedger}, extracted so a caller that needs
* several trailing sub-windows (7-day / 30-day / display / heatmap, all
* ending at `now`) can mint the bands ONCE over the widest window and tally
* each sub-window from the same rows via {@link tallyLedgerRows} instead of
* re-expanding per window.
*
* Pure / synchronous: bands come from pre-fetched schedules + intake
* instants; no DB access.
*/
export function buildComplianceLedgerRows(
events: IntakeEvent[],
schedules: ComplianceSchedule[],
ctx: ComplianceMedicationContext,
from: Date,
to: Date,
now: Date,
windowConfig?: DoseWindowConfig,
): DoseHistoryRow[] {
const medication: BandMinterMedication = {
id: "compliance-tally",
startsOn: ctx.startsOn,
@@ -1222,14 +1256,31 @@ export function tallyComplianceFromLedger(
autoMissed: e.autoMissed ?? false,
}));
const rows = reconstructDoseHistory(bands, intakes, now);
return reconstructDoseHistory(bands, intakes, now);
}
/**
* Tally pre-built ledger rows into the {@link LedgerComplianceTally}
* counters. When `window` is supplied only rows whose instant (`row.at`)
* falls inside `[window.from, window.to]` (inclusive) are counted — that is
* how a sub-window tally is carved out of a wider single-pass ledger. The
* window-less call tallies every row, byte-identical to the historical
* {@link tallyComplianceFromLedger} behaviour.
*/
export function tallyLedgerRows(
rows: DoseHistoryRow[],
window?: { from: Date; to: Date },
): LedgerComplianceTally {
let takenOnTime = 0;
let takenLate = 0;
let missed = 0;
let skipped = 0;
let adHoc = 0;
for (const row of rows) {
if (window) {
const t = row.at.getTime();
if (t < window.from.getTime() || t > window.to.getTime()) continue;
}
switch (row.status) {
case "taken_on_time":
takenOnTime++;
@@ -1517,3 +1568,277 @@ export function calculateCompliance(
return { totalExpected, taken, skipped, missed, rate, streak };
}
/**
* Widest trailing window the single-pass compliance ledger has to cover:
* the top rung of {@link COMPLIANCE_WINDOW_LADDER} (365 days). Every
* sub-window the per-medication compliance endpoint serves (7 / 30 /
* cadence-scaled display rows / 90-day heatmap) is a suffix of it.
*/
export const COMPLIANCE_LEDGER_WINDOW_DAYS = 365;
/**
* The per-medication compliance payload computed from ONE shared expansion
* pass. `ledgerRows` is the unified dose-history ledger over
* `[ledgerFrom, now]`; the caller carves the 90-day heatmap out of it by
* filtering on `row.at`.
*/
export interface MedicationComplianceBundle {
compliance7: ComplianceResult;
compliance30: ComplianceResult;
complianceDisplay: ComplianceDisplay;
/** Unified ledger rows over `[ledgerFrom, now]`, chronological. */
ledgerRows: DoseHistoryRow[];
/** Lower bound of the mint window (clamped to the medication's creation). */
ledgerFrom: Date;
}
/**
* Build every block of the per-medication compliance response from a single
* band-expansion pass.
*
* The historical composition called {@link calculateCompliance} four times
* (7 / 30 / short / long), {@link selectComplianceWindows} (up to four more
* occurrence expansions for the rung probes) and a separate 90-day heatmap
* mint — five-plus full band expansions per request. This builder instead:
*
* 1. mints the bands + reconstructs the ledger ONCE over
* `[max(createdAt, now − 365 d), now]` (every served window is a
* suffix of that range and ends at `now`, so a sub-window tally is a
* filter over `row.at`, not a re-expansion);
* 2. builds ONE cadence timeline over the same range for the per-window
* streaks ({@link streaksFromTimeline} bounds its day-walk by the
* requested window, so the wider timeline serves every window);
* 3. walks the {@link COMPLIANCE_WINDOW_LADDER} on the ledger's slot-row
* counts (one band per engine occurrence, so the counts match the
* historical `expectedSlotsBetween` probes).
*
* The returned blocks carry the exact public shapes the route has always
* served — only the number of expansion passes changed.
*/
export function buildMedicationComplianceBundle(
events: IntakeEvent[],
schedules: ComplianceSchedule[],
ctx: ComplianceMedicationContext,
now: Date,
): MedicationComplianceBundle {
const ledgerPeriodStart = new Date(
now.getTime() - COMPLIANCE_LEDGER_WINDOW_DAYS * ONE_DAY_MS,
);
const ledgerFrom =
ctx.createdAt.getTime() > ledgerPeriodStart.getTime()
? ctx.createdAt
: ledgerPeriodStart;
const hasSchedules = schedules.length > 0;
const ledgerRows = hasSchedules
? buildComplianceLedgerRows(events, schedules, ctx, ledgerFrom, now, now)
: [];
// ONE cadence timeline over the full ledger window. Each per-window
// streak below walks only its own trailing `effectiveDays`, so sharing
// the wide timeline reproduces the per-window builds.
const fullDays = Math.max(
1,
Math.ceil((now.getTime() - ledgerFrom.getTime()) / ONE_DAY_MS),
);
const timeline = hasSchedules
? buildTimelineForWindow(events, schedules, ctx, now, ledgerFrom, fullDays)
: [];
const resultForWindow = (days: number): ComplianceResult => {
if (!hasSchedules) {
// Mirrors `calculateCompliance`'s empty-schedule short-circuit.
return {
totalExpected: 0,
taken: 0,
skipped: 0,
missed: 0,
rate: 100,
streak: 0,
};
}
const periodStart = new Date(now.getTime() - days * ONE_DAY_MS);
const effectiveStart =
ctx.createdAt.getTime() > periodStart.getTime()
? ctx.createdAt
: periodStart;
const effectiveDays = Math.max(
1,
Math.ceil((now.getTime() - effectiveStart.getTime()) / ONE_DAY_MS),
);
const tally = tallyLedgerRows(ledgerRows, { from: effectiveStart, to: now });
const { current: streak } = streaksFromTimeline(
timeline,
now,
effectiveDays,
ctx.timeZone,
);
return {
totalExpected: tally.taken + tally.skipped + tally.missed,
taken: tally.taken,
skipped: tally.skipped,
missed: tally.missed,
rate: tally.rate,
streak,
};
};
// Window-ladder selection from the ledger's slot rows. A slot row is one
// minted band, and the minter emits one band per engine occurrence, so
// counting slot rows over a trailing window equals the historical
// `expectedSlotsBetween(...).length` probe for that window.
const expectedCache = new Map<number, number>();
const expectedOver = (days: number): number => {
const hit = expectedCache.get(days);
if (hit !== undefined) return hit;
const from = Math.max(
ctx.createdAt.getTime(),
now.getTime() - days * ONE_DAY_MS,
);
let count = 0;
for (const row of ledgerRows) {
if (row.kind !== "slot") continue;
const t = row.at.getTime();
if (t >= from && t <= now.getTime()) count++;
}
expectedCache.set(days, count);
return count;
};
let selection: ComplianceWindowSelection | null = null;
for (const [shortDays, longDays] of COMPLIANCE_WINDOW_LADDER) {
const expectedShort = expectedOver(shortDays);
const expectedLong = expectedOver(longDays);
if (expectedShort >= MIN_STABLE_DOSES && expectedLong >= MIN_STABLE_DOSES) {
selection = { shortDays, longDays, expectedShort, expectedLong };
break;
}
}
if (!selection) {
// No rung cleared the floor — fall back to the widest rung, exactly
// like `selectComplianceWindows`.
const [shortDays, longDays] =
COMPLIANCE_WINDOW_LADDER[COMPLIANCE_WINDOW_LADDER.length - 1];
selection = {
shortDays,
longDays,
expectedShort: expectedOver(shortDays),
expectedLong: expectedOver(longDays),
};
}
const compliance7 = resultForWindow(7);
const compliance30 = resultForWindow(30);
const short = resultForWindow(selection.shortDays);
const long = resultForWindow(selection.longDays);
const currentCycle = buildCurrentCycle(
schedules,
ctx,
now,
selection.expectedShort,
events,
);
const currentDose: { status: DoseStatus; targetAt: Date | null } =
currentCycle.nextDueAt
? {
status: deriveDoseStatus(
currentCycle.nextDueAt,
soonestCadenceFamily(schedules),
now,
),
targetAt: currentCycle.nextDueAt,
}
: { status: "upcoming", targetAt: null };
const complianceDisplay: ComplianceDisplay = {
shortDays: selection.shortDays,
longDays: selection.longDays,
expectedShort: selection.expectedShort,
expectedLong: selection.expectedLong,
minStableDoses: MIN_STABLE_DOSES,
short: {
rate: short.rate,
taken: short.taken,
expected: short.taken + short.missed,
missed: short.missed,
streak: short.streak,
},
long: {
rate: long.rate,
taken: long.taken,
expected: long.taken + long.missed,
missed: long.missed,
},
currentCycle,
currentDose,
};
return { compliance7, compliance30, complianceDisplay, ledgerRows, ledgerFrom };
}
/**
* The cadence-timeline construction from {@link calculateCompliance},
* extracted so {@link buildMedicationComplianceBundle} can build it once
* over the full ledger window instead of once per served sub-window. Same
* normalisation, same engine context, same rolling-retrospective routing.
*/
function buildTimelineForWindow(
events: IntakeEvent[],
schedules: ComplianceSchedule[],
ctx: ComplianceMedicationContext,
now: Date,
effectiveStart: Date,
effectiveDays: number,
): ReturnType<typeof buildCadenceTimeline> {
const normalisedSchedules: ScheduleLike[] = schedules.map((s, i) => ({
id: `compliance-${i}`,
windowStart: s.windowStart,
windowEnd: s.windowEnd,
daysOfWeek: s.daysOfWeek ?? null,
rrule: s.rrule ?? null,
rollingIntervalDays: s.rollingIntervalDays ?? null,
timesOfDay: s.timesOfDay,
reminderGraceMinutes: s.reminderGraceMinutes ?? null,
scheduleType: s.scheduleType ?? null,
cyclicOnWeeks: s.cyclicOnWeeks ?? null,
cyclicOffWeeks: s.cyclicOffWeeks ?? null,
}));
const engineCtx: CadenceEngineContext = {
startsOn: ctx.startsOn,
endsOn: ctx.endsOn,
oneShot: ctx.oneShot,
createdAt: ctx.createdAt,
lastIntakeAt: ctx.lastIntakeAt,
timeZone: ctx.timeZone,
};
const normalisedEvents: IntakeEventLike[] = events
.filter((e) => e.scheduledFor >= effectiveStart && e.scheduledFor <= now)
.map((e) => ({
scheduledFor: e.scheduledFor,
takenAt: e.takenAt,
skipped: e.skipped,
autoMissed: e.autoMissed ?? false,
}));
const hasRolling = schedules.some(
(s) => s.rollingIntervalDays != null && s.rollingIntervalDays > 0,
);
const retro = hasRolling
? { intakeInstants: rollingIntakeInstants(events, now), now }
: undefined;
return buildCadenceTimeline(
normalisedSchedules,
normalisedEvents,
now,
effectiveDays,
ctx.createdAt,
ctx.timeZone,
engineCtx,
retro,
);
}
+26
View File
@@ -50,6 +50,18 @@ async function primeAllCaches(): Promise<void> {
c: 2,
}));
// v1.15.20 — per-medication compliance payload cache.
await cached(
caches.medicationCompliance,
`${USER_A}|med-1|compliance`,
async () => ({ mc: 1 }),
);
await cached(
caches.medicationCompliance,
`${USER_B}|med-1|compliance`,
async () => ({ mc: 2 }),
);
await cached(caches.achievements, USER_A, async () => ({ ach: 1 }));
await cached(caches.achievements, USER_B, async () => ({ ach: 2 }));
@@ -149,6 +161,20 @@ describe("invalidateUserMedications", () => {
expect(caches.medications.get(USER_B)).not.toBeNull();
expect(caches.medicationsIntake.get(`${USER_B}|compliance|30`)).not.toBeNull();
});
it("evicts the per-medication compliance payload for the target user only", async () => {
await primeAllCaches();
invalidateUserMedications(USER_A);
// v1.15.20 — the compliance route caches 15 min; an intake write must
// flush the `${userId}|` prefix so the next card read is fresh.
expect(
caches.medicationCompliance.get(`${USER_A}|med-1|compliance`),
).toBeNull();
expect(
caches.medicationCompliance.get(`${USER_B}|med-1|compliance`),
).not.toBeNull();
});
});
describe("invalidateUserDashboardWidgets", () => {
+4
View File
@@ -105,6 +105,10 @@ export function invalidateUserMood(userId: string): void {
export function invalidateUserMedications(userId: string): void {
caches.medications.deleteByPrefix(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).
+16
View File
@@ -393,6 +393,22 @@ export const caches = {
maxEntries: 1000,
ttlMs: 900_000,
}),
/**
* v1.15.20 — per-medication compliance payload
* (`GET /api/medications/[id]/compliance`). The medications list fans
* the endpoint out once per card, and each cold build runs the full
* band-expansion pass — so the warm path has to live server-side.
* Keyed `${userId}|${medicationId}|compliance`; every intake /
* medication write flushes the `${userId}|` prefix via
* `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.
*/
medicationCompliance: new ServerCache<unknown>({
name: "medicationCompliance",
maxEntries: 2000,
ttlMs: 900_000,
}),
moodAnalytics: new ServerCache<unknown>({
name: "moodAnalytics",
maxEntries: 1000,
+23
View File
@@ -64,6 +64,29 @@ export function rateLimitHeaders(
};
}
/**
* v1.15.20 — shared per-user budget for the heavy read-only analytics
* surfaces (`/api/insights/comprehensive`, `/api/insights/correlations`,
* `/api/insights/derived`, `/api/analytics/range`). The insights page
* legitimately fans several of these out per mount, so the bucket is
* generous — 120/min only caps a runaway client loop or a scripted
* drain, mirroring the `sync:changes` budget. One shared bucket (not
* per-surface) keeps the cap meaningful when a loop rotates across
* endpoints.
*/
const ANALYTICS_READ_LIMIT = 120;
const ANALYTICS_READ_WINDOW_MS = 60 * 1000;
export async function checkAnalyticsReadRateLimit(
userId: string,
): Promise<RateLimitResult> {
return checkRateLimit(
`analytics-read:${userId}`,
ANALYTICS_READ_LIMIT,
ANALYTICS_READ_WINDOW_MS,
);
}
/**
* v1.4.43 W13 M-4 — anonymous/trust-violation bucket key shared by every
* caller of `checkAuthSurfaceRateLimit`. When `TRUST_PROXY_HOPS` and the