⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(reminders): persist notification and claim atomically
Tinc4928f8e2d7a
diff --git a/apps/api/src/notification/controllers/create-notification.ts b/apps/api/src/notification/controllers/create-notification.tsindex 2ba7681a1..384b50cfe 100644--- a/apps/api/src/notification/controllers/create-notification.ts+++ b/apps/api/src/notification/controllers/create-notification.ts@@ -7,25 +7,33 @@ import { deliverNotification } from "../../notification-preferences/delivery";import { safeOutboundError } from "../../utils/outbound-request";import { canReceiveResourceNotification } from "../resource-access";-async function createNotification({- userId,- title,- content,- type,- eventData,- resourceId,- resourceType,-}: {- userId: string;- title?: string | null;- content?: string | null;- type?: string;- eventData?: Record<string, unknown> | null;- resourceId?: string;- resourceType?: string;-}) {+export async function persistNotification(+ {+ userId,+ title,+ content,+ type,+ eventData,+ resourceId,+ resourceType,+ }: {+ userId: string;+ title?: string | null;+ content?: string | null;+ type?: string;+ eventData?: Record<string, unknown> | null;+ resourceId?: string;+ resourceType?: string;+ },+ database: Pick<typeof db, "query" | "insert" | "select"> = db,+) {if (- !(await canReceiveResourceNotification(userId, resourceId, resourceType))+ !(await canReceiveResourceNotification(+ userId,+ resourceId,+ resourceType,+ database,+ ))) {return null;}@@ -42,18 +50,17 @@ async function createNotification({: null;if (preferenceKey) {- const preference = await db.query.userNotificationPreferenceTable.findFirst(- {+ const preference =+ await database.query.userNotificationPreferenceTable.findFirst({where: (table, { eq }) => eq(table.userId, userId),- },- );+ });if (preference?.[preferenceKey] === false) {return null;}}- const [notification] = await db+ const [notification] = await database.insert(notificationTable).values({id: createId(),@@ -67,19 +74,29 @@ async function createNotification({}).returning();- if (notification) {- await publishEvent("notification.created", {+ return notification;+}++export async function dispatchNotification(+ notification: typeof notificationTable.$inferSelect,+) {+ await publishEvent("notification.created", {+ notificationId: notification.id,+ userId: notification.userId,+ });+ void deliverNotification(notification.id).catch((error) => {+ console.error("Failed to deliver notification", {notificationId: notification.id,- userId,- });- void deliverNotification(notification.id).catch((error) => {- console.error("Failed to deliver notification", {- notificationId: notification.id,- error: safeOutboundError(error),- });+ error: safeOutboundError(error),});- }+ });+}+async function createNotification(+ data: Parameters<typeof persistNotification>[0],+) {+ const notification = await persistNotification(data);+ if (notification) await dispatchNotification(notification);return notification;}diff --git a/apps/api/src/notification/resource-access.ts b/apps/api/src/notification/resource-access.tsindex 482efaf02..a3b05f2fa 100644--- a/apps/api/src/notification/resource-access.ts+++ b/apps/api/src/notification/resource-access.ts@@ -29,8 +29,9 @@ export async function canReceiveResourceNotification(userId: string,resourceId?: string | null,resourceType?: string | null,+ database: Pick<typeof db, "select"> = db,) {- const [user] = await db+ const [user] = await database.select({ id: userTable.id }).from(userTable).where(diff --git a/apps/api/src/scheduler/due-date-reminders.ts b/apps/api/src/scheduler/due-date-reminders.tsindex 48c6e0878..69e704ca0 100644--- a/apps/api/src/scheduler/due-date-reminders.ts+++ b/apps/api/src/scheduler/due-date-reminders.ts@@ -8,7 +8,10 @@ import {userNotificationPreferenceTable,workspaceUserTable,} from "../database/schema";-import createNotification from "../notification/controllers/create-notification";+import {+ persistNotification,+ dispatchNotification,+} from "../notification/controllers/create-notification";import {DUE_DATE_DURATION_MS,REMINDER_WINDOW_MINUTES,@@ -111,9 +114,8 @@ async function processReminder() {if (!task.userId) return;- // Insert sent record first; if it already exists, skip notification- try {- const [inserted] = await db+ const notification = await db.transaction(async (tx) => {+ const [claimed] = await tx.insert(taskReminderSentTable).values({taskId: task.id,@@ -126,29 +128,30 @@ async function processReminder(],}).returning();+ if (!claimed) return null;- if (!inserted) return;- } catch (error) {- console.error("Failed to record due date reminder", {- taskId: task.id,- reminderType,- error,- });- return;- }-- await createNotification({- userId: task.userId,- type: notificationType,- eventData: {- taskTitle: task.title,- reminderType,- leadTimeMinutes: task.leadTimeMinutes ?? 1440,- dueDate: task.dueDate?.toISOString() ?? null,- },- resourceId: task.id,- resourceType: "task",+ const created = await persistNotification(+ {+ userId: task.userId!,+ type: notificationType,+ eventData: {+ taskTitle: task.title,+ reminderType,+ leadTimeMinutes: task.leadTimeMinutes ?? 1440,+ dueDate: task.dueDate?.toISOString() ?? null,+ },+ resourceId: task.id,+ resourceType: "task",+ },+ tx,+ );+ if (!created)+ await tx+ .delete(taskReminderSentTable)+ .where(eq(taskReminderSentTable.id, claimed.id));+ return created;});+ if (notification) await dispatchNotification(notification);}export async function checkDueDateReminders(): Promise<{ degraded: boolean }> {diff --git a/tests/api-integration/date-only-reminders.test.ts b/tests/api-integration/date-only-reminders.test.tsindex b885c2239..438782abc 100644--- a/tests/api-integration/date-only-reminders.test.ts+++ b/tests/api-integration/date-only-reminders.test.ts@@ -8,7 +8,7 @@ import {} from "vite-plus/test";import db, { schema } from "../../apps/api/src/database";import { taskReminderSentTable } from "../../apps/api/src/database/schema";-import createNotification from "../../apps/api/src/notification/controllers/create-notification";+import { persistNotification as createNotification } from "../../apps/api/src/notification/controllers/create-notification";import { sendDueDateReminder } from "../../apps/api/src/plugins/generic-webhook/events";import { checkDueDateReminders } from "../../apps/api/src/scheduler/due-date-reminders";import { checkProjectWebhookReminders } from "../../apps/api/src/scheduler/project-webhook-reminders";@@ -21,7 +21,10 @@ import {vi.mock("../../apps/api/src/notification/controllers/create-notification",() => ({- default: vi.fn().mockResolvedValue(undefined),+ persistNotification: vi+ .fn()+ .mockResolvedValue({ id: "synthetic-notification" }),+ dispatchNotification: vi.fn().mockResolvedValue(undefined),}),);vi.mock("../../apps/api/src/plugins/generic-webhook/events", () => ({@@ -135,6 +138,7 @@ describe("API integration: date-only reminders", () => {leadTimeMinutes: 840,}),}),+ expect.any(Object),);expect(sendDueDateReminder).toHaveBeenCalledExactlyOnceWith(expect.any(Object),@@ -165,6 +169,7 @@ describe("API integration: date-only reminders", () => {type: "task_overdue",resourceId: task.id,}),+ expect.any(Object),);});@@ -177,6 +182,7 @@ describe("API integration: date-only reminders", () => {await checkAllReminders();expect(createNotification).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ type: "due_date_reminder" }),+ expect.any(Object),);expect(sendDueDateReminder).toHaveBeenCalledTimes(1);});diff --git a/tests/api-integration/reminder-atomicity.test.ts b/tests/api-integration/reminder-atomicity.test.tsnew file mode 100644index 000000000..9a9ff5bd5--- /dev/null+++ b/tests/api-integration/reminder-atomicity.test.ts@@ -0,0 +1,54 @@+import { beforeEach, expect, it, vi } from "vite-plus/test";+const m = vi.hoisted(() => ({ fail: true }));+vi.mock(+ "../../apps/api/src/notification/controllers/create-notification",+ async (original) => {+ const actual =+ await original<+ typeof import("../../apps/api/src/notification/controllers/create-notification")+ >();+ return {+ ...actual,+ persistNotification: (+ ...args: Parameters<typeof actual.persistNotification>+ ) => {+ if (m.fail) throw new Error("temporary notification failure");+ return actual.persistNotification(...args);+ },+ };+ },+);+import db, { schema } from "../../apps/api/src/database";+import { checkDueDateReminders } from "../../apps/api/src/scheduler/due-date-reminders";+import { DUE_DATE_DURATION_MS } from "../../apps/api/src/scheduler/reminder-timing";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++beforeEach(resetTestDatabase);+it("rolls back the reminder claim when notification creation fails, then retries once", async () => {+ const { workspace, user } = await createWorkspaceMember();+ const { project, columns } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ await db.insert(schema.taskTable).values({+ projectId: project.id,+ userId: user.id,+ title: "test reminder",+ status: "to-do",+ columnId: columns.todo.id,+ number: 1,+ dueDate: new Date(Date.now() + (1440 - 5) * 60000 - DUE_DATE_DURATION_MS),+ });+ m.fail = true;+ expect(await checkDueDateReminders()).toEqual({ degraded: true });+ expect(await db.select().from(schema.taskReminderSentTable)).toHaveLength(0);+ expect(await db.select().from(schema.notificationTable)).toHaveLength(0);+ m.fail = false;+ expect(await checkDueDateReminders()).toEqual({ degraded: false });+ await checkDueDateReminders();+ expect(await db.select().from(schema.taskReminderSentTable)).toHaveLength(1);+ expect(await db.select().from(schema.notificationTable)).toHaveLength(1);+});