Repository navigation
fix(web): start the webhook cleanup job, deleting old finished calls in small batches (cloud) #521
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
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
08a41d3
fix(web): start the webhook cleanup job, and delete old calls in smal…
KMKoushik 104bdca
fix(web): only delete finished, untouched webhook calls, with per-bat…
KMKoushik 2ca89ad
fix(web): give each cleanup batch a Prisma transaction limit above it…
KMKoushik f829a97
test(web): register the cleanup-job mock per test, so the self-hosted…
KMKoushik 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
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,75 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| const flags = vi.hoisted(() => ({ | ||
| webhookCleanupImported: false, | ||
| isCloud: true, | ||
| })); | ||
|
|
||
| const mocks = vi.hoisted(() => ({ | ||
| init: vi.fn().mockResolvedValue(undefined), | ||
| initDomain: vi.fn().mockResolvedValue(undefined), | ||
| start: vi.fn().mockResolvedValue(undefined), | ||
| })); | ||
|
|
||
| vi.mock("~/utils/common", () => ({ | ||
| isCloud: () => flags.isCloud, | ||
| isEmailCleanupEnabled: () => false, | ||
| })); | ||
|
|
||
| vi.mock("~/server/service/email-queue-service", () => ({ | ||
| EmailQueueService: { init: mocks.init }, | ||
| })); | ||
|
|
||
| vi.mock("~/server/jobs/usage-job", () => ({})); | ||
|
|
||
| vi.mock("~/server/jobs/domain-verification-job", () => ({ | ||
| initDomainVerificationJob: mocks.initDomain, | ||
| })); | ||
|
|
||
| vi.mock("~/server/jobs/cleanup-email-bodies", () => ({})); | ||
|
|
||
| vi.mock("~/server/jobs/campaign-scheduler-job", () => ({ | ||
| CampaignSchedulerService: { start: mocks.start }, | ||
| })); | ||
|
|
||
| describe("instrumentation register", () => { | ||
| beforeEach(() => { | ||
| vi.resetModules(); | ||
| // Registered fresh for every test: a factory registered once with vi.mock | ||
| // is cached, so later imports wouldn't record that the job was loaded. | ||
| vi.doMock("~/server/jobs/webhook-cleanup-job", () => { | ||
| flags.webhookCleanupImported = true; | ||
| return {}; | ||
| }); | ||
| flags.webhookCleanupImported = false; | ||
| flags.isCloud = true; | ||
| vi.stubEnv("NEXT_RUNTIME", "nodejs"); | ||
| vi.stubEnv("REDIS_URL", "redis://127.0.0.1:6380/15"); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllEnvs(); | ||
| }); | ||
|
|
||
| it("starts the webhook cleanup job when Redis is configured", async () => { | ||
| const { register } = await import("~/instrumentation"); | ||
| await register(); | ||
| expect(mocks.init).toHaveBeenCalledTimes(1); | ||
| expect(mocks.initDomain).toHaveBeenCalledTimes(1); | ||
| expect(flags.webhookCleanupImported).toBe(true); | ||
| }); | ||
|
|
||
| it("does not start the webhook cleanup job on self-hosted installs", async () => { | ||
| flags.isCloud = false; | ||
| const { register } = await import("~/instrumentation"); | ||
| await register(); | ||
| expect(flags.webhookCleanupImported).toBe(false); | ||
| }); | ||
|
|
||
| it("does not start the webhook cleanup job without a Redis URL", async () => { | ||
| vi.stubEnv("REDIS_URL", ""); | ||
| const { register } = await import("~/instrumentation"); | ||
| await register(); | ||
| expect(flags.webhookCleanupImported).toBe(false); | ||
| }); | ||
| }); | ||
121 changes: 121 additions & 0 deletions
121
apps/web/src/server/jobs/webhook-cleanup-job.integration.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,121 @@ | ||
| import { WebhookCallStatus } from "@prisma/client"; | ||
| import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; | ||
| import { db } from "~/server/db"; | ||
| import { createTeam } from "~/test/factories/core"; | ||
| import { | ||
| closeIntegrationConnections, | ||
| integrationEnabled, | ||
| resetDatabase, | ||
| } from "~/test/integration/helpers"; | ||
|
|
||
| // Only the database is real here: the job module's queue and worker are not | ||
| // needed to test the deletion itself. | ||
| vi.mock("bullmq", () => ({ | ||
| Queue: class { | ||
| upsertJobScheduler = vi.fn().mockResolvedValue(undefined); | ||
| }, | ||
| Worker: class { | ||
| on = vi.fn(); | ||
| }, | ||
| })); | ||
|
|
||
| import { deleteOldWebhookCalls } from "~/server/jobs/webhook-cleanup-job"; | ||
|
|
||
| const describeIntegration = integrationEnabled ? describe : describe.skip; | ||
|
|
||
| const DAY_MS = 24 * 60 * 60 * 1000; | ||
|
|
||
| describeIntegration("webhook cleanup against postgres", () => { | ||
| let webhookId: string; | ||
| let teamId: number; | ||
|
|
||
| async function createCall( | ||
| name: string, | ||
| status: WebhookCallStatus, | ||
| createdDaysAgo: number, | ||
| updatedDaysAgo: number, | ||
| ) { | ||
| const call = await db.webhookCall.create({ | ||
| data: { | ||
| webhookId, | ||
| teamId, | ||
| type: "email.sent", | ||
| payload: JSON.stringify({ name }), | ||
| status, | ||
| }, | ||
| }); | ||
| const createdAt = new Date(Date.now() - createdDaysAgo * DAY_MS); | ||
| const updatedAt = new Date(Date.now() - updatedDaysAgo * DAY_MS); | ||
| await db.$executeRaw`UPDATE "WebhookCall" SET "createdAt" = ${createdAt}, "updatedAt" = ${updatedAt} WHERE id = ${call.id}`; | ||
| return call.id; | ||
| } | ||
|
|
||
| beforeEach(async () => { | ||
| await resetDatabase(); | ||
| const team = await createTeam(); | ||
| teamId = team.id; | ||
| const webhook = await db.webhook.create({ | ||
| data: { | ||
| teamId, | ||
| url: "https://example.com/hook", | ||
| secret: "whsec_test", | ||
| eventTypes: [], | ||
| }, | ||
| }); | ||
| webhookId = webhook.id; | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| await closeIntegrationConnections(); | ||
| }); | ||
|
|
||
| it("deletes only finished calls that are over 30 days old and untouched since", async () => { | ||
| const deletedIds = [ | ||
| await createCall("old delivered 1", WebhookCallStatus.DELIVERED, 60, 60), | ||
| await createCall("old delivered 2", WebhookCallStatus.DELIVERED, 45, 45), | ||
| await createCall("old failed", WebhookCallStatus.FAILED, 50, 49), | ||
| await createCall("old discarded", WebhookCallStatus.DISCARDED, 40, 40), | ||
| ]; | ||
| const keptIds = [ | ||
| await createCall("old but pending", WebhookCallStatus.PENDING, 60, 60), | ||
| await createCall( | ||
| "old in progress", | ||
| WebhookCallStatus.IN_PROGRESS, | ||
| 60, | ||
| 60, | ||
| ), | ||
| await createCall( | ||
| "old, retried today", | ||
| WebhookCallStatus.DELIVERED, | ||
| 60, | ||
| 0, | ||
| ), | ||
| await createCall("recent", WebhookCallStatus.DELIVERED, 2, 2), | ||
| ]; | ||
|
|
||
| const result = await deleteOldWebhookCalls({ | ||
| cutoff: new Date(Date.now() - 30 * DAY_MS), | ||
| batchSize: 3, | ||
| pauseMs: 0, | ||
| }); | ||
|
|
||
| expect(result).toMatchObject({ deleted: 4, batches: 2, finished: true }); | ||
| const remaining = await db.webhookCall.findMany({ select: { id: true } }); | ||
| expect(remaining.map((row) => row.id).sort()).toEqual([...keptIds].sort()); | ||
| expect(deletedIds.every((id) => !remaining.some((r) => r.id === id))).toBe( | ||
| true, | ||
| ); | ||
| }); | ||
|
|
||
| it("does nothing when nothing is old enough", async () => { | ||
| await createCall("recent", WebhookCallStatus.DELIVERED, 1, 1); | ||
|
|
||
| const result = await deleteOldWebhookCalls({ | ||
| cutoff: new Date(Date.now() - 30 * DAY_MS), | ||
| pauseMs: 0, | ||
| }); | ||
|
|
||
| expect(result).toMatchObject({ deleted: 0, batches: 0, finished: true }); | ||
| expect(await db.webhookCall.count()).toBe(1); | ||
| }); | ||
| }); |
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.