v1.4.34 — apple-health import + reliability + web-freeze

The final functional web release before the iOS native client lands.
Headline work: a streaming Apple Health `export.zip` importer for
prospective iOS-migrating accounts, a server-side aggregation cache
that collapses the three hottest dashboard reads onto in-process LRU
slots with single-flight coalescing and per-user invalidation, a
broader compliance classifier with a dedicated `early` bucket so
ahead-of-window doses count as compliant, the Coach launch surface
hoisted onto every authed page with a dashboard-hero CTA, and a
trimmer Settings shelf that folds Sources into Targets. The release
also lights up the `cache.<name>.outcome` annotation on the active
wide event so production logs carry the cache hit-ratio signal
without leaking userIds.

### Added

- **Server-side aggregation cache.** A new `ServerCache<T>` primitive
  (`src/lib/cache/server-cache.ts`) extends the v1.4.33 Coach snapshot
  LRU shape into a reusable per-route layer with TTL expiry,
  capacity-bounded LRU eviction, single-flight read coalescing, and
  per-instance hit / miss / eviction / stampede counters. Wires the
  three hottest dashboard reads — `/api/analytics` (slim + default),
  `/api/gamification/achievements`, `/api/medications/intake?scope=compliance`
  — and bolts per-user invalidation onto every measurement / mood /
  medication / workout / dashboard-widget write endpoint so the next
  read paints fresh data instead of waiting out the TTL. Every cache
  hit / miss surfaces on the active wide event as
  `cache.<name>.outcome` + `cache.<name>.key_hash` so production logs
  carry the hit-ratio signal without leaking userIds.
- **Apple Health `export.zip` import.** New endpoint
  `POST /api/import/apple-health-export` (synchronous multipart
  upload, asynchronous ingest via a dedicated pg-boss
  `apple-health-import` worker, per-`MeasurementType` ingestion
  stats). Streams the upload straight to disk so a multi-gigabyte
  export never lands in V8 heap, hashes the bytes inline for
  content-based idempotency, and unpacks `apple_health_export/export.xml`
  with a hand-rolled ZIP central-directory walker that handles Zip64
  for archives past the 4 GB barrier. The parser folds every
  `<Record>`, `<Workout>`, `<Correlation>`, and `<ClinicalRecord>`
  into the existing `Measurement` and `Workout` row shapes — spot
  rows keyed by `HKMetadataKeyExternalUUID` (or a deterministic
  `sample:<sha256>` fallback), cumulative HK types collapsed into
  one `stats:<HKType>:<YYYY-MM-DD>` row per user-local day to match
  the iOS daily-aggregation convention. Live per-stage progress
  surfaces through `GET /api/import/apple-health-export/{jobId}/status`.
  An admin variant at `POST /api/admin/import-apple-health-export`
  imports on behalf of a target user (cookie-only `requireAdmin()`
  gate; Bearer tokens never elevate).
- **`ImportJob` schema model + migration.** New Prisma model captures
  the per-upload state machine (`queued | unpacking | parsing |
  upserting | done | failed`), the content-hash for idempotency
  short-circuits, and the per-`MeasurementType` ingestion counters
  the status route surfaces back to the client.
- **`lastSeenByType` on `/api/analytics`.** Both the slim
  (`?slice=summaries`) and default slices return a per-type
  `{ lastSeenAt, daysAgo }` map. The dashboard trend tiles wire 12
  mounts to a new `tileStaleDays()` helper so an "X days / weeks /
  months ago" hint paints under any per-metric tile whose last
  sample crosses the 7-day floor. Six locales gained additive
  week / month plural keys; Polish uses the genitive-plural form
  that covers every non-1 count the bucket math can produce.
- **Dashboard "Ask the coach" hero CTA.** A new pill next to the
  existing "Hinzufügen" / "Add" launches the Coach drawer directly
  from the dashboard hero. The `<CoachLaunchProvider>` hoisted from
  the insights layout to the auth shell so the drawer is reachable
  from every authed route; the floating action button stays scoped
  to `/insights/**` so it cannot distract on the dashboard.
- **Shared achievements query hook.** `useAchievementsQuery()`
  centralises the three previous consumers — recent-achievements
  card, the `/achievements` mother page, and the unlock notifier —
  onto one TanStack queryKey + cache slot so dashboard cold mount
  fires the endpoint once instead of twice.
- **Typed authed Cache-Control presets.** New
  `src/lib/http/cache-headers.ts` module exports
  `NO_STORE_BUT_BFCACHE = "private, max-age=0, must-revalidate"`,
  `SHORT_LIVED_PUBLIC`, and an `applyAuthedHeaders()` helper. The
  presets land at the framework level via a `next.config.ts`
  `headers()` rule that stamps the bfcache-friendly directive on
  every authed HTML response, restoring Chromium bfcache eligibility
  for in-app back / forward navigation.
- **`scripts/print-bundle-report.mjs`.** Restores the at-a-glance
  "top client chunks by parsed size" signal Turbopack dropped from
  `next build`; reads `.next/analyze/client.json` (written by
  `@next/bundle-analyzer` when `pnpm analyze` runs with `ANALYZE=1`)
  and prints a sorted table plus totals.

### Changed

- **Settings sidebar: "Sources" folded into "Targets & Sources".**
  Per-metric threshold ranges and per-metric source priority now
  share one `/settings/thresholds` page so the same metric's
  threshold and device-source preference sit together instead of
  one sidebar entry away. `/settings/sources` keeps a
  `permanentRedirect` so external bookmarks and docs links follow
  through unchanged. Section count: 11 → 10.
- **Insights tab strip: vital pills collapse under a "Vitals"
  parent.** Five vital pills (HRV, Resting HR, Oxygen, Body
  Temperature, Active Energy) hide behind one parent pill that
  opens a popover sub-list. Parent-pill active state mirrors the
  URL so spatial orientation survives the collapse; each sub-page
  keeps its own URL and bookmark resolves unchanged. Strip
  footprint: 14 → 10 entries when every metric has data.
- **Coolify env-var audit.** `mcp__coolify-apps01__env_vars`
  inspection captured the section-1 / section-2 duplicates that
  have accumulated under apps-01 since v1.3.1. Audit pinned at
  `.planning/round-v1434-iwa-coolify-env-audit.md`; no env-var
  deletes performed (operator action).

### Fixed

- **Compliance classifier: early intakes count as compliant.** The
  classifier picked up a dedicated `early` bucket (window-start
  minus three hours through window-start), the `on_time` post-window
  tolerance widened from one hour to three hours, and the `late`
  band sits between the new `on_time` ceiling and the configurable
  `lateMinutes` knob. Heatmap consumers route the new bucket
  through the compliant path; the dedicated `early` counter rides
  on `DailyComplianceEntry` for downstream consumers that want to
  distinguish ahead-of-window from on-window intakes.
- **Compliance heatmap fallback retired.** The v1.4.33 defensive
  `looksClassifierBug` fallthrough is gone now that the underlying
  classifier widening removes the every-dose-very-late mode the
  fallback covered.

### Performance

- **`/api/gamification/achievements` consumer collapse.** Two of
  three previous consumers shared the same TanStack queryKey
  literal; the third carried a per-user discriminator so the cache
  treated it as a fresh slot. Dashboard cold mount fired the
  endpoint twice. Collapsing onto the shared hook trims that to a
  single request; with the new server-side cache slot warm, the
  duplicate-mount worst case rides single-flight coalescing.
- **GHCR build fires once per release tag.** The
  `docker-publish.yml` workflow lost its `push.branches: [main]`
  trigger; the `:latest` raw-tag enable rule moved onto the tag
  ref so each release produces exactly one multi-arch build that
  refreshes both the semver tags and the `:latest` alias.
- **NFT-trace warnings silenced.** `next.config.ts` gained an
  `outputFileTracingExcludes` block that narrows the Turbopack
  tracer away from the `MAXMIND_LICENSE_KEY` env-access path so
  the trace-report no longer warns on every dependent route file.

### Refactor

- **Dashboard analytics consumers.** The two cards that previously
  decided their own freshness copy now lean on the typed
  `tileStaleDays()` helper and the additive `lastSeenByType` field
  on the analytics response. Mood and BD-Zielbereich tiles keep the
  default `null` because they have no underlying per-type freshness
  signal.

