mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
fix(api,lib): consent before reuse, tighter inputs and caches that tell on themselves
Per-status texts check AI consent before the unchanged-data refresh can re-stamp them, the comprehensive fingerprint folds in the comparison baseline and generation language so toggling either regenerates once, and profile, threshold and source-priority writes evict the analytics, targets and derived caches they feed. CSV export neutralises spreadsheet formula prefixes on free-text cells while numeric columns stay typed, the derived batch validates its type token against the measurement enum and carries a per-user rate limit, and a dose synced from the phone app counts as the interactive write it is. Background cache refresh failures log a structured event instead of vanishing, the warm queue runs visit-triggered jobs alongside the nightly walk, the formatter memo evicts one entry instead of flushing wholesale with its option objects frozen, the targets cold build bounds its fan-out, and time in bed unions every writer's envelope while stages stay with the richest recorder.
This commit is contained in:
1 parent
95f21bfa4d
commit
f790e14edd
40 files changed
+1141
-287
No files matched your search
+55
-15
@@ -6,11 +6,7 @@
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
__resetAllCachesForTests,
|
||||
cached,
|
||||
caches,
|
||||
} from "../server-cache";
|
||||
import { __resetAllCachesForTests, cached, caches } from "../server-cache";
|
||||
import {
|
||||
invalidateAppSettings,
|
||||
invalidateUserDashboardWidgets,
|
||||
@@ -19,6 +15,7 @@ import {
|
||||
invalidateUserMeasurements,
|
||||
invalidateUserMedications,
|
||||
invalidateUserMood,
|
||||
invalidateUserProfile,
|
||||
dashboardSnapshotCacheKey,
|
||||
} from "../invalidate";
|
||||
|
||||
@@ -43,12 +40,20 @@ async function primeAllCaches(): Promise<void> {
|
||||
await cached(caches.medications, USER_A, async () => ({ m: 1 }));
|
||||
await cached(caches.medications, USER_B, async () => ({ m: 2 }));
|
||||
|
||||
await cached(caches.medicationsIntake, `${USER_A}|compliance|30`, async () => ({
|
||||
c: 1,
|
||||
}));
|
||||
await cached(caches.medicationsIntake, `${USER_B}|compliance|30`, async () => ({
|
||||
c: 2,
|
||||
}));
|
||||
await cached(
|
||||
caches.medicationsIntake,
|
||||
`${USER_A}|compliance|30`,
|
||||
async () => ({
|
||||
c: 1,
|
||||
}),
|
||||
);
|
||||
await cached(
|
||||
caches.medicationsIntake,
|
||||
`${USER_B}|compliance|30`,
|
||||
async () => ({
|
||||
c: 2,
|
||||
}),
|
||||
);
|
||||
|
||||
// v1.15.20 — per-medication compliance payload cache.
|
||||
await cached(
|
||||
@@ -149,9 +154,7 @@ describe("invalidateUserMeasurements", () => {
|
||||
).toBeNull();
|
||||
|
||||
// User B stays warm; the non-analytics buckets evict as before.
|
||||
expect(
|
||||
caches.analytics.getAllowStale(`${USER_B}|default`),
|
||||
).not.toBeNull();
|
||||
expect(caches.analytics.getAllowStale(`${USER_B}|default`)).not.toBeNull();
|
||||
expect(caches.achievements.get(USER_A)).toBeNull();
|
||||
expect(caches.workouts.get(`${USER_A}|3|0||`)).toBeNull();
|
||||
});
|
||||
@@ -197,7 +200,9 @@ describe("invalidateUserMedications", () => {
|
||||
// covers the snapshot key.
|
||||
expect(caches.analytics.get(dashboardSnapshotCacheKey(USER_A))).toBeNull();
|
||||
expect(caches.medications.get(USER_B)).not.toBeNull();
|
||||
expect(caches.medicationsIntake.get(`${USER_B}|compliance|30`)).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 () => {
|
||||
@@ -308,6 +313,41 @@ describe("invalidateUserInsights", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("invalidateUserProfile", () => {
|
||||
it("hard-evicts targets + derived + analytics for the target user only", async () => {
|
||||
await primeAllCaches();
|
||||
await cached(caches.insightsTargets, USER_A, async () => ({ t: 1 }));
|
||||
await cached(caches.insightsTargets, USER_B, async () => ({ t: 2 }));
|
||||
await cached(caches.insightsDerived, `${USER_A}|batch|x|en`, async () => ({
|
||||
d: 1,
|
||||
}));
|
||||
await cached(caches.insightsDerived, `${USER_B}|batch|x|en`, async () => ({
|
||||
d: 2,
|
||||
}));
|
||||
|
||||
invalidateUserProfile(USER_A);
|
||||
|
||||
// Profile-derived payloads drop — including the SWR stale window
|
||||
// (a Settings save is interactive; the pre-edit grid must not serve).
|
||||
expect(caches.insightsTargets.getAllowStale(USER_A)).toBeNull();
|
||||
expect(
|
||||
caches.insightsDerived.getAllowStale(`${USER_A}|batch|x|en`),
|
||||
).toBeNull();
|
||||
expect(
|
||||
caches.analytics.getAllowStale(dashboardSnapshotCacheKey(USER_A)),
|
||||
).toBeNull();
|
||||
expect(caches.analytics.getAllowStale(`${USER_A}|default`)).toBeNull();
|
||||
|
||||
// The other user's cells stay warm.
|
||||
expect(caches.insightsTargets.get(USER_B)).not.toBeNull();
|
||||
expect(caches.insightsDerived.get(`${USER_B}|batch|x|en`)).not.toBeNull();
|
||||
expect(caches.analytics.get(`${USER_B}|default`)).not.toBeNull();
|
||||
|
||||
// Buckets a profile edit does not feed stay untouched.
|
||||
expect(caches.medications.get(USER_A)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("invalidateAppSettings", () => {
|
||||
it("evicts the entire bug-report status cache (singleton row)", async () => {
|
||||
await primeAllCaches();
|
||||
|
||||
+52
-1
@@ -62,7 +62,13 @@ describe("ServerCache per-key TTL override", () => {
|
||||
it("wrap()/cached() thread the TTL override and stay evictable by prefix", async () => {
|
||||
vi.useFakeTimers();
|
||||
const cache = new ServerCache<string>({ maxEntries: 4, ttlMs: 60_000 });
|
||||
await cached(cache, "u1|dashboard-snapshot", async () => "snap", undefined, 180_000);
|
||||
await cached(
|
||||
cache,
|
||||
"u1|dashboard-snapshot",
|
||||
async () => "snap",
|
||||
undefined,
|
||||
180_000,
|
||||
);
|
||||
// Default bucket TTL elapsed; the override keeps the entry warm so
|
||||
// the 120 s client refetch interval lands on a hit, not a miss.
|
||||
vi.advanceTimersByTime(120_000);
|
||||
@@ -308,6 +314,51 @@ describe("ServerCache stale-while-revalidate (wrapSwr / cachedSwr)", () => {
|
||||
expect(builder).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("logs a refresh_failed signal when the detached background rebuild rejects", async () => {
|
||||
vi.useFakeTimers();
|
||||
const consoleError = vi
|
||||
.spyOn(console, "error")
|
||||
.mockImplementation(() => {});
|
||||
const cache = new ServerCache<string>({
|
||||
name: "analytics",
|
||||
maxEntries: 4,
|
||||
ttlMs: 1000,
|
||||
staleTtlMs: 600_000,
|
||||
});
|
||||
let calls = 0;
|
||||
const builder = vi.fn(async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) return "v1";
|
||||
throw new Error("db gone");
|
||||
});
|
||||
await cache.wrapSwr("k", builder);
|
||||
vi.advanceTimersByTime(1500);
|
||||
|
||||
// Stale serve succeeds for the caller…
|
||||
const stale = await cache.wrapSwr("k", builder);
|
||||
expect(stale.outcome).toBe("stale");
|
||||
expect(stale.value).toBe("v1");
|
||||
await vi.runAllTimersAsync();
|
||||
|
||||
// …but the failed background rebuild is surfaced, not swallowed:
|
||||
// bucket-scoped event name + hashed key + the error message.
|
||||
expect(consoleError).toHaveBeenCalledTimes(1);
|
||||
const [event, payload] = consoleError.mock.calls[0] as [string, string];
|
||||
expect(event).toBe("cache.analytics.refresh_failed");
|
||||
const parsed = JSON.parse(payload) as {
|
||||
key_hash: number;
|
||||
error: string;
|
||||
};
|
||||
expect(parsed.key_hash).toBe(hashCacheKey("k"));
|
||||
expect(parsed.error).toBe("db gone");
|
||||
|
||||
// The pending slot is clear — the next stale read retries the build.
|
||||
const retry = await cache.wrapSwr("k", builder);
|
||||
expect(retry.outcome).toBe("stale");
|
||||
expect(builder).toHaveBeenCalledTimes(3);
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("treats an entry past the stale window as a hard miss", async () => {
|
||||
vi.useFakeTimers();
|
||||
const cache = new ServerCache<string>({
|
||||
|
||||
Vendored
+32
-5
@@ -138,13 +138,14 @@ export function invalidateUserMood(userId: string): void {
|
||||
* 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
|
||||
* skip, a CRUD edit, an intake edit / delete / purge / import, AND the
|
||||
* iOS bulk-intake endpoint — it carries the phone user's own doses) 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.
|
||||
* Background paths (the auto-miss cron, slot dedup) keep the default
|
||||
* mark-stale so a high-frequency pass 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,
|
||||
@@ -179,6 +180,32 @@ export function invalidateUserMedications(
|
||||
caches.insightsTargets.deleteByPrefix(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.16.8 — invalidate every cache whose payload derives from the user's
|
||||
* PROFILE-level settings rather than from measurement / mood / medication
|
||||
* rows. The measurement-write invalidators never fire on a settings save,
|
||||
* so before this helper a height / birth-date / gender edit, a threshold
|
||||
* override, or a source-priority reorder kept serving the pre-edit
|
||||
* targets grid (BMI band, BP-by-age range, glucose effective ranges),
|
||||
* derived scores (baseline profile: age / sex / height), and analytics
|
||||
* snapshot until the TTL lapsed.
|
||||
*
|
||||
* Hard-evict on every bucket: these are interactive Settings writes, and
|
||||
* a marked-stale SWR cell would hand the user back the pre-edit payload
|
||||
* on the very next read.
|
||||
*
|
||||
* Callers: `/api/user/thresholds` PUT + DELETE, `applyProfileUpdate`
|
||||
* (only when heightCm / dateOfBirth / gender is in the update set), and
|
||||
* `/api/auth/me/source-priority` PUT. The unit-preference toggle is NOT
|
||||
* wired in: it only drives the client-side display transform, no
|
||||
* server-cached payload reads it.
|
||||
*/
|
||||
export function invalidateUserProfile(userId: string): void {
|
||||
caches.insightsTargets.deleteByPrefix(userId);
|
||||
caches.insightsDerived.deleteByPrefix(`${userId}|`);
|
||||
caches.analytics.deleteByPrefix(`${userId}|`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate the dashboard-widget layout cache for a single user.
|
||||
*
|
||||
|
||||
Vendored
+38
-13
@@ -162,12 +162,20 @@ export class ServerCache<T> {
|
||||
/**
|
||||
* v1.12.1 — mark every entry under `prefix` stale without dropping it.
|
||||
* Collapses the fresh TTL to "now" so the next `wrapSwr` read serves
|
||||
* the prior value immediately (within the stale window) while a single
|
||||
* coalesced recompute warms a fresh value. This replaces the
|
||||
* hard-evict on a mood write so an active logger no longer re-pays the
|
||||
* cold compute on every entry. No-op for buckets without `staleTtlMs`
|
||||
* (the entry is already at/over its hard TTL after this, so the next
|
||||
* read is a clean miss — identical to the old evict behaviour).
|
||||
* the prior value immediately while a single coalesced recompute warms
|
||||
* a fresh value. This replaces the hard-evict on a mood write so an
|
||||
* active logger no longer re-pays the cold compute on every entry.
|
||||
*
|
||||
* Stale-serve bound: marking does NOT touch `staleUntil`, which was
|
||||
* fixed at insert time as `insert + ttlMs + staleTtlMs`. A marked
|
||||
* entry can therefore keep serving stale until up to `ttlMs +
|
||||
* staleTtlMs` after it was INSERTED — not `staleTtlMs` after the
|
||||
* mark. (Marking near the end of the fresh window leaves close to
|
||||
* `staleTtlMs` of serveability; marking right after insert leaves
|
||||
* nearly the full `ttlMs + staleTtlMs`.) No-op for buckets without
|
||||
* `staleTtlMs` (the entry is already at/over its hard TTL after this,
|
||||
* so the next read is a clean miss — identical to the old evict
|
||||
* behaviour).
|
||||
*/
|
||||
markStaleByPrefix(prefix: string): number {
|
||||
let marked = 0;
|
||||
@@ -295,9 +303,24 @@ export class ServerCache<T> {
|
||||
});
|
||||
this.pending.set(key, refresh);
|
||||
// Detach: the foreground caller does not await the rebuild.
|
||||
// Swallow the rejection on the detached handle so an
|
||||
// unhandled-rejection warning never fires.
|
||||
refresh.catch(() => {});
|
||||
// Handle the rejection on the detached handle so an
|
||||
// unhandled-rejection warning never fires — but never silently:
|
||||
// a refresh that keeps failing means the bucket serves an
|
||||
// ever-older stale value until the SWR window finally lapses,
|
||||
// so the failure must reach the logs. There is no request
|
||||
// context here (the caller already returned), so a structured
|
||||
// console.error stands in for the wide-event annotation; the
|
||||
// key is logged as its djb2 hash, matching the cache-outcome
|
||||
// meta convention, so the userId segment never reaches stdout.
|
||||
refresh.catch((err) => {
|
||||
console.error(
|
||||
`cache.${this.opts.name ?? "unnamed"}.refresh_failed`,
|
||||
JSON.stringify({
|
||||
key_hash: hashCacheKey(key),
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
return { value: cachedEntry.value, outcome: "stale" };
|
||||
}
|
||||
@@ -422,10 +445,12 @@ export const caches = {
|
||||
* 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.
|
||||
* intake / medication writes — including the iOS bulk-intake endpoint,
|
||||
* which carries the phone user's own taken/skipped doses — hard-evict
|
||||
* (the user must see their own dose on the next read); the genuinely
|
||||
* background writers (the auto-miss cron, slot dedup) mark stale so a
|
||||
* high-frequency pass never busts every card into an inline cold
|
||||
* rebuild.
|
||||
*/
|
||||
medicationCompliance: new ServerCache<unknown>({
|
||||
name: "medicationCompliance",
|
||||
|
||||
Reference in new issue
Block a user