feat(notifications): coalesce the intake sync push per user and strip its payload

The MEDICATION_INTAKE_SYNC fan-out used to fire one silent APNs per
distinct dose slot, so a bulk intake marking five doses woke every other
device five times. Replace the per-slot dispatch with a per-user
coalescer: the first mutation in a burst dispatches immediately, every
further mutation inside the 2 s window folds into one trailing fan-out.
A bulk request now costs exactly one queue call, and a rapid burst of N
single-dose mutations costs at most two fan-outs. The window state is
in-process; multiple app instances throttle independently, which is
accepted because the iOS reconcile is idempotent and the deployment
model is a single container.

The silent payload shrinks to a pure sync trigger — eventType +
syncedAt. The per-slot medicationId / scheduledFor fields are gone: the
iOS handler runs a full reconcile regardless, a coalesced burst has no
single slot to name, and a push payload travels through Apple's
infrastructure, so it now carries no health data by construction. The
Live Activity end push likewise sends only the ActivityKit envelope.

The trailing flush keeps the origin skip only when every coalesced
mutation came from the same device; a mixed-origin burst wakes everyone.
Each flush still records one push_attempts ledger row, reaps
hard-rejected device tokens, and annotates the wide event with the
recipient count and coalesced-mutation count.
This commit is contained in:
Marc-André Bombeck committed 2026-07-07 10:21:53 +02:00
1 parent 0da11811e2
commit b9b38d182c
7 files changed
+512 -283

No files matched your search

