mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
feat: separate notification event anchors
- Store record-scoped scheduler events outside delivery attempts\n- Keep delivery diagnostics free of bookkeeping rows
This commit is contained in:
1 parent
2999b75ea6
commit
9380ea0f18
8 files changed
+85
-48
No files matched your search
@@ -68,7 +68,6 @@ vi.mock("@/lib/crypto", () => ({
|
||||
import { GET } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireAdmin, HttpError } from "@/lib/api-handler";
|
||||
import { REMINDER_DEDUP_CHANNEL } from "@/lib/notifications/reminder-dedup";
|
||||
|
||||
const ADMIN_USER_ID = "admin-1";
|
||||
const ADMIN_CTX = {
|
||||
@@ -405,19 +404,15 @@ describe("GET /api/admin/notifications/diagnostic — recentPushAttempts", () =>
|
||||
expect(args.take).toBe(20);
|
||||
});
|
||||
|
||||
it("excludes reminder-dedup bookkeeping rows so the last 20 are real sends", async () => {
|
||||
// The medication tick anchors its per-slot dedup in this table under a
|
||||
// sentinel channel. Letting those rows into the trailing window would
|
||||
// push the actual delivery attempts — the thing an operator opens this
|
||||
// endpoint for — off the list.
|
||||
it("reads recipient-scoped delivery attempts without bookkeeping sentinels", async () => {
|
||||
vi.mocked(requireAdmin).mockResolvedValue(ADMIN_CTX);
|
||||
vi.mocked(prisma.pushAttempt.findMany).mockResolvedValue([] as never);
|
||||
|
||||
await GET();
|
||||
|
||||
const args = vi.mocked(prisma.pushAttempt.findMany).mock.calls[0]?.[0] as {
|
||||
where: { channel?: { not?: string } };
|
||||
where: { recipientUserId?: string };
|
||||
};
|
||||
expect(args.where.channel).toEqual({ not: REMINDER_DEDUP_CHANNEL });
|
||||
expect(args.where).toEqual({ recipientUserId: ADMIN_USER_ID });
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,6 @@ import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import type { ChannelType } from "@/lib/notifications/types";
|
||||
import { REMINDER_DEDUP_CHANNEL } from "@/lib/notifications/reminder-dedup";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -176,12 +175,8 @@ export const GET = apiHandler(async () => {
|
||||
// recipient index keeps the bounded diagnostic read independent of the
|
||||
// account's lifetime notification volume.
|
||||
prisma.pushAttempt.findMany({
|
||||
// The reminder tick's per-slot dedup anchors live in this table under
|
||||
// a sentinel channel. They are bookkeeping, not delivery attempts,
|
||||
// and would push the real sends out of the trailing window.
|
||||
where: {
|
||||
recipientUserId: user.id,
|
||||
channel: { not: REMINDER_DEDUP_CHANNEL },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
|
||||
@@ -37,7 +37,6 @@ vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
import { GET } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireAdmin, HttpError } from "@/lib/api-handler";
|
||||
import { REMINDER_DEDUP_CHANNEL } from "@/lib/notifications/reminder-dedup";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
const ADMIN_CTX = {
|
||||
@@ -140,15 +139,12 @@ describe("GET /api/admin/notifications/health — aggregate", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("excludes reminder-dedup bookkeeping rows from the channel picture", async () => {
|
||||
// The medication tick anchors its per-slot dedup in the same table
|
||||
// under a sentinel channel. Those rows are not delivery attempts, so
|
||||
// counting them would misreport what the channels are doing.
|
||||
it("groups every delivery attempt in the selected window", async () => {
|
||||
await GET(req());
|
||||
const args = vi.mocked(prisma.pushAttempt.groupBy).mock.calls[0][0] as {
|
||||
where: { channel?: { not?: string } };
|
||||
where: { createdAt?: { gte?: Date } };
|
||||
};
|
||||
expect(args.where.channel).toEqual({ not: REMINDER_DEDUP_CHANNEL });
|
||||
expect(args.where.createdAt?.gte).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it("defaults the window to 24h and clamps out-of-range values", async () => {
|
||||
|
||||
@@ -2,7 +2,6 @@ import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { REMINDER_DEDUP_CHANNEL } from "@/lib/notifications/reminder-dedup";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -59,12 +58,8 @@ export const GET = apiHandler(async (request) => {
|
||||
const [grouped, disabled] = await Promise.all([
|
||||
prisma.pushAttempt.groupBy({
|
||||
by: ["channel", "result"],
|
||||
// The reminder tick anchors its per-slot dedup in the same table
|
||||
// under a sentinel channel. Those rows record a decision, not a
|
||||
// delivery, so they stay out of the per-channel health picture.
|
||||
where: {
|
||||
createdAt: { gte: since },
|
||||
channel: { not: REMINDER_DEDUP_CHANNEL },
|
||||
},
|
||||
_count: { _all: true },
|
||||
}),
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
* ntfy had no row, so the tick re-sent the same overdue notice on every
|
||||
* pass for the rest of the local day.
|
||||
*
|
||||
* The anchor now lives in `push_attempts`, the ledger the daily briefing
|
||||
* and the illness escalation already use for the same purpose. Two
|
||||
* properties matter and both are deliberate:
|
||||
* The anchor now lives in `notification_events`, a record-scoped event ledger
|
||||
* rather than a channel delivery record. Two properties matter and both are
|
||||
* deliberate:
|
||||
*
|
||||
* - **Written per dispatched slot, not per successful send.** Anchoring
|
||||
* on a delivered push would re-open the flood the moment a channel
|
||||
@@ -19,24 +19,14 @@
|
||||
* for that phase rather than risking a repeat; the next phase still
|
||||
* escalates, and the next local day starts clean.
|
||||
*
|
||||
* The rows are bookkeeping, not delivery attempts, so they carry the
|
||||
* `DEDUP` channel sentinel and the operator-facing notification surfaces
|
||||
* filter them out.
|
||||
*/
|
||||
import type { PrismaClient } from "@/generated/prisma/client";
|
||||
|
||||
/**
|
||||
* Channel sentinel for a bookkeeping row. Never a real delivery target —
|
||||
* `/api/admin/notifications/{health,diagnostic}` exclude it so the
|
||||
* per-channel health picture stays a picture of actual sends.
|
||||
*/
|
||||
export const REMINDER_DEDUP_CHANNEL = "DEDUP";
|
||||
|
||||
/**
|
||||
* How far back the anchor lookup reads. The key already carries the local
|
||||
* date, so anything older than this cannot match; the bound exists to keep
|
||||
* the read on the `(user_id, created_at DESC)` index. Two days covers every
|
||||
* timezone offset plus a DST shift.
|
||||
* the read on the record/event/key index. Two days covers every timezone
|
||||
* offset plus a DST shift.
|
||||
*/
|
||||
const ANCHOR_LOOKBACK_MS = 48 * 60 * 60 * 1000;
|
||||
|
||||
@@ -79,11 +69,11 @@ export async function hasReminderDedupAnchor(
|
||||
input: { userId: string; eventType: string; reason: string; now: Date },
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const row = await prisma.pushAttempt.findFirst({
|
||||
const row = await prisma.notificationEvent.findFirst({
|
||||
where: {
|
||||
userId: input.userId,
|
||||
recordUserId: input.userId,
|
||||
eventType: input.eventType,
|
||||
reason: input.reason,
|
||||
dedupKey: input.reason,
|
||||
createdAt: { gte: new Date(input.now.getTime() - ANCHOR_LOOKBACK_MS) },
|
||||
},
|
||||
select: { id: true },
|
||||
@@ -104,13 +94,11 @@ export async function writeReminderDedupAnchor(
|
||||
input: { userId: string; eventType: string; reason: string },
|
||||
): Promise<void> {
|
||||
try {
|
||||
await prisma.pushAttempt.create({
|
||||
await prisma.notificationEvent.create({
|
||||
data: {
|
||||
userId: input.userId,
|
||||
channel: REMINDER_DEDUP_CHANNEL,
|
||||
recordUserId: input.userId,
|
||||
eventType: input.eventType,
|
||||
result: "skipped",
|
||||
reason: input.reason,
|
||||
dedupKey: input.reason,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
|
||||
Reference in new issue
Block a user