### Accessibility

- **Dashboard hero CTA hits the WCAG 2.5.5 touch-target floor.**
  The new "Ask the coach" pill carries `min-h-11` on mobile and
  the matching `sm:min-h-9` desktop floor so the touch target
  stays above 44 px on the Pixel 5 boundary.
- **Insights tab-strip Vitals parent reads correctly to assistive
  tech.** Parent pill carries `aria-current="page"` whenever the
  current URL matches one of its child vital sub-pages, plus a
  `data-slot="insights-tab-strip-group"` hook for visual-regression
  testing.

### Internal

- **Two e2e flake windows tightened.** `onboarding-flicker` swapped
  its 12-sample 50 ms poll loop for a single Playwright
  auto-retrying `toBeHidden({ timeout: 700 })` assertion so the
  1-2 ms race window between the analytics-pending shell and
  `useAuth().user` resolving collapses to a single retry slot.
  `mobile-viewport` dropped `nav a[href]` from the touch-target
  sweep (the bottom-nav owns its own WCAG spec) and gated the
  44-px floor on `matchMedia('(min-width: 640px)').matches === false`
  so the Pixel 5 viewport never tripped into the `sm:` tier during
  WebKit render commits.
- **Server-cache observability.** Every `cached()` invocation passes
  an `annotate` callback that lands two keys on the wide event:
  `cache.<name>.outcome` ∈ `{ hit | miss | stampede }` and
  `cache.<name>.key_hash` (non-reversible djb2 32-bit hash). Ops
  can grep `cache.analytics.outcome` over any time window to
  compute the hit ratio per deployment.
- **AASA followups verified.** The v1.4.33 `/.well-known/apple-app-site-association`
  handler serves a direct 200 on every fronting origin; Apple's
  CDN has ingested matching bodies for all three domains.

### Web freeze

v1.4.34 marks the last functional release of the web codebase before
the iOS native client launches. Subsequent v1.4.x tags carry security
fixes, dependency bumps, and hotfix-only corrections. New feature work
is paused until the iOS app clears Apple review, at which point a
v1.5.0 version-bump-only release tags the milestone. The Prisma
schema head comment and `.planning/v15-strategic-plan.md` §5
decision-log row pin the freeze trigger in-tree.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-16 21:25:26 +02:00
1 parent 7bef199039
commit affede31a4
104 files changed
+8050 -404

No files matched your search