@@ -54,10 +54,10 @@ vi.mock("@/lib/medications/inventory/consumption", () => ({
}));
// v1.17.1 (#22) — silent cross-device intake sync. Mocked so the route
// test asserts the wiring (called with the right slot + origin token)
// without reaching the APNs senders.
// test asserts the wiring (queued with the right origin token) without
// reaching the APNs senders or the coalescing timers.
vi.mock("@/lib/notifications/medication-intake-sync", () => ({
dispatchMedicationIntakeSync: vi.fn().mockResolvedValue(undefined),
queueMedicationIntakeSync: vi.fn(),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
@@ -82,7 +82,7 @@ import {
consumeForIntake,
restoreForIntake,
} from "@/lib/medications/inventory/consumption";
import { dispatchMedicationIntakeSync } from "@/lib/notifications/medication-intake-sync";
import { queueMedicationIntakeSync } from "@/lib/notifications/medication-intake-sync";
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
const SESSION_OK = {
@@ -425,11 +425,9 @@ describe("POST /api/medications/intake", () => {
const res = await POST(r);
expect(res.status).toBe(200);
expect(dispatchMedicationIntakeSync).toHaveBeenCalledTimes(1);
expect(dispatchMedicationIntakeSync).toHaveBeenCalledWith({
expect(queueMedicationIntakeSync).toHaveBeenCalledTimes(1);
expect(queueMedicationIntakeSync).toHaveBeenCalledWith({
userId: "user-1",
medicationId: "m1",
scheduledFor: "2026-05-18T10:00:00.000Z",
originDeviceToken: "origin-device-token",
});
});
@@ -63,11 +63,19 @@ vi.mock("next/headers", () => ({
})),
}));
// (#22) — silent cross-device intake sync. Mocked so the route test can
// assert the batch queues exactly ONE fan-out without reaching the APNs
// senders or the coalescing timers.
vi.mock("@/lib/notifications/medication-intake-sync", () => ({
queueMedicationIntakeSync: vi.fn(),
}));
import { POST } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { checkRateLimit } from "@/lib/rate-limit";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { queueMedicationIntakeSync } from "@/lib/notifications/medication-intake-sync";
import {
consumeForIntake,
restoreForIntake,
@@ -313,6 +321,61 @@ describe("POST /api/medications/intake/bulk — v1.8.2 reconcile", () => {
});
});
it("queues exactly ONE intake-sync fan-out for a multi-entry batch", async () => {
// Two pending rows at the day's two slots; the batch resolves both.
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
{
id: "row-am",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
{
id: "row-pm",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T17:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.update)
.mockResolvedValueOnce({ id: "row-am" } as never)
.mockResolvedValueOnce({ id: "row-pm" } as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
},
{
medicationId: "med-1",
scheduledFor: "2026-06-15T17:00:30.000Z",
takenAt: "2026-06-15T17:02:00.000Z",
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { updated: number } };
expect(body.data.updated).toBe(2);
// The whole batch produces ONE queued fan-out, not one per dose; the
// web caller carries no X-Device-Id, so no origin is excluded.
expect(queueMedicationIntakeSync).toHaveBeenCalledTimes(1);
expect(queueMedicationIntakeSync).toHaveBeenCalledWith({
userId: "user-1",
originDeviceToken: null,
});
});
it("C1 — a same-slot P2002 on create converges via re-find+update, not dropped as duplicate", async () => {
// First slot find empty → create races a P2002 → re-find returns the
// racing pending row → update applies the incoming takenAt.
+7 -7
View File
@@ -68,7 +68,7 @@ import {
type InjectionSiteValue,
} from "@/lib/validations/medication";
import type { InjectionSiteKey } from "@/lib/medications/injection-sites";
import { dispatchMedicationIntakeSyncBulk } from "@/lib/notifications/medication-intake-sync";
import { queueMedicationIntakeSync } from "@/lib/notifications/medication-intake-sync";
import { dispatchMedicationIntakeWebClearBulk } from "@/lib/notifications/web-push-clear";
import { countOutstandingDosesToday } from "@/lib/medications/outstanding-doses";
@@ -702,15 +702,15 @@ async function postBulk(request: NextRequest): Promise<Response> {
}
}
// v1.17.1 (#22) — silent cross-device intake sync. One push per device
// per distinct affected slot (the map de-dupes), excluding the
// originating device (`X-Device-Id` = registered `Device.token`).
// APNs-only, best-effort, fire-and-forget: the canonical rows are already
// v1.17.1 (#22) — silent cross-device intake sync. ONE queued fan-out
// for the whole batch regardless of how many slots it touched (the
// per-user coalescer folds bursts further), excluding the originating
// device (`X-Device-Id` = registered `Device.token`). APNs-only,
// best-effort, fire-and-forget: the canonical rows are already
// persisted, so a sync-push miss never affects the batch response.
if (syncSlots.size > 0) {
void dispatchMedicationIntakeSyncBulk({
queueMedicationIntakeSync({
userId: user.id,
slots: Array.from(syncSlots.values()),
originDeviceToken: request.headers.get("x-device-id"),
});
+3 -5
View File
@@ -49,7 +49,7 @@ import {
injectionSiteEnum,
type InjectionSiteValue,
} from "@/lib/validations/medication";
import { dispatchMedicationIntakeSync } from "@/lib/notifications/medication-intake-sync";
import { queueMedicationIntakeSync } from "@/lib/notifications/medication-intake-sync";
import { dispatchMedicationIntakeWebClear } from "@/lib/notifications/web-push-clear";
import { countOutstandingDosesToday } from "@/lib/medications/outstanding-doses";
@@ -522,14 +522,12 @@ export const POST = apiHandler(async (request: NextRequest) => {
// v1.17.1 (#22) — silent cross-device intake sync. Wake the user's OTHER
// iOS devices so a running Live Activity / Home-Screen widget reconciles
// the dose state changed here. APNs-only, best-effort, fire-and-forget:
// the dose state changed here. APNs-only, best-effort, coalesced per user:
// the canonical row is already persisted, so a sync-push miss never
// affects the response. The originating device (the one that POSTed) is
// excluded via its `X-Device-Id` (= registered `Device.token`).
void dispatchMedicationIntakeSync({
queueMedicationIntakeSync({
userId: user.id,
medicationId: existing.medicationId,
scheduledFor: (movedTo ?? existing.scheduledFor).toISOString(),
originDeviceToken: request.headers.get("x-device-id"),
});