-
-
Notifications
You must be signed in to change notification settings - Fork 401
fix: deduplicate dashboard engagement usage #425
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+203
−8
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
186 changes: 186 additions & 0 deletions
186
apps/web/src/server/service/ses-hook-parser.unit.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }, | ||
| ); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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:
Repository: usesend/useSend
Length of output: 634
🏁 Script executed:
Repository: usesend/useSend
Length of output: 3142
Dedup still races under concurrent deliveries
findFirstcan returnnullin two parallel invocations before either reachesdb.emailEvent.create(), andEmailEventhas 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