-
-
Notifications
You must be signed in to change notification settings - Fork 7
feat(worker): add cleanup task for unreferenced S3 attachments #195
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
Open
bbornino
wants to merge
3
commits into
playfulprogramming:main
Choose a base branch
from
bbornino:feature/191-cleanup-unreferenced-attachments
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
121 changes: 121 additions & 0 deletions
121
apps/worker/src/tasks/cleanup-attachments/processor.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 processor from "./processor.ts"; | ||
| import { db, postAttachments } from "@playfulprogramming/db"; | ||
| import { s3 } from "@playfulprogramming/s3"; | ||
|
|
||
| const NOW = new Date("2025-05-05T12:00:00Z"); | ||
| const ONE_HOUR_MS = 60 * 60 * 1000; | ||
| const OUTSIDE_GRACE_PERIOD = new Date(NOW.getTime() - ONE_HOUR_MS - 1000); | ||
| const INSIDE_GRACE_PERIOD = new Date(NOW.getTime() - 30 * 60 * 1000); | ||
|
|
||
| test("Removes an attachment from S3 when no post_attachments row references it", async () => { | ||
| vi.setSystemTime(NOW); | ||
|
|
||
| vi.mocked(s3.list).mockResolvedValue([ | ||
| { | ||
| key: "posts/example-post/en/content.md", | ||
| lastModified: OUTSIDE_GRACE_PERIOD, | ||
| }, | ||
| { | ||
| key: "posts/example-post/attachments/referenced-sha.pdf", | ||
| lastModified: OUTSIDE_GRACE_PERIOD, | ||
| }, | ||
| { | ||
| key: "posts/example-post/attachments/orphaned-sha.jpeg", | ||
| lastModified: OUTSIDE_GRACE_PERIOD, | ||
| }, | ||
| ]); | ||
|
|
||
| vi.mocked(db.select).mockReturnValue({ | ||
| from: vi.fn().mockResolvedValue([ | ||
| { | ||
| attachmentKey: "posts/example-post/attachments/referenced-sha.pdf", | ||
| }, | ||
| ]), | ||
| } as never); | ||
|
|
||
| await processor({} as never); | ||
|
|
||
| expect(s3.remove).toBeCalledWith( | ||
| "example-bucket", | ||
| "posts/example-post/attachments/orphaned-sha.jpeg", | ||
| ); | ||
| expect(s3.remove).toBeCalledTimes(1); | ||
| }); | ||
|
|
||
| test("Leaves an attachment alone when a post_attachments row still references it", async () => { | ||
| vi.setSystemTime(NOW); | ||
|
|
||
| vi.mocked(s3.list).mockResolvedValue([ | ||
| { | ||
| key: "posts/example-post/attachments/referenced-sha.pdf", | ||
| lastModified: OUTSIDE_GRACE_PERIOD, | ||
| }, | ||
| ]); | ||
|
|
||
| vi.mocked(db.select).mockReturnValue({ | ||
| from: vi.fn().mockResolvedValue([ | ||
| { | ||
| attachmentKey: "posts/example-post/attachments/referenced-sha.pdf", | ||
| }, | ||
| ]), | ||
| } as never); | ||
|
|
||
| await processor({} as never); | ||
|
|
||
| expect(s3.remove).not.toBeCalled(); | ||
| }); | ||
|
|
||
| test("Does nothing when there are no attachment objects in S3", async () => { | ||
| vi.setSystemTime(NOW); | ||
|
|
||
| vi.mocked(s3.list).mockResolvedValue([ | ||
| { | ||
| key: "posts/example-post/en/content.md", | ||
| lastModified: OUTSIDE_GRACE_PERIOD, | ||
| }, | ||
| ]); | ||
|
|
||
| await processor({} as never); | ||
|
|
||
| expect(db.select).not.toBeCalled(); | ||
| expect(s3.remove).not.toBeCalled(); | ||
| }); | ||
|
|
||
| test("Queries the full attachment table with no per-post filter", async () => { | ||
| vi.setSystemTime(NOW); | ||
|
|
||
| vi.mocked(s3.list).mockResolvedValue([ | ||
| { | ||
| key: "posts/example-post/attachments/orphaned-sha.jpeg", | ||
| lastModified: OUTSIDE_GRACE_PERIOD, | ||
| }, | ||
| ]); | ||
|
|
||
| const from = vi.fn().mockResolvedValue([]); | ||
| vi.mocked(db.select).mockReturnValue({ from } as never); | ||
|
|
||
| await processor({} as never); | ||
|
|
||
| expect(from).toBeCalledWith(postAttachments); | ||
| expect(s3.remove).toBeCalledWith( | ||
| "example-bucket", | ||
| "posts/example-post/attachments/orphaned-sha.jpeg", | ||
| ); | ||
| }); | ||
|
|
||
| test("Leaves an unreferenced attachment alone when it's within the grace period", async () => { | ||
| vi.setSystemTime(NOW); | ||
|
|
||
| vi.mocked(s3.list).mockResolvedValue([ | ||
| { | ||
| key: "posts/example-post/attachments/fresh-sha.jpeg", | ||
| lastModified: INSIDE_GRACE_PERIOD, | ||
| }, | ||
| ]); | ||
|
|
||
| await processor({} as never); | ||
|
|
||
| // The grace period filters it out before the post_attachments query even runs | ||
| expect(db.select).not.toBeCalled(); | ||
| expect(s3.remove).not.toBeCalled(); | ||
| }); |
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,39 @@ | ||
| import { env } from "@playfulprogramming/common"; | ||
| import { Tasks } from "@playfulprogramming/bullmq"; | ||
| import { db, postAttachments } from "@playfulprogramming/db"; | ||
| import { s3 } from "@playfulprogramming/s3"; | ||
| import { createProcessor } from "../../createProcessor.ts"; | ||
|
|
||
| const ATTACHMENTS_PREFIX = "posts/"; | ||
| const GRACE_PERIOD_MS = 60 * 60 * 1000; | ||
|
|
||
| export default createProcessor(Tasks.CLEANUP_ATTACHMENTS, async () => { | ||
| const bucket = await s3.ensureBucket(env.S3_BUCKET); | ||
|
|
||
| const objects = await s3.list(bucket, ATTACHMENTS_PREFIX); | ||
| const now = Date.now(); | ||
|
|
||
| // sync-post uploads an attachment to S3 before its post_attachments row is | ||
| // committed, so a very recent object may just be mid-flight rather than | ||
| // truly orphaned - skip anything younger than the grace period. | ||
| const candidateKeys = objects | ||
| .filter((object) => object.key.includes("/attachments/")) | ||
| .filter((object) => now - object.lastModified.getTime() > GRACE_PERIOD_MS) | ||
| .map((object) => object.key); | ||
|
|
||
| if (candidateKeys.length === 0) return; | ||
|
|
||
| const referencedRows = await db | ||
| .select({ attachmentKey: postAttachments.attachmentKey }) | ||
| .from(postAttachments); | ||
| const referencedKeys = new Set( | ||
| referencedRows.map((row) => row.attachmentKey), | ||
| ); | ||
|
|
||
| for (const key of candidateKeys) { | ||
| if (referencedKeys.has(key)) continue; | ||
|
|
||
| await s3.remove(bucket, key); | ||
| console.log(`Removed unreferenced attachment ${key} from S3`); | ||
| } | ||
| }); |
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
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.
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.