Repository navigation
fix(files): lock the workspace row before inserting a workspace file #8972
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
3 commits
Select commit
Hold shift + click to select a range
760b920
fix(files): lock the workspace row before inserting a workspace file
waleedlatif1 189f5c8
improvement(files): take the workspace row lock inside the shared fil…
waleedlatif1 ad85d9a
fix(files): skip the lock-order test without the search trigger and s…
waleedlatif1 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
167 changes: 167 additions & 0 deletions
167
apps/sim/lib/uploads/contexts/workspace/__integration__/storage-lock-order.integration.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,167 @@ | ||
| /** | ||
| * Real PostgreSQL lock ordering between new-file finalization and a concurrent content write in | ||
| * the same workspace. Both reach the workspace row and the per-workspace search dispatch queue row | ||
| * (through the `workspace_files` search-index trigger), so they must take them in the same order. | ||
| */ | ||
| import { mkdtempSync } from 'node:fs' | ||
| import { rm } from 'node:fs/promises' | ||
| import { tmpdir } from 'node:os' | ||
| import path from 'node:path' | ||
| import { db, dbFor } from '@sim/db' | ||
| import { | ||
| organization, | ||
| user, | ||
| workspace, | ||
| workspaceFileSearchDispatchQueue, | ||
| workspaceFiles, | ||
| } from '@sim/db/schema' | ||
| import { deleteWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' | ||
| import { createDeferred } from '@sim/testing/helpers/deferred' | ||
| import { generateId } from '@sim/utils/id' | ||
| import { eq, inArray, sql } from 'drizzle-orm' | ||
| import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const fixtureStorage = vi.hoisted(() => ({ root: '' })) | ||
| vi.mock('@/lib/uploads/core/setup.server', () => ({ | ||
| get UPLOAD_DIR_SERVER() { | ||
| return fixtureStorage.root | ||
| }, | ||
| })) | ||
|
|
||
| import { lockWorkspaceStorageForMutationInTx } from '@/lib/billing/storage' | ||
| import { | ||
| createKnowledgeAclFixtureIds, | ||
| seedKnowledgeAclFixture, | ||
| } from '@/lib/knowledge/__integration__/seed-source-access-fixture' | ||
| import { | ||
| generateWorkspaceFileKey, | ||
| registerUploadedWorkspaceFile, | ||
| uploadWorkspaceFile, | ||
| } from '@/lib/uploads/contexts/workspace/workspace-file-manager' | ||
| import { uploadFile } from '@/lib/uploads/core/storage-service' | ||
|
|
||
| type FinalizeNewFile = (workspaceId: string, userId: string) => Promise<unknown> | ||
|
|
||
| const finalizeByUpload: FinalizeNewFile = (workspaceId, userId) => { | ||
| const name = `upload-${generateId()}.txt` | ||
| return uploadWorkspaceFile(workspaceId, userId, Buffer.from(name), name, 'text/plain', { | ||
| notifyWorkspaceChange: false, | ||
| }) | ||
| } | ||
|
|
||
| const finalizeByRegistration: FinalizeNewFile = async (workspaceId, userId) => { | ||
| const name = `registered-${generateId()}.txt` | ||
| const key = generateWorkspaceFileKey(workspaceId, name) | ||
| await uploadFile({ | ||
| file: Buffer.from(name), | ||
| fileName: key, | ||
| contentType: 'text/plain', | ||
| context: 'workspace', | ||
| preserveKey: true, | ||
| customKey: key, | ||
| persistMetadata: false, | ||
| }) | ||
| return registerUploadedWorkspaceFile({ | ||
| workspaceId, | ||
| userId, | ||
| key, | ||
| originalName: name, | ||
| contentType: 'text/plain', | ||
| }) | ||
| } | ||
|
|
||
| /** `db:push` never installs the migration-only search-index trigger that reaches the queue row. */ | ||
| const [{ migrated }] = await db.execute<{ migrated: boolean }>(sql`SELECT EXISTS ( | ||
| SELECT 1 FROM pg_trigger | ||
| WHERE tgrelid = 'workspace_files'::regclass AND tgname = 'workspace_files_search_index_pending' | ||
| ) AS migrated`) | ||
| /** The suite's own `afterAll` never runs when it is skipped, so release the probe connection here. */ | ||
| if (!migrated) await db.$client.end() | ||
|
|
||
| describe.skipIf(!migrated)('workspace file storage lock order in PostgreSQL', () => { | ||
| const fixtures: ReturnType<typeof createKnowledgeAclFixtureIds>[] = [] | ||
|
|
||
| beforeAll(() => { | ||
| fixtureStorage.root = mkdtempSync(path.join(tmpdir(), 'sim-file-lock-order-')) | ||
| }) | ||
|
|
||
| afterAll(async () => { | ||
| for (const ids of fixtures) { | ||
| await deleteWorkspaceFixture(db, eq(workspace.id, ids.workspaceId)) | ||
| await db.delete(organization).where(eq(organization.id, ids.organizationId)) | ||
| await db.delete(user).where(inArray(user.id, [ids.aliceId, ids.bobId])) | ||
| } | ||
| await rm(fixtureStorage.root, { recursive: true, force: true }) | ||
| await Promise.all([db.$client.end(), dbFor('cleanup').$client.end()]) | ||
| }) | ||
|
|
||
| /** Seeds a workspace with one file, which also creates the workspace's dispatch queue row. */ | ||
| async function seedWorkspaceWithFile() { | ||
| const ids = createKnowledgeAclFixtureIds() | ||
| fixtures.push(ids) | ||
| await seedKnowledgeAclFixture(ids) | ||
| const name = `existing-${generateId()}.txt` | ||
| const existing = await uploadWorkspaceFile( | ||
| ids.workspaceId, | ||
| ids.aliceId, | ||
| Buffer.from(name), | ||
| name, | ||
| 'text/plain', | ||
| { notifyWorkspaceChange: false } | ||
| ) | ||
| const queued = await db | ||
| .select({ workspaceId: workspaceFileSearchDispatchQueue.workspaceId }) | ||
| .from(workspaceFileSearchDispatchQueue) | ||
| .where(eq(workspaceFileSearchDispatchQueue.workspaceId, ids.workspaceId)) | ||
| expect(queued).toHaveLength(1) | ||
| return { ...ids, existingFileId: existing.id } | ||
| } | ||
|
|
||
| it.each([ | ||
| ['uploadWorkspaceFile', finalizeByUpload], | ||
| ['registerUploadedWorkspaceFile', finalizeByRegistration], | ||
| ])( | ||
| '%s commits alongside a content write that already holds the workspace row', | ||
| async (_name, finalize) => { | ||
| const fixture = await seedWorkspaceWithFile() | ||
| const ready = createDeferred<number>() | ||
| const finalizeIsWaiting = createDeferred<void>() | ||
|
|
||
| // The lock sequence of `updateWorkspaceFileContent`: workspace row, then a content write. | ||
| const contentWrite = db.transaction(async (tx) => { | ||
| await lockWorkspaceStorageForMutationInTx(tx, fixture.workspaceId) | ||
| const [connection] = await tx.execute<{ pid: number }>(sql`SELECT pg_backend_pid() AS pid`) | ||
| ready.resolve(connection.pid) | ||
| await finalizeIsWaiting.promise | ||
| await tx | ||
| .update(workspaceFiles) | ||
| .set({ contentUpdatedAt: new Date(Date.now() + 1000) }) | ||
| .where(eq(workspaceFiles.id, fixture.existingFileId)) | ||
| }) | ||
| const contentWritePid = await ready.promise | ||
|
|
||
| const finalized = finalize(fixture.workspaceId, fixture.aliceId) | ||
| const settled = Promise.allSettled([contentWrite, finalized]) | ||
| try { | ||
| await expect | ||
| .poll( | ||
| async () => | ||
| ( | ||
| await db.execute( | ||
| sql`SELECT pid FROM pg_stat_activity | ||
| WHERE ${contentWritePid} = ANY(pg_blocking_pids(pid))` | ||
| ) | ||
| ).length, | ||
| { timeout: 4000 } | ||
| ) | ||
| .toBe(1) | ||
| } finally { | ||
| finalizeIsWaiting.resolve() | ||
| await settled | ||
| } | ||
|
|
||
| const results = await settled | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
| expect(results.filter((result) => result.status === 'rejected')).toEqual([]) | ||
| } | ||
| ) | ||
| }) | ||
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.