@@ -0,0 +1,130 @@
/**
* Smoke tests for the admin Apple Health import endpoint. Covers the
* cookie-only `requireAdmin()` gate (Bearer never elevates), the 413
* size-cap, and the 429 rate-limit path. Multipart streaming + boss
* enqueue are exercised by the parser + multipart unit suites.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
const mocks = vi.hoisted(() => ({
checkRateLimit: vi.fn().mockResolvedValue({ allowed: true }),
bossSend: vi.fn().mockResolvedValue("boss-job-1"),
getGlobalBoss: vi.fn(),
importJobCreate: vi.fn(),
importJobFindFirst: vi.fn().mockResolvedValue(null),
importJobUpdate: vi.fn(),
userFindUnique: vi.fn(),
}));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: mocks.checkRateLimit,
}));
vi.mock("@/lib/jobs/boss-instance", () => ({
getGlobalBoss: mocks.getGlobalBoss,
}));
vi.mock("@/lib/db", () => ({
prisma: {
importJob: {
create: mocks.importJobCreate,
findFirst: mocks.importJobFindFirst,
update: mocks.importJobUpdate,
},
user: {
findUnique: mocks.userFindUnique,
},
},
}));
import { POST } from "../route";
import { getSession } from "@/lib/auth/session";
const ADMIN_SESSION = {
session: { id: "sess-admin", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "admin-1", username: "marc", role: "ADMIN" as const },
};
const USER_SESSION = {
session: { id: "sess-user", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-2", username: "alice", role: "USER" as const },
};
beforeEach(() => {
vi.resetAllMocks();
mocks.checkRateLimit.mockResolvedValue({ allowed: true });
mocks.bossSend.mockResolvedValue("boss-job-1");
mocks.getGlobalBoss.mockReturnValue({ send: mocks.bossSend });
mocks.importJobCreate.mockResolvedValue({ id: "ij-1" });
mocks.importJobFindFirst.mockResolvedValue(null);
mocks.importJobUpdate.mockResolvedValue({ id: "ij-1" });
mocks.userFindUnique.mockResolvedValue({ id: "user-2", username: "alice" });
});
describe("POST /api/admin/import-apple-health-export", () => {
it("returns 401 when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const req = new NextRequest("http://localhost/api/admin/import-apple-health-export", {
method: "POST",
headers: { "content-type": "multipart/form-data; boundary=---x" },
body: "stub",
});
const res = await POST(req);
expect(res.status).toBe(401);
});
it("returns 403 when a non-admin cookie session calls the route", async () => {
vi.mocked(getSession).mockResolvedValue(USER_SESSION as never);
const req = new NextRequest("http://localhost/api/admin/import-apple-health-export", {
method: "POST",
headers: { "content-type": "multipart/form-data; boundary=---x" },
body: "stub",
});
const res = await POST(req);
expect(res.status).toBe(403);
});
it("returns 413 when Content-Length exceeds the cap", async () => {
vi.mocked(getSession).mockResolvedValue(ADMIN_SESSION as never);
const headers = new Headers({
"content-type": "multipart/form-data; boundary=---x",
"content-length": String(2 * 1024 * 1024 * 1024),
});
const req = new NextRequest("http://localhost/api/admin/import-apple-health-export", {
method: "POST",
headers,
body: "stub",
});
const res = await POST(req);
expect(res.status).toBe(413);
});
it("returns 429 on rate-limit exhaustion", async () => {
vi.mocked(getSession).mockResolvedValue(ADMIN_SESSION as never);
mocks.checkRateLimit.mockResolvedValueOnce({ allowed: false });
const req = new NextRequest("http://localhost/api/admin/import-apple-health-export", {
method: "POST",
headers: { "content-type": "multipart/form-data; boundary=---x" },
body: "stub",
});
const res = await POST(req);
expect(res.status).toBe(429);
});
});
@@ -0,0 +1,192 @@
/**
* `POST /api/admin/import-apple-health-export` — admin-only Apple
* Health import on behalf of a target user.
*
* Same multipart streaming path as the user-facing kick-off, but with
* `requireAdmin()` (cookie-only — Bearer tokens never elevate) and a
* `userId` text field naming the target user. The kicked-off
* `ImportJob` row carries `triggeredByAdminId = admin.id` so the
* status endpoint admits both the target user AND the triggering
* admin.
*
* Locks per `.planning/research/v1434-r-1-xml-import.md` §9.
*/
import type { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireAdmin, HttpError } from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { checkRateLimit } from "@/lib/rate-limit";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
import {
APPLE_HEALTH_IMPORT_QUEUE,
type AppleHealthImportPayload,
} from "@/lib/jobs/apple-health-import-worker";
import { streamMultipartToDisk } from "@/lib/multipart/stream-to-disk";
export const dynamic = "force-dynamic";
const MAX_UPLOAD_BYTES = 1.5 * 1024 * 1024 * 1024;
const RATE_LIMIT_MAX = 3;
const RATE_LIMIT_WINDOW_MS = 60_000;
export const POST = apiHandler(async (request: NextRequest) => {
const { user: admin } = await requireAdmin();
annotate({ action: { name: "admin.import-apple-health.kickoff" } });
const rl = await checkRateLimit(
`admin-import-apple-health:${admin.id}`,
RATE_LIMIT_MAX,
RATE_LIMIT_WINDOW_MS,
);
if (!rl.allowed) {
throw new HttpError(429, "Too many import uploads, try again later");
}
const declaredBytes = Number(request.headers.get("content-length") ?? 0);
if (declaredBytes > MAX_UPLOAD_BYTES) {
await auditLog("admin.import-apple-health.kickoff.denied", {
userId: admin.id,
ipAddress: getClientIp(request),
details: {
reason: "content_length_exceeded",
contentLength: declaredBytes,
},
});
return apiError("Upload exceeds 1.5 GB limit", 413);
}
const body = request.body;
if (!body) {
return apiError("Request body is required", 400);
}
let uploaded;
try {
uploaded = await streamMultipartToDisk(
body,
request.headers.get("content-type"),
{
maxBytes: MAX_UPLOAD_BYTES,
fieldName: "file",
tmpPrefix: "healthlog-admin-apple-health-import",
},
);
} catch (err) {
const message = err instanceof Error ? err.message : "upload_failed";
await auditLog("admin.import-apple-health.kickoff.denied", {
userId: admin.id,
ipAddress: getClientIp(request),
details: { reason: "stream_to_disk_failed", message },
});
return apiError(`Multipart upload failed: ${message}`, 422);
}
// Resolve the target user from the multipart text field. Mandatory:
// the admin variant is explicitly cross-user.
const targetUserId = uploaded.textFields.userId;
if (!targetUserId) {
await auditLog("admin.import-apple-health.kickoff.denied", {
userId: admin.id,
ipAddress: getClientIp(request),
details: { reason: "missing_user_id" },
});
return apiError("Multipart field 'userId' is required", 422);
}
const targetUser = await prisma.user.findUnique({
where: { id: targetUserId },
select: { id: true, username: true },
});
if (!targetUser) {
await auditLog("admin.import-apple-health.kickoff.denied", {
userId: admin.id,
ipAddress: getClientIp(request),
details: { reason: "target_user_missing", targetUserId },
});
return apiError(
`Target user '${targetUserId}' does not exist`,
422,
);
}
// Same content-hash idempotency as the user-facing route, but scoped
// by the target user — an admin re-uploading the same file for the
// same user resolves to the previous job.
const existing = await prisma.importJob.findFirst({
where: {
userId: targetUser.id,
uploadSha256: uploaded.sha256,
},
orderBy: { startedAt: "desc" },
});
if (existing) {
annotate({ meta: { idempotent_hit: true, job_id: existing.id } });
return apiSuccess(
{
jobId: existing.id,
status: existing.status,
idempotent: true,
},
202,
);
}
const boss = getGlobalBoss();
if (!boss) {
await auditLog("admin.import-apple-health.kickoff.denied", {
userId: admin.id,
ipAddress: getClientIp(request),
details: { reason: "worker_not_running" },
});
throw new HttpError(503, "Background worker is not running");
}
const importJob = await prisma.importJob.create({
data: {
userId: targetUser.id,
triggeredByAdminId: admin.id,
status: "queued",
uploadBytes: uploaded.bytes,
uploadSha256: uploaded.sha256,
},
});
const payload: AppleHealthImportPayload = {
userId: targetUser.id,
triggeredByAdminId: admin.id,
uploadPath: uploaded.filePath,
uploadBytes: uploaded.bytes,
enqueuedAt: new Date().toISOString(),
};
const bossJobId = await boss.send(APPLE_HEALTH_IMPORT_QUEUE, payload);
await prisma.importJob.update({
where: { id: importJob.id },
data: { pgBossJobId: bossJobId },
});
await auditLog("admin.import-apple-health.kickoff", {
userId: admin.id,
ipAddress: getClientIp(request),
details: {
jobId: importJob.id,
bossJobId: bossJobId ?? null,
targetUserId: targetUser.id,
targetUsername: targetUser.username,
uploadBytes: uploaded.bytes,
uploadSha256: uploaded.sha256,
},
});
return apiSuccess(
{
jobId: importJob.id,
status: "queued" as const,
targetUserId: targetUser.id,
},
202,
);
});
+6
View File
@@ -15,6 +15,7 @@ import {
invalidateServerDefaultTimezone,
isValidTimezone,
} from "@/lib/tz/resolver";
import { invalidateAppSettings } from "@/lib/cache/invalidate";
export const dynamic = "force-dynamic";
@@ -228,6 +229,11 @@ export const PUT = apiHandler(async (request: NextRequest) => {
invalidateServerDefaultTimezone();
}
// v1.4.34 IW-G — bust the bug-report status cache (global singleton)
// so the next read reflects the new GitHub-token / bug-report-enabled
// shape. Cheap call — the cache holds at most 10 entries.
invalidateAppSettings();
await auditLog("admin.settings.update", {
userId: user.id,
ipAddress: getClientIp(request),
+88 -1
View File
@@ -52,6 +52,7 @@ vi.mock("next/headers", () => ({
import { GET } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
interface MeasurementRow {
id: string;
@@ -89,6 +90,10 @@ function pulseRow(measuredAt: Date, value: number, id: string): MeasurementRow {
beforeEach(() => {
vi.resetAllMocks();
// v1.4.34 IW-G — reset the analytics LRU between tests so each case
// observes a cold cache (otherwise tests sharing a userId would land
// on the prior test's cached response).
__resetAllCachesForTests();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue(
@@ -172,11 +177,76 @@ describe("GET /api/analytics", () => {
expect(body.data.healthScore).toBeNull();
});
// v1.4.34 IW-B — the dashboard tile strip reads `lastSeenByType[type]?.daysAgo`
// and forwards it to each `<TrendCard>` so a metric the user hasn't
// logged in a while keeps its tile visible with an "Letzter Wert vor
// Xd" caption instead of disappearing.
it("emits lastSeenByType keyed on the freshest measuredAt per type", async () => {
const eightDaysAgo = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000);
const oneDayAgo = new Date(Date.now() - 1 * 24 * 60 * 60 * 1000);
vi.mocked(prisma.measurement.findMany).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(async (args: any) => {
if (args.where?.type === "WEIGHT" && !args.cursor) {
return [
{
id: "w-old",
measuredAt: eightDaysAgo,
value: 80.5,
source: "MANUAL",
deviceType: null,
},
] as never;
}
if (args.where?.type === "PULSE" && !args.cursor) {
return [
{
id: "p-fresh",
measuredAt: oneDayAgo,
value: 72,
source: "APPLE_HEALTH",
deviceType: "watch",
},
] as never;
}
return [] as never;
}) as never,
);
const res = await (
GET as unknown as (...args: never[]) => Promise<Response>
)();
expect(res.status).toBe(200);
// bfcache-friendly Cache-Control — verifies the IW-B header
// posture is on the wire.
expect(res.headers.get("Cache-Control")).toBe(
"private, max-age=0, must-revalidate",
);
const body = (await res.json()) as {
data: {
lastSeenByType: Record<
string,
{ lastSeenAt: string; daysAgo: number } | null
>;
};
};
expect(body.data.lastSeenByType.WEIGHT?.daysAgo).toBeGreaterThanOrEqual(7);
expect(body.data.lastSeenByType.WEIGHT?.daysAgo).toBeLessThanOrEqual(9);
expect(body.data.lastSeenByType.PULSE?.daysAgo).toBeGreaterThanOrEqual(0);
expect(body.data.lastSeenByType.PULSE?.daysAgo).toBeLessThanOrEqual(2);
// Types the user never logged report `null` so the tile-strip
// helper falls through without painting a caption.
expect(body.data.lastSeenByType.BLOOD_GLUCOSE).toBeNull();
});
// v1.4.33 C1 — slim summaries slice. The route branches on
// `?slice=summaries` BEFORE any chunked findMany; the two `$queryRaw`
// passes carry the per-type DataSummary shape with the same
// contract the dashboard tile strip reads.
it("returns the slim summaries slice when ?slice=summaries is set", async () => {
const fiveDaysAgo = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000);
// Aggregate pass + latest pass. The mock returns one row per pass.
vi.mocked(prisma.$queryRaw)
.mockResolvedValueOnce([
@@ -196,7 +266,9 @@ describe("GET /api/analytics", () => {
r2_90: 0.2,
},
] as never)
.mockResolvedValueOnce([{ type: "WEIGHT", value: 81.8 }] as never);
.mockResolvedValueOnce([
{ type: "WEIGHT", value: 81.8, measured_at: fiveDaysAgo },
] as never);
const req = new Request(
"http://localhost/api/analytics?slice=summaries",
@@ -205,6 +277,11 @@ describe("GET /api/analytics", () => {
GET as unknown as (req: Request) => Promise<Response>
)(req);
expect(res.status).toBe(200);
// v1.4.34 IW-B — bfcache-friendly directive rides on the slim
// slice too.
expect(res.headers.get("Cache-Control")).toBe(
"private, max-age=0, must-revalidate",
);
const body = (await res.json()) as {
data: {
summaries: Record<
@@ -216,6 +293,10 @@ describe("GET /api/analytics", () => {
}
>;
bmi: number | null;
lastSeenByType: Record<
string,
{ lastSeenAt: string; daysAgo: number } | null
>;
};
};
// The slim slice produced WEIGHT from the SQL pass; no chunked
@@ -226,5 +307,11 @@ describe("GET /api/analytics", () => {
expect(body.data.summaries.WEIGHT.slope30?.direction).toBe("down");
// Slim slice never carries BMI — the consumer re-derives.
expect(body.data.bmi).toBeNull();
// v1.4.34 IW-B — slim slice surfaces lastSeenByType too so the
// tile-strip caption works regardless of which slice the client
// read.
expect(body.data.lastSeenByType.WEIGHT?.daysAgo).toBeGreaterThanOrEqual(4);
expect(body.data.lastSeenByType.WEIGHT?.daysAgo).toBeLessThanOrEqual(6);
expect(body.data.lastSeenByType.PULSE).toBeNull();
});
});
+89 -5
View File
@@ -2,6 +2,8 @@ import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { apiSuccess } from "@/lib/api-response";
import { NO_STORE_BUT_BFCACHE } from "@/lib/http/cache-headers";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
import { summarize, type DataPoint } from "@/lib/analytics/trends";
import { computeSummariesSlice } from "@/lib/analytics/summaries-slice";
import { getBpTargets } from "@/lib/analytics/bp-targets";
@@ -63,10 +65,58 @@ export const GET = apiHandler(async (request?: Request) => {
// tile's `<InView>` boundary. Consumers that need only the headline
// tile values land on this branch and skip the heavy chain.
if (readSliceParam(request) === "summaries") {
const slim = await computeSummariesSlice(user.id);
return apiSuccess(slim);
// v1.4.34 IW-G — read-through the analytics cache keyed on
// (userId, slice). The slim slice is the dashboard tile strip's hot
// path; multiple dashboard mounts inside a 60-second TTL all hit a
// warm cache.
const slim = await cached(
caches.analytics as ServerCache<Awaited<ReturnType<typeof computeSummariesSlice>>>,
`${user.id}|summaries`,
() => computeSummariesSlice(user.id),
annotate,
);
// v1.4.34 IW-B — bfcache-friendly directive on the slim slice too
// so a back-forward navigation that landed on the dashboard tile
// strip can restore from memory instead of paying a full reload.
const slimRes = apiSuccess(slim);
slimRes.headers.set("Cache-Control", NO_STORE_BUT_BFCACHE);
return slimRes;
}
// v1.4.34 IW-G — wrap the heavy default-slice body in the analytics
// cache keyed on (userId, "default"). The dashboard, the checklist
// mount, and the Coach drawer all hit this endpoint within seconds
// of each other; the 60s TTL converts the 7.99s combined dashboard
// wait to a Map lookup on every subsequent caller.
const body = await cached(
caches.analytics as ServerCache<Awaited<ReturnType<typeof buildAnalyticsResponse>>>,
`${user.id}|default`,
() => buildAnalyticsResponse(user),
annotate,
);
const response = apiSuccess(body);
// v1.4.34 IW-B — bfcache-friendly directive so back-forward navigation
// restores the dashboard from memory. Per `src/lib/http/cache-headers.ts`:
// `private` keeps shared caches out of personal data, `max-age=0` forces
// revalidation on every navigation so session swaps detect on the wire,
// and `must-revalidate` holds the staleness contract. Replaces the
// framework's stock `no-store` which Chromium treats as a hard
// bfcache breaker.
response.headers.set("Cache-Control", NO_STORE_BUT_BFCACHE);
return response;
});
type AuthedUser = Awaited<ReturnType<typeof requireAuth>>["user"];
/**
* v1.4.34 IW-G — the heavy default-slice body, lifted out of the route
* handler so `cached()` can wrap it. Returns the raw JSON payload; the
* route handler attaches `Cache-Control` headers afterward. The split
* matches the v1.4.33 snapshot LRU's `buildCoachSnapshot` →
* `buildCoachSnapshotImpl` shape.
*/
async function buildAnalyticsResponse(user: AuthedUser) {
// v1.4.25 W7b — every day-bucket call inside this route now honours
// the user's display timezone. The legacy `berlinDayKey()` import
// remains for sleep-stage and correlation paths that share their
@@ -91,6 +141,19 @@ export const GET = apiHandler(async (request?: Request) => {
// when the column is null or malformed.
const sourcePriorityJson = user.sourcePriorityJson;
// v1.4.34 IW-B — capture the most-recent `measuredAt` per type so the
// dashboard tile strip can render an "Letzter Wert vor Xd" caption on
// tiles whose latest reading is older than a week. The series read
// already orders ascending (`fetchMeasurementSeriesChunked`'s stable
// `(measuredAt, id)` order); the last entry is the freshest sample.
// Surface as ISO + a server-computed `daysAgo` so the client never
// has to do tz-aware date math to colour the tile.
const nowForStaleness = new Date();
const lastSeenByType: Record<string, {
lastSeenAt: string;
daysAgo: number;
} | null> = {};
let totalRowsReadForAggregate = 0;
const measurementsByType = await Promise.all(
types.map((type) =>
@@ -98,6 +161,23 @@ export const GET = apiHandler(async (request?: Request) => {
includeSleepStage: true,
}).then((measurements) => {
totalRowsReadForAggregate += measurements.length;
// v1.4.34 IW-B — record the freshest `measuredAt` for this type
// (or null when the user has never logged this metric). The
// helper returns rows sorted ascending so `.at(-1)` is the
// most-recent point without an extra pass.
const latest = measurements.at(-1);
if (latest) {
const daysAgo = Math.floor(
(nowForStaleness.getTime() - latest.measuredAt.getTime()) /
(24 * 60 * 60 * 1000),
);
lastSeenByType[type] = {
lastSeenAt: latest.measuredAt.toISOString(),
daysAgo,
};
} else {
lastSeenByType[type] = null;
}
// v1.4.23 — Apple Health's sleep ingest stores one row per
// stage per night. Summarising the raw rows would treat each
// stage as its own datapoint and grossly understate "average
@@ -310,7 +390,7 @@ export const GET = apiHandler(async (request?: Request) => {
});
}
return apiSuccess({
return {
summaries: results,
bmi,
bpInTargetPct,
@@ -323,8 +403,12 @@ export const GET = apiHandler(async (request?: Request) => {
correlations,
healthScore,
sleepStages,
});
});
// v1.4.34 IW-B — per-type freshness map drives the dashboard's
// staleness caption on each `<TrendCard>`. Additive: clients that
// don't read the field stay unchanged.
lastSeenByType,
};
}
/**
* Per-stage sleep-minutes breakdown over the trailing 30 days.
+9
View File
@@ -21,6 +21,7 @@ import {
} from "@/lib/dashboard-layout";
import { Prisma } from "@/generated/prisma/client";
import { z } from "zod/v4";
import { invalidateUserDashboardWidgets } from "@/lib/cache/invalidate";
import type { NextRequest } from "next/server";
// Single source of truth — every widget id rendered by the Settings →
@@ -149,6 +150,10 @@ export const PUT = apiHandler(async (request: NextRequest) => {
meta: { visible_count: normalized.widgets.filter((w) => w.visible).length },
});
// v1.4.34 IW-G — bust the per-user dashboard-widgets cache so the
// next dashboard mount paints the new layout.
invalidateUserDashboardWidgets(user.id);
return apiSuccess(normalized);
});
@@ -162,5 +167,9 @@ export const DELETE = apiHandler(async () => {
annotate({ action: { name: "dashboard.widgets.reset" } });
// v1.4.34 IW-G — bust the per-user dashboard-widgets cache so the
// next dashboard mount paints the reset (default) layout.
invalidateUserDashboardWidgets(user.id);
return apiSuccess(DEFAULT_DASHBOARD_LAYOUT);
});
@@ -36,6 +36,7 @@ vi.mock("next/headers", () => ({
import { GET } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
@@ -65,6 +66,9 @@ const HIDDEN_TRIGGER_STRINGS = [
beforeEach(() => {
vi.resetAllMocks();
// v1.4.34 IW-G — reset achievement LRU between tests so each case
// observes a cold cache.
__resetAllCachesForTests();
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue(
[] as never,
@@ -36,6 +36,7 @@ vi.mock("next/headers", () => ({
import { GET } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
@@ -51,6 +52,9 @@ const SESSION_OK = {
beforeEach(() => {
vi.resetAllMocks();
// v1.4.34 IW-G — reset achievement LRU between tests so each case
// observes a cold cache.
__resetAllCachesForTests();
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue(
[] as never,
+58 -26
View File
@@ -2,6 +2,7 @@ import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { apiSuccess } from "@/lib/api-response";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
import {
ACHIEVEMENT_DEFINITIONS,
GAMIFICATION_ROLLOUT_AT,
@@ -278,7 +279,9 @@ function getOnTimePerfectDaySeries(
scheduledDate,
);
if (timing !== "on_time") {
// v1.4.34 IW-C — `early` is also a compliant bucket (dose taken
// within the 3h pre-window grace), so it preserves a perfect day.
if (timing !== "on_time" && timing !== "early") {
isPerfectDay = false;
break;
}
@@ -461,6 +464,58 @@ export const GET = apiHandler(async (request: NextRequest) => {
meta: { format: isIosFormat ? "ios" : "default" },
});
// v1.4.34 IW-G — cache the web-shape result keyed on userId. The
// iOS-format branch runs the locale-aware transform after the cache
// read so the cache stays format-agnostic and the achievement-progress
// dashboard duplicate (seen twice per dashboard mount in the v1.4.33
// HAR) coalesces into one builder call. Newly-unlocked achievements
// get persisted inside the builder so the second concurrent mount
// observes the up-to-date `persisted` state.
const result = await cached(
caches.achievements as ServerCache<AchievementsResult>,
user.id,
() => buildAchievementsResult(user),
annotate,
);
if (isIosFormat) {
const locale = await resolveServerLocale({
request,
userLocale: user.locale,
});
const t = getServerTranslator(locale);
const ios: IosAchievement[] = result.achievements.map((a) => ({
id: a.id,
key: a.id,
title: t.t(a.titleKey),
description: t.t(a.descriptionKey),
iconName: a.icon,
unlocked: a.unlocked,
unlockedAt: a.completedAt,
progress: Math.max(0, Math.min(1, a.progressPercent / 100)),
}));
return apiSuccess(ios);
}
return apiSuccess(result);
});
type AuthedUser = Awaited<ReturnType<typeof requireAuth>>["user"];
type AchievementsResult = Awaited<ReturnType<typeof buildAchievementsResult>>;
/**
* v1.4.34 IW-G — pulled out of the GET handler so `cached()` can wrap
* the heavy aggregation. Returns the locale-agnostic web payload; the
* iOS-format transform runs in the handler after the cache read.
*
* `prisma.userAchievement.createMany` inside the builder is kept here
* (rather than moved to the cache hit path) because new unlocks are
* a side effect of the same aggregate computation. A duplicate concurrent
* read coalesces through the cache's single-flight `pending` map so the
* createMany only fires once.
*/
async function buildAchievementsResult(user: AuthedUser) {
const now = new Date();
const userId = user.id;
const startDate = maxDate(user.createdAt, GAMIFICATION_ROLLOUT_AT);
@@ -866,31 +921,8 @@ export const GET = apiHandler(async (request: NextRequest) => {
metrics: redactedMetrics,
};
if (isIosFormat) {
const locale = await resolveServerLocale({
request,
userLocale: user.locale,
});
const t = getServerTranslator(locale);
// Same redaction principle: iOS clients receive opaque
// placeholders for hidden+locked entries. The native client
// mirrors the web-card opaque-placeholder UI when it sees the
// sentinel id `achievements.hiddenCard.title` come back.
const ios: IosAchievement[] = redactedAchievements.map((a) => ({
id: a.id,
key: a.id,
title: t.t(a.titleKey),
description: t.t(a.descriptionKey),
iconName: a.icon,
unlocked: a.unlocked,
unlockedAt: a.completedAt,
progress: Math.max(0, Math.min(1, a.progressPercent / 100)),
}));
return apiSuccess(ios);
}
return apiSuccess(result);
});
return result;
}
/**
* Hidden Easter-eggs ship to the client *only* as opaque cards while
@@ -0,0 +1,121 @@
/**
* Tests for the polling status endpoint. Covers the canonical envelope
* shape, the 404 on cross-user access, and the admin-trigger allow-list.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
const mocks = vi.hoisted(() => ({
importJobFindUnique: vi.fn(),
}));
vi.mock("@/lib/db", () => ({
prisma: {
importJob: { findUnique: mocks.importJobFindUnique },
},
}));
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
const OWNER_SESSION = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
};
const OTHER_SESSION = {
session: { id: "sess-2", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-99", username: "eve", role: "USER" as const },
};
const ADMIN_SESSION = {
session: { id: "sess-a", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "admin-1", username: "marc-admin", role: "ADMIN" as const },
};
const NOW = new Date("2026-05-15T10:00:00.000Z");
function makeRow(overrides: Partial<Record<string, unknown>> = {}) {
return {
id: "ij-1",
userId: "user-1",
triggeredByAdminId: null,
pgBossJobId: "boss-1",
status: "parsing",
failureReason: null,
uploadBytes: 12345,
uploadSha256: "abc",
exportedAt: null,
startedAt: NOW,
completedAt: null,
progress: { currentPhase: "parsing", recordsRead: 100, rowsUpserted: 0,
percent: null, elapsedMs: 1500 },
result: null,
...overrides,
};
}
beforeEach(() => {
vi.resetAllMocks();
});
describe("GET /api/import/apple-health-export/[jobId]/status", () => {
it("returns the row envelope to the owning user", async () => {
vi.mocked(getSession).mockResolvedValue(OWNER_SESSION as never);
mocks.importJobFindUnique.mockResolvedValue(makeRow());
const req = new NextRequest("http://localhost/api/import/apple-health-export/ij-1/status");
const res = await GET(req, { params: Promise.resolve({ jobId: "ij-1" }) });
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { status: string }; error: null };
expect(body.error).toBeNull();
expect(body.data.status).toBe("parsing");
});
it("returns 404 to a non-owner non-admin user", async () => {
vi.mocked(getSession).mockResolvedValue(OTHER_SESSION as never);
mocks.importJobFindUnique.mockResolvedValue(makeRow());
const req = new NextRequest("http://localhost/api/import/apple-health-export/ij-1/status");
const res = await GET(req, { params: Promise.resolve({ jobId: "ij-1" }) });
expect(res.status).toBe(404);
});
it("admits the triggering admin even when userId differs", async () => {
vi.mocked(getSession).mockResolvedValue(ADMIN_SESSION as never);
mocks.importJobFindUnique.mockResolvedValue(
makeRow({ triggeredByAdminId: "admin-1" }),
);
const req = new NextRequest("http://localhost/api/import/apple-health-export/ij-1/status");
const res = await GET(req, { params: Promise.resolve({ jobId: "ij-1" }) });
expect(res.status).toBe(200);
});
it("returns 404 when the job row is missing", async () => {
vi.mocked(getSession).mockResolvedValue(OWNER_SESSION as never);
mocks.importJobFindUnique.mockResolvedValue(null);
const req = new NextRequest("http://localhost/api/import/apple-health-export/ij-1/status");
const res = await GET(req, { params: Promise.resolve({ jobId: "ij-1" }) });
expect(res.status).toBe(404);
});
it("returns 401 when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const req = new NextRequest("http://localhost/api/import/apple-health-export/ij-1/status");
const res = await GET(req, { params: Promise.resolve({ jobId: "ij-1" }) });
expect(res.status).toBe(401);
});
});
@@ -0,0 +1,77 @@
/**
* `GET /api/import/apple-health-export/[jobId]/status` — polling
* endpoint for an in-flight Apple Health import.
*
* Returns the canonical `ImportJobStatusResponse` envelope (§8 of
* `.planning/research/v1434-r-1-xml-import.md`). The polling cadence
* the iOS client uses:
* - every 2 s while `queued | unpacking | parsing | upserting`
* - every 30 s once `done | failed` (last-known state is fine)
*
* Authorisation: the row's `userId` must match the requester or the
* requester is the admin who kicked it off via the admin variant.
*/
import type { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiError, apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
export const dynamic = "force-dynamic";
interface RouteContext {
params: Promise<{ jobId: string }>;
}
interface ImportJobStatusResponse {
jobId: string;
status: string;
startedAt: string;
completedAt: string | null;
uploadBytes: number;
exportedAt: string | null;
progress: Record<string, unknown>;
result: Record<string, unknown> | null;
failureReason: string | null;
}
export const GET = apiHandler(
async (_request: NextRequest, ctx: RouteContext) => {
const { user } = await requireAuth();
const { jobId } = await ctx.params;
annotate({
action: { name: "import.apple-health.status" },
meta: { job_id: jobId },
});
const row = await prisma.importJob.findUnique({ where: { id: jobId } });
if (!row) {
return apiError("Import job not found", 404);
}
// Authorisation: the owner can see their own job; the admin who
// triggered it can see it from the admin route. Any other caller
// gets a 404 (not 403 — we don't leak existence to outsiders).
const isOwner = row.userId === user.id;
const isTriggeringAdmin =
row.triggeredByAdminId !== null && row.triggeredByAdminId === user.id;
if (!isOwner && !isTriggeringAdmin) {
return apiError("Import job not found", 404);
}
const body: ImportJobStatusResponse = {
jobId: row.id,
status: row.status,
startedAt: row.startedAt.toISOString(),
completedAt: row.completedAt?.toISOString() ?? null,
uploadBytes: row.uploadBytes,
exportedAt: row.exportedAt?.toISOString() ?? null,
progress: (row.progress as Record<string, unknown>) ?? {},
result: (row.result as Record<string, unknown> | null) ?? null,
failureReason: row.failureReason,
};
return apiSuccess(body, 200);
},
);
@@ -0,0 +1,112 @@
/**
* Smoke / contract tests for the Apple Health import endpoints.
*
* Targets the cookie + Bearer auth path, the 413 size-cap, and the
* 503 worker-not-running path. End-to-end ingest (multipart streaming
* + parser + worker) is covered separately by the parser unit suite
* + the integration suite under `tests/integration`.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
const mocks = vi.hoisted(() => ({
checkRateLimit: vi.fn().mockResolvedValue({ allowed: true }),
bossSend: vi.fn().mockResolvedValue("boss-job-1"),
getGlobalBoss: vi.fn(),
importJobCreate: vi.fn(),
importJobFindFirst: vi.fn().mockResolvedValue(null),
importJobUpdate: vi.fn(),
}));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: mocks.checkRateLimit,
}));
vi.mock("@/lib/jobs/boss-instance", () => ({
getGlobalBoss: mocks.getGlobalBoss,
}));
vi.mock("@/lib/db", () => ({
prisma: {
importJob: {
create: mocks.importJobCreate,
findFirst: mocks.importJobFindFirst,
update: mocks.importJobUpdate,
},
},
}));
import { POST } from "../route";
import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
};
beforeEach(() => {
vi.resetAllMocks();
mocks.checkRateLimit.mockResolvedValue({ allowed: true });
mocks.bossSend.mockResolvedValue("boss-job-1");
mocks.getGlobalBoss.mockReturnValue({ send: mocks.bossSend });
mocks.importJobCreate.mockResolvedValue({ id: "ij-1" });
mocks.importJobFindFirst.mockResolvedValue(null);
mocks.importJobUpdate.mockResolvedValue({ id: "ij-1" });
});
describe("POST /api/import/apple-health-export", () => {
it("returns 401 when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const req = new NextRequest("http://localhost/api/import/apple-health-export", {
method: "POST",
headers: { "content-type": "multipart/form-data; boundary=---x" },
body: "stub",
});
const res = await POST(req);
expect(res.status).toBe(401);
});
it("returns 413 when Content-Length exceeds the 1.5 GB cap", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const headers = new Headers({
"content-type": "multipart/form-data; boundary=---x",
"content-length": String(2 * 1024 * 1024 * 1024),
});
const req = new NextRequest("http://localhost/api/import/apple-health-export", {
method: "POST",
headers,
body: "stub",
});
const res = await POST(req);
expect(res.status).toBe(413);
});
it("returns 429 when the rate-limit window is exhausted", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
mocks.checkRateLimit.mockResolvedValueOnce({ allowed: false });
const req = new NextRequest("http://localhost/api/import/apple-health-export", {
method: "POST",
headers: { "content-type": "multipart/form-data; boundary=---x" },
body: "stub",
});
const res = await POST(req);
expect(res.status).toBe(429);
});
});
@@ -0,0 +1,176 @@
/**
* `POST /api/import/apple-health-export` — user-facing kick-off for an
* Apple Health `export.zip` import.
*
* Streams the upload directly to disk (`/tmp/healthlog-upload-*.bin`)
* without buffering the full body in memory, creates an `ImportJob`
* row in `queued`, and enqueues an `apple-health-import` pg-boss job.
* Returns `{ jobId }` so the client can poll
* `GET /api/import/apple-health-export/[jobId]/status`.
*
* Idempotency: a re-upload of the exact same file (same SHA-256 of
* the bytes) short-circuits to the previous `ImportJob` id without
* re-queueing — the iOS client cannot reliably emit a stable
* `Idempotency-Key` for a 1 GB file, so we hash the bytes and dedup
* on content.
*
* Locks per `.planning/research/v1434-r-1-xml-import.md` §5.3.
*/
import type { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth, HttpError } from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { checkRateLimit } from "@/lib/rate-limit";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
import {
APPLE_HEALTH_IMPORT_QUEUE,
type AppleHealthImportPayload,
} from "@/lib/jobs/apple-health-import-worker";
import { streamMultipartToDisk } from "@/lib/multipart/stream-to-disk";
export const dynamic = "force-dynamic";
/**
* Hard cap on the upload size. Apple's largest observed exports
* sit around 800 MB for a 10-year iCloud-synced account; 1.5 GB
* leaves comfortable margin for the long tail.
*/
const MAX_UPLOAD_BYTES = 1.5 * 1024 * 1024 * 1024;
/** Rate-limit window: three uploads per minute per user. */
const RATE_LIMIT_MAX = 3;
const RATE_LIMIT_WINDOW_MS = 60_000;
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
annotate({ action: { name: "import.apple-health.kickoff" } });
// Rate limit before touching the body — protects against a flood of
// 1 GB uploads from a single user.
const rl = await checkRateLimit(
`import:apple-health:${user.id}`,
RATE_LIMIT_MAX,
RATE_LIMIT_WINDOW_MS,
);
if (!rl.allowed) {
throw new HttpError(429, "Too many import uploads, try again later");
}
// Cheap pre-flight on the declared Content-Length. The streaming
// sink below enforces the hard cap as well — a missing/wrong
// content-length cannot bypass it.
const declaredBytes = Number(request.headers.get("content-length") ?? 0);
if (declaredBytes > MAX_UPLOAD_BYTES) {
await auditLog("import.apple-health.kickoff.denied", {
userId: user.id,
ipAddress: getClientIp(request),
details: {
reason: "content_length_exceeded",
contentLength: declaredBytes,
},
});
return apiError("Upload exceeds 1.5 GB limit", 413);
}
const body = request.body;
if (!body) {
return apiError("Request body is required", 400);
}
// Stream the upload to disk, computing a SHA-256 in the same pass.
let uploaded;
try {
uploaded = await streamMultipartToDisk(
body,
request.headers.get("content-type"),
{
maxBytes: MAX_UPLOAD_BYTES,
fieldName: "file",
tmpPrefix: "healthlog-apple-health-import",
},
);
} catch (err) {
const message = err instanceof Error ? err.message : "upload_failed";
await auditLog("import.apple-health.kickoff.denied", {
userId: user.id,
ipAddress: getClientIp(request),
details: { reason: "stream_to_disk_failed", message },
});
return apiError(`Multipart upload failed: ${message}`, 422);
}
// Content-hash idempotency: a re-upload of the same bytes resolves
// to the previous ImportJob row instead of re-queueing.
const existing = await prisma.importJob.findFirst({
where: {
userId: user.id,
uploadSha256: uploaded.sha256,
},
orderBy: { startedAt: "desc" },
});
if (existing) {
annotate({ meta: { idempotent_hit: true, job_id: existing.id } });
return apiSuccess(
{
jobId: existing.id,
status: existing.status,
idempotent: true,
},
202,
);
}
const boss = getGlobalBoss();
if (!boss) {
await auditLog("import.apple-health.kickoff.denied", {
userId: user.id,
ipAddress: getClientIp(request),
details: { reason: "worker_not_running" },
});
throw new HttpError(503, "Background worker is not running");
}
const importJob = await prisma.importJob.create({
data: {
userId: user.id,
status: "queued",
uploadBytes: uploaded.bytes,
uploadSha256: uploaded.sha256,
},
});
const payload: AppleHealthImportPayload = {
userId: user.id,
uploadPath: uploaded.filePath,
uploadBytes: uploaded.bytes,
enqueuedAt: new Date().toISOString(),
};
const bossJobId = await boss.send(APPLE_HEALTH_IMPORT_QUEUE, payload);
await prisma.importJob.update({
where: { id: importJob.id },
data: { pgBossJobId: bossJobId },
});
await auditLog("import.apple-health.kickoff", {
userId: user.id,
ipAddress: getClientIp(request),
details: {
jobId: importJob.id,
bossJobId: bossJobId ?? null,
uploadBytes: uploaded.bytes,
uploadSha256: uploaded.sha256,
},
});
return apiSuccess(
{
jobId: importJob.id,
status: "queued" as const,
},
202,
);
});
+9
View File
@@ -9,6 +9,7 @@ import {
safeJson,
} from "@/lib/api-response";
import { updateMeasurementSchema } from "@/lib/validations/measurement";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { Prisma } from "@/generated/prisma/client";
import { NextRequest } from "next/server";
@@ -107,6 +108,10 @@ export const PUT = apiHandler(
},
});
// v1.4.34 IW-G — bust per-user analytics + achievements + workouts
// caches so subsequent reads reflect the edited row.
invalidateUserMeasurements(user.id);
return apiSuccess(measurement);
},
);
@@ -141,6 +146,10 @@ export const DELETE = apiHandler(
},
});
// v1.4.34 IW-G — bust per-user analytics + achievements + workouts
// caches so subsequent reads reflect the deletion.
invalidateUserMeasurements(user.id);
return apiSuccess({ deleted: true });
},
);
+9
View File
@@ -37,6 +37,7 @@ import { validateMeasurementRange } from "@/lib/validations/measurement";
import { deviceTypeEnum } from "@/lib/validations/source-priority";
import { checkRateLimit } from "@/lib/rate-limit";
import { enqueuePrDetection } from "@/lib/jobs/pr-detection";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { Prisma } from "@/generated/prisma/client";
// v1.4.25 W16c — historical-backfill threshold for PR push
@@ -366,6 +367,14 @@ async function postBatch(request: NextRequest): Promise<Response> {
},
});
// v1.4.34 IW-G — bust per-user analytics + achievements + workouts
// caches when at least one row landed so the next read picks up the
// ingested batch. Skipped-only ingests don't change state, so we
// gate the invalidation on `insertedCount > 0`.
if (insertedCount > 0) {
invalidateUserMeasurements(user.id);
}
return apiSuccess({
processed: entries.length,
inserted: insertedCount,
@@ -31,6 +31,7 @@ import {
getClientIp,
safeJson,
} from "@/lib/api-response";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
const MAX_BATCH_ENTRIES = 500;
@@ -103,5 +104,12 @@ async function deleteByExternalIds(request: NextRequest): Promise<Response> {
meta: { processed: externalIds.length, deleted: result.count },
});
// v1.4.34 IW-G — bust per-user analytics + achievements + workouts
// caches when at least one row deleted so the next read reflects the
// reconciliation. A 0-delete batch is a no-op and skips the eviction.
if (result.count > 0) {
invalidateUserMeasurements(user.id);
}
return apiSuccess({ deletedCount: result.count });
}
+9
View File
@@ -20,6 +20,7 @@ import {
} from "@/lib/measurements/range-aggregation";
import { CUMULATIVE_HK_TYPES } from "@/lib/measurements/apple-health-mapping";
import { withIdempotency } from "@/lib/idempotency";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { NextRequest } from "next/server";
import type {
MeasurementType,
@@ -214,6 +215,10 @@ async function postMeasurement(request: NextRequest) {
},
});
// v1.4.34 IW-G — flush every cache that reflects this user's
// measurement set so the next read paints the new rows.
invalidateUserMeasurements(user.id);
return apiSuccess(results, 201);
}
@@ -270,5 +275,9 @@ async function postMeasurement(request: NextRequest) {
},
});
// v1.4.34 IW-G — flush every cache that reflects this user's
// measurement set so the next read paints the new row.
invalidateUserMeasurements(user.id);
return apiSuccess(measurement, 201);
}
@@ -80,6 +80,7 @@ export const GET = apiHandler(
let onTime = 0;
let late = 0;
let veryLate = 0;
let early = 0;
for (const evt of takenEvents) {
if (medication.schedules.length === 0) {
@@ -111,7 +112,13 @@ export const GET = apiHandler(
dayStart, // the scheduled date
);
// v1.4.34 IW-C — `early` is the new compliant bucket; it counts
// alongside `onTime` for the heatmap so a proactive logger reads
// green. The classifier still emits a distinct `"early"` value
// for downstream consumers that want to differentiate; the
// separate counter is surfaced on the daily entry below.
if (timing === "on_time") onTime++;
else if (timing === "early") early++;
else if (timing === "late") late++;
else veryLate++;
}
@@ -120,9 +127,10 @@ export const GET = apiHandler(
expected: schedulesPerDay,
taken: takenEvents.length,
skipped: dayEvents.filter((e) => e.skipped).length,
onTime,
onTime: onTime + early,
late,
veryLate,
early,
};
}
@@ -9,6 +9,7 @@ import {
safeJson,
} from "@/lib/api-response";
import { updateIntakeEventSchema } from "@/lib/validations/medication";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { NextRequest } from "next/server";
type RouteParams = { params: Promise<{ id: string; eventId: string }> };
@@ -62,6 +63,10 @@ export const PUT = apiHandler(
meta: { medication_id: id },
});
// v1.4.34 IW-G — bust per-user medications + compliance + achievement
// caches so the next read reflects the edited event.
invalidateUserMedications(user.id);
return apiSuccess(updated);
},
);
@@ -98,6 +103,10 @@ export const DELETE = apiHandler(
meta: { medication_id: id },
});
// v1.4.34 IW-G — bust per-user medications + compliance + achievement
// caches so the next read reflects the deletion.
invalidateUserMedications(user.id);
return apiSuccess({ deleted: true });
},
);
@@ -15,6 +15,7 @@ import {
import { withIdempotency } from "@/lib/idempotency";
import { consumeOneDose } from "@/lib/medications/inventory/service";
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { NextRequest } from "next/server";
type RouteParams = { params: Promise<{ id: string }> };
@@ -154,6 +155,10 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
},
});
// v1.4.34 IW-G — bust per-user medications + compliance + achievement
// caches so the next read reflects the dose event.
invalidateUserMedications(user.id);
return apiSuccess(event, 201);
}
+9
View File
@@ -9,6 +9,7 @@ import {
safeJson,
} from "@/lib/api-response";
import { updateMedicationSchema } from "@/lib/validations/medication";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import {
deleteMedicationCategory,
getMedicationCategories,
@@ -177,6 +178,10 @@ export const PUT = apiHandler(
},
});
// v1.4.34 IW-G — bust per-user medications + compliance + achievement
// caches so the next read reflects the schedule change.
invalidateUserMedications(user.id);
return apiSuccess({
...medication,
category: normalizedCategory,
@@ -222,6 +227,10 @@ export const DELETE = apiHandler(
},
});
// v1.4.34 IW-G — bust per-user medications + compliance + achievement
// caches so the next read reflects the deletion.
invalidateUserMedications(user.id);
return apiSuccess({ deleted: true });
},
);
@@ -37,6 +37,7 @@ vi.mock("next/headers", () => ({
import { GET, POST } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
@@ -45,6 +46,9 @@ const SESSION_OK = {
beforeEach(() => {
vi.resetAllMocks();
// v1.4.34 IW-G — reset compliance LRU between tests so each case
// observes a cold cache.
__resetAllCachesForTests();
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue(
[] as never,
);
@@ -40,6 +40,7 @@ import {
} from "@/lib/api-response";
import { withIdempotency } from "@/lib/idempotency";
import { checkRateLimit } from "@/lib/rate-limit";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
const MAX_ENTRIES_PER_BATCH = 500;
const BATCH_RATE_LIMIT_MAX = 60;
@@ -205,6 +206,13 @@ async function postBulk(request: NextRequest): Promise<Response> {
},
});
// v1.4.34 IW-G — bust per-user medications + compliance + achievement
// caches when at least one row landed so the next read reflects the
// ingested batch.
if (inserted > 0) {
invalidateUserMedications(user.id);
}
return apiSuccess({
processed: entries.length,
inserted,
+50 -13
View File
@@ -24,6 +24,8 @@ import { annotate } from "@/lib/logging/context";
import { prisma } from "@/lib/db";
import { auditLog } from "@/lib/auth/audit";
import { userDayKey, DEFAULT_TIMEZONE } from "@/lib/tz/resolver";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
const querySchema = z.object({
scope: z.enum(["today", "compliance"]),
@@ -109,16 +111,54 @@ export const GET = apiHandler(async (request: NextRequest) => {
);
}
// compliance: per-day scheduled vs taken for the last N days
const start = new Date(Date.now() - days * 86_400_000);
// v1.4.34 IW-G — compliance: per-day scheduled vs taken for the last
// N days. Cached at a 15-minute TTL because daily compliance buckets
// are slow-moving (intake events trickle in, yesterday's row doesn't
// move). Cache key carries the userTz so a user who changes timezone
// doesn't read another tz's bucketing.
const result = await cached(
caches.medicationsIntake as ServerCache<ComplianceBucket[]>,
`${user.id}|compliance|${days}|${userTz}`,
() => buildComplianceBuckets(user.id, days, userTz),
annotate,
);
annotate({
action: { name: "medications.intake.compliance" },
meta: { days, count: result.length },
});
return apiSuccess(result);
});
interface ComplianceBucket {
date: string;
scheduled: number;
taken: number;
}
/**
* v1.4.34 IW-G — pulled out of the GET handler so `cached()` can wrap
* the per-user compliance aggregation. Pure function over the user's
* intake events + the requested window; deterministic given a fixed
* "now" wall-clock (we anchor on `Date.now()` once at call time so a
* 15-minute cached row stays internally consistent).
*/
async function buildComplianceBuckets(
userId: string,
days: number,
userTz: string,
): Promise<ComplianceBucket[]> {
const nowMs = Date.now();
const start = new Date(nowMs - days * 86_400_000);
const events = await prisma.medicationIntakeEvent.findMany({
where: { userId: user.id, scheduledFor: { gte: start } },
where: { userId, scheduledFor: { gte: start } },
select: { scheduledFor: true, takenAt: true, skipped: true },
});
const buckets = new Map<string, { scheduled: number; taken: number }>();
for (let i = 0; i < days; i++) {
const d = new Date(Date.now() - i * 86_400_000);
const d = new Date(nowMs - i * 86_400_000);
buckets.set(userDayKey(d, userTz), { scheduled: 0, taken: 0 });
}
for (const e of events) {
@@ -129,17 +169,10 @@ export const GET = apiHandler(async (request: NextRequest) => {
if (e.takenAt && !e.skipped) bucket.taken += 1;
}
const result = [...buckets.entries()]
return [...buckets.entries()]
.map(([date, v]) => ({ date, scheduled: v.scheduled, taken: v.taken }))
.sort((a, b) => a.date.localeCompare(b.date));
annotate({
action: { name: "medications.intake.compliance" },
meta: { days, count: result.length },
});
return apiSuccess(result);
});
}
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
@@ -201,5 +234,9 @@ export const POST = apiHandler(async (request: NextRequest) => {
meta: { intakeId, status },
});
// v1.4.34 IW-G — bust the medications + compliance + achievement
// caches for this user so the next read reflects the dose change.
invalidateUserMedications(user.id);
return apiSuccess(updated);
});
+5
View File
@@ -15,6 +15,7 @@ import {
} from "@/lib/medication-category";
import { serializeScheduleRecurrence } from "@/lib/medication-schedule";
import { getUserTodayBounds } from "@/lib/timezone";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { NextRequest } from "next/server";
export const GET = apiHandler(async () => {
@@ -153,6 +154,10 @@ export const POST = apiHandler(async (request: NextRequest) => {
},
});
// v1.4.34 IW-G — bust per-user medications + compliance + achievement
// caches so the next read reflects the new schedule.
invalidateUserMedications(user.id);
return apiSuccess(
{
...medication,
+7
View File
@@ -14,6 +14,7 @@ import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { moodDateKey, DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
import { invalidateUserMood } from "@/lib/cache/invalidate";
type RouteParams = { params: Promise<{ id: string }> };
@@ -108,6 +109,9 @@ export const PUT = apiHandler(
meta: { moodEntryId: id },
});
// v1.4.34 IW-G — bust per-user mood + achievements + analytics caches.
invalidateUserMood(user.id);
return apiSuccess({ ...entry, tags: parseTags(entry.tags) });
},
);
@@ -137,6 +141,9 @@ export const DELETE = apiHandler(
meta: { moodEntryId: id },
});
// v1.4.34 IW-G — bust per-user mood + achievements + analytics caches.
invalidateUserMood(user.id);
return apiSuccess({ deleted: true });
},
);
+8
View File
@@ -42,6 +42,7 @@ import {
moodSourceEnum,
} from "@/lib/validations/moodlog";
import { moodDateKey, DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
import { invalidateUserMood } from "@/lib/cache/invalidate";
const MAX_ENTRIES_PER_BATCH = 500;
const BATCH_RATE_LIMIT_MAX = 60;
@@ -210,6 +211,13 @@ async function postBulk(request: NextRequest): Promise<Response> {
},
});
// v1.4.34 IW-G — bust per-user mood + achievements + analytics caches
// when at least one row landed so the next read picks up the ingested
// batch. Skipped / duplicate-only ingests are no-ops.
if (inserted > 0) {
invalidateUserMood(user.id);
}
return apiSuccess({
processed: entries.length,
inserted,
+4
View File
@@ -17,6 +17,7 @@ import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { withIdempotency } from "@/lib/idempotency";
import { moodDateKey, DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
import { invalidateUserMood } from "@/lib/cache/invalidate";
function parseTags(tags: string | null): string[] {
if (!tags) return [];
@@ -125,6 +126,9 @@ async function postMoodEntry(request: NextRequest) {
meta: { moodEntryId: entry.id, mood },
});
// v1.4.34 IW-G — bust per-user mood + achievements + analytics caches.
invalidateUserMood(user.id);
return apiSuccess({ ...entry, tags: parseTags(entry.tags) }, 201);
} catch (err) {
if (
+9
View File
@@ -63,6 +63,7 @@ import {
import { withIdempotency } from "@/lib/idempotency";
import { checkRateLimit } from "@/lib/rate-limit";
import { enqueuePrDetection } from "@/lib/jobs/pr-detection";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import {
createBatchWorkoutSchema,
MAX_WORKOUTS_PER_BATCH,
@@ -523,6 +524,14 @@ async function postBatch(request: NextRequest): Promise<Response> {
},
});
// v1.4.34 IW-G — bust per-user analytics + achievements + workouts
// caches when at least one row landed. Workouts ride on the
// measurements bucket because achievements / analytics also touch
// workout-derived metrics.
if (insertedCount > 0) {
invalidateUserMeasurements(user.id);
}
return apiSuccess({
processed: workouts.length,
inserted: insertedCount,