Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions apps/web/src/server/service/ses-hook-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,19 @@ export async function parseSesHook(data: SesEvent) {
return true;
}

const isEngagementEvent = [EmailStatus.OPENED, EmailStatus.CLICKED].includes(
mailStatus,
);
const existingMailEvent =
email.campaignId || isEngagementEvent
? await db.emailEvent.findFirst({
where: {
emailId: email.id,
status: mailStatus,
},
})
: null;

Comment on lines +104 to +116

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether EmailEvent has a uniqueness guarantee on (emailId, status)
# that would make this check-then-act pattern safe under concurrency.
fd -e prisma | xargs -I{} grep -n -A 15 "model EmailEvent" {}

Repository: usesend/useSend

Length of output: 634


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant parser flow around the lookup, duplicate checks, and create path.
file="apps/web/src/server/service/ses-hook-parser.ts"

sed -n '90,130p' "$file"
printf '\n---\n'
sed -n '198,220p' "$file"
printf '\n---\n'
sed -n '286,320p' "$file"

printf '\n=== Prisma model ===\n'
fd -e prisma | xargs -I{} sh -c 'grep -n -A 20 "model EmailEvent" "{}"'

Repository: usesend/useSend

Length of output: 3142


Dedup still races under concurrent deliveries
findFirst can return null in two parallel invocations before either reaches db.emailEvent.create(), and EmailEvent has no uniqueness constraint on (emailId, status) to block the duplicate insert. Move this guard to the DB layer with a unique constraint + upsert/ON CONFLICT DO NOTHING, or wrap the lookup and create in a transaction/lock.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/src/server/service/ses-hook-parser.ts` around lines 104 - 116, Make
deduplication in the email-event creation flow atomic rather than relying on the
`existingMailEvent` lookup. Add a database uniqueness constraint for the
`(emailId, status)` pair and use an upsert or conflict-ignoring insert when
creating `EmailEvent`; alternatively, transactionally lock the record around the
lookup and create. Preserve the existing campaign and engagement-event
eligibility behavior.

// Update the latest status and to avoid race conditions
await db.$executeRaw`
UPDATE "Email"
Expand Down Expand Up @@ -190,7 +203,10 @@ export async function parseSesHook(data: SesEvent) {
}
}

const isDuplicateEngagement = Boolean(existingMailEvent) && isEngagementEvent;

if (
!isDuplicateEngagement &&
[
"DELIVERED",
"OPENED",
Expand Down Expand Up @@ -274,14 +290,7 @@ export async function parseSesHook(data: SesEvent) {
mailData: data,
});

const mailEvent = await db.emailEvent.findFirst({
where: {
emailId: email.id,
status: mailStatus,
},
});

if (!mailEvent) {
if (!existingMailEvent) {
await updateCampaignAnalytics(
email.campaignId,
mailStatus,
Expand Down
186 changes: 186 additions & 0 deletions apps/web/src/server/service/ses-hook-parser.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import { EmailStatus } from "@prisma/client";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { SesEvent } from "~/types/aws-types";

const { mockDb, mockUpdateCampaignAnalytics, mockWebhookEmit } = vi.hoisted(
() => ({
mockDb: {
$executeRaw: vi.fn(),
email: {
findUnique: vi.fn(),
update: vi.fn(),
},
emailEvent: {
findFirst: vi.fn(),
create: vi.fn(),
},
dailyEmailUsage: {
upsert: vi.fn(),
},
cumulatedMetrics: {
upsert: vi.fn(),
},
},
mockUpdateCampaignAnalytics: vi.fn(),
mockWebhookEmit: vi.fn(),
}),
);

vi.mock("~/server/db", () => ({
db: mockDb,
}));

vi.mock("~/env", () => ({
env: {
NEXTAUTH_URL: "https://usesend.example",
},
}));

vi.mock("~/server/service/campaign-service", () => ({
unsubscribeContact: vi.fn(),
updateCampaignAnalytics: mockUpdateCampaignAnalytics,
}));

vi.mock("~/server/service/webhook-service", () => ({
WebhookService: {
emit: mockWebhookEmit,
},
}));

vi.mock("~/server/service/suppression-service", () => ({
SuppressionService: {
addSuppression: vi.fn(),
},
}));

vi.mock("bullmq", () => ({
Queue: class {
add = vi.fn();
},
Worker: class {},
}));

vi.mock("~/server/redis", () => ({
BULL_PREFIX: "test",
getRedis: vi.fn(() => ({})),
}));

vi.mock("~/server/logger/log", () => ({
getChildLogger: vi.fn(),
logger: {
error: vi.fn(),
info: vi.fn(),
setBindings: vi.fn(),
warn: vi.fn(),
},
withLogger: vi.fn(),
}));

import { parseSesHook } from "~/server/service/ses-hook-parser";

const email = {
id: "email_1",
sesEmailId: "ses_1",
from: "sender@example.com",
to: ["recipient@example.com"],
replyTo: [],
cc: [],
bcc: [],
subject: "Hello",
text: null,
html: null,
latestStatus: EmailStatus.DELIVERED,
teamId: 7,
domainId: 11,
apiId: null,
createdAt: new Date("2026-07-13T00:00:00.000Z"),
updatedAt: new Date("2026-07-13T00:00:00.000Z"),
scheduledAt: null,
attachments: null,
campaignId: null,
contactId: null,
inReplyToId: null,
headers: null,
};

function buildEvent(eventType: "Open" | "Click"): SesEvent {
const event = {
eventType,
mail: {
timestamp: "2026-07-13T01:00:00.000Z",
source: "sender@example.com",
messageId: "ses_1",
destination: ["recipient@example.com"],
headersTruncated: false,
headers: [],
commonHeaders: {
from: ["sender@example.com"],
to: ["recipient@example.com"],
messageId: "message_1",
},
tags: {},
},
} as SesEvent;

if (eventType === "Open") {
event.open = {
ipAddress: "192.0.2.1",
timestamp: "2026-07-13T01:00:00.000Z",
userAgent: "test-agent",
};
} else {
event.click = {
ipAddress: "192.0.2.1",
timestamp: "2026-07-13T01:00:00.000Z",
userAgent: "test-agent",
link: "https://example.com",
linkTags: {},
};
}

return event;
}

describe("parseSesHook dashboard engagement usage", () => {
beforeEach(() => {
vi.clearAllMocks();
mockDb.email.findUnique.mockResolvedValue(email);
mockDb.emailEvent.create.mockResolvedValue({});
mockDb.dailyEmailUsage.upsert.mockResolvedValue({});
mockWebhookEmit.mockResolvedValue(undefined);
});

it.each([
["Open", EmailStatus.OPENED],
["Click", EmailStatus.CLICKED],
] as const)(
"counts only the first %s event for an email",
async (eventType, status) => {
mockDb.emailEvent.findFirst
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "existing_event", status });

const event = buildEvent(eventType);
await parseSesHook(event);
await parseSesHook(event);

expect(mockDb.emailEvent.findFirst).toHaveBeenNthCalledWith(1, {
where: {
emailId: email.id,
status,
},
});
expect(mockDb.dailyEmailUsage.upsert).toHaveBeenCalledTimes(1);
expect(mockDb.dailyEmailUsage.upsert).toHaveBeenCalledWith(
expect.objectContaining({
update: {
[status.toLowerCase()]: {
increment: 1,
},
},
}),
);
expect(mockDb.emailEvent.create).toHaveBeenCalledTimes(2);
},
);
});
Loading