|
| 1 | +/** Real PostgreSQL verifies cross-session registration and durable logo retention. */ |
| 2 | +import { db } from '@sim/db' |
| 3 | +import { withInsertColumns } from '@sim/db/insert-columns' |
| 4 | +import { member, organization, organizationColumns, uploadSession } from '@sim/db/schema' |
| 5 | +import { generateId } from '@sim/utils/id' |
| 6 | +import { eq } from 'drizzle-orm' |
| 7 | +import type { Sql } from 'postgres' |
| 8 | +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' |
| 9 | + |
| 10 | +const fixture = vi.hoisted(() => ({ |
| 11 | + schema: '', |
| 12 | + connection: undefined as Sql | undefined, |
| 13 | + deleteObject: vi.fn(), |
| 14 | + headObject: vi.fn(), |
| 15 | +})) |
| 16 | + |
| 17 | +vi.mock('@sim/db', async () => { |
| 18 | + const { drizzle } = await import('drizzle-orm/postgres-js') |
| 19 | + const { default: postgres } = await import('postgres') |
| 20 | + const { withUtcTimestamps } = await import('@sim/db/timestamps') |
| 21 | + const { generateId } = await import('@sim/utils/id') |
| 22 | + fixture.schema = `logo_test_${generateId().replaceAll('-', '')}` |
| 23 | + fixture.connection = postgres( |
| 24 | + process.env.KNOWLEDGE_ACL_TEST_DATABASE_URL!, |
| 25 | + withUtcTimestamps({ |
| 26 | + max: 4, |
| 27 | + prepare: false, |
| 28 | + fetch_types: false, |
| 29 | + connection: { search_path: fixture.schema }, |
| 30 | + onnotice: () => {}, |
| 31 | + }) |
| 32 | + ) |
| 33 | + const database = drizzle(fixture.connection) |
| 34 | + return { db: database, dbFor: () => database } |
| 35 | +}) |
| 36 | + |
| 37 | +vi.mock('@/lib/permission-groups/resolve.server', () => ({ |
| 38 | + getUserPermissionConfigForOrganization: async () => null, |
| 39 | +})) |
| 40 | +vi.mock('@sim/audit', async (importOriginal) => ({ |
| 41 | + ...(await importOriginal<typeof import('@sim/audit')>()), |
| 42 | + recordAudit: vi.fn(), |
| 43 | +})) |
| 44 | +vi.mock('@/lib/uploads/upload-session/cleanup', () => ({ |
| 45 | + maybeCleanupLocalUploadArtifacts: async () => ({ scanned: 0, removed: 0 }), |
| 46 | +})) |
| 47 | +vi.mock('@/lib/uploads/upload-session/provider', async (importOriginal) => ({ |
| 48 | + ...(await importOriginal<typeof import('@/lib/uploads/upload-session/provider')>()), |
| 49 | + createPutProviderTransfer: async () => ({ |
| 50 | + method: 'put', |
| 51 | + url: 'http://localhost/upload', |
| 52 | + headers: {}, |
| 53 | + }), |
| 54 | + headProviderObject: fixture.headObject, |
| 55 | + deleteProviderObjectVersion: fixture.deleteObject, |
| 56 | +})) |
| 57 | + |
| 58 | +import { |
| 59 | + createOrganizationLogoUpload, |
| 60 | + finalizeOrganizationLogoUpload, |
| 61 | +} from '@/lib/uploads/contexts/organization-logo/application' |
| 62 | +import { cleanupExpiredUploadSessions } from '@/lib/uploads/upload-session/service' |
| 63 | + |
| 64 | +describe('organization logo concurrency and retention', () => { |
| 65 | + const organizationId = generateId() |
| 66 | + const principals = [ |
| 67 | + { kind: 'session', userId: generateId(), sessionId: generateId() }, |
| 68 | + { kind: 'session', userId: generateId(), sessionId: generateId() }, |
| 69 | + ] as const |
| 70 | + const request = { headers: new Headers() } |
| 71 | + |
| 72 | + beforeAll(async () => { |
| 73 | + const connection = fixture.connection! |
| 74 | + await connection`CREATE SCHEMA ${connection(fixture.schema)}` |
| 75 | + for (const table of ['user', 'member', 'organization', 'upload_session']) { |
| 76 | + await connection`CREATE TABLE ${connection(table)} (LIKE ${connection(`public.${table}`)} INCLUDING ALL)` |
| 77 | + } |
| 78 | + await db.insert(withInsertColumns(organization, organizationColumns)).values({ |
| 79 | + id: organizationId, |
| 80 | + name: 'Logo test organization', |
| 81 | + slug: generateId(), |
| 82 | + createdAt: new Date(), |
| 83 | + }) |
| 84 | + await db.insert(member).values( |
| 85 | + principals.map((principal) => ({ |
| 86 | + id: generateId(), |
| 87 | + organizationId, |
| 88 | + userId: principal.userId, |
| 89 | + role: 'admin', |
| 90 | + })) |
| 91 | + ) |
| 92 | + }) |
| 93 | + |
| 94 | + beforeEach(async () => { |
| 95 | + vi.clearAllMocks() |
| 96 | + await db.delete(uploadSession) |
| 97 | + await db.update(organization).set({ logo: null }).where(eq(organization.id, organizationId)) |
| 98 | + }) |
| 99 | + |
| 100 | + afterAll(async () => { |
| 101 | + const connection = fixture.connection |
| 102 | + if (!connection) return |
| 103 | + try { |
| 104 | + await connection`DROP SCHEMA ${connection(fixture.schema)} CASCADE` |
| 105 | + } finally { |
| 106 | + await connection.end() |
| 107 | + } |
| 108 | + }) |
| 109 | + |
| 110 | + async function start(principal = principals[0]) { |
| 111 | + const session = await createOrganizationLogoUpload(principal, { |
| 112 | + organizationId, |
| 113 | + name: 'logo.png', |
| 114 | + contentType: 'image/png', |
| 115 | + size: 100, |
| 116 | + localOrigin: 'http://localhost', |
| 117 | + }) |
| 118 | + await db |
| 119 | + .update(uploadSession) |
| 120 | + .set({ status: 'finalizing' }) |
| 121 | + .where(eq(uploadSession.id, session.id)) |
| 122 | + return session |
| 123 | + } |
| 124 | + |
| 125 | + async function currentLogo() { |
| 126 | + const [row] = await db |
| 127 | + .select({ logo: organization.logo }) |
| 128 | + .from(organization) |
| 129 | + .where(eq(organization.id, organizationId)) |
| 130 | + return row.logo |
| 131 | + } |
| 132 | + |
| 133 | + it('rejects an older upload after a different administrator completes a newer one', async () => { |
| 134 | + const older = await start() |
| 135 | + const newer = await start(principals[1]) |
| 136 | + const result = await finalizeOrganizationLogoUpload(principals[1], newer, request) |
| 137 | + await expect( |
| 138 | + finalizeOrganizationLogoUpload(principals[0], older, request) |
| 139 | + ).rejects.toMatchObject({ code: 'conflict' }) |
| 140 | + expect(await currentLogo()).toBe(result.value.path) |
| 141 | + }) |
| 142 | + |
| 143 | + it('allows only one concurrent completion from the same starting logo', async () => { |
| 144 | + const sessions = await Promise.all(principals.map((principal) => start(principal))) |
| 145 | + const results = await Promise.allSettled( |
| 146 | + sessions.map((session, index) => |
| 147 | + finalizeOrganizationLogoUpload(principals[index], session, request) |
| 148 | + ) |
| 149 | + ) |
| 150 | + expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1) |
| 151 | + const rejected = results.find((result) => result.status === 'rejected') |
| 152 | + expect(rejected?.status === 'rejected' && rejected.reason).toMatchObject({ code: 'conflict' }) |
| 153 | + }) |
| 154 | + |
| 155 | + it('retains the active logo and retries deletion of a replaced logo before purging its record', async () => { |
| 156 | + const first = await start() |
| 157 | + await finalizeOrganizationLogoUpload(principals[0], first, request) |
| 158 | + const second = await start(principals[1]) |
| 159 | + const current = await finalizeOrganizationLogoUpload(principals[1], second, request) |
| 160 | + await finalizeOrganizationLogoUpload(principals[0], first, request) |
| 161 | + expect(await currentLogo()).toBe(current.value.path) |
| 162 | + await db.update(uploadSession).set({ |
| 163 | + status: 'completed', |
| 164 | + completedAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000), |
| 165 | + }) |
| 166 | + fixture.headObject.mockImplementation(async ({ key }: { key: string }) => { |
| 167 | + expect(key).toBe(first.finalKey) |
| 168 | + return { |
| 169 | + size: first.fileSize, |
| 170 | + contentType: first.contentType, |
| 171 | + uploadId: first.id, |
| 172 | + version: 'v1', |
| 173 | + } |
| 174 | + }) |
| 175 | + fixture.deleteObject.mockRejectedValueOnce(new Error('Storage unavailable')) |
| 176 | + expect(await cleanupExpiredUploadSessions()).toEqual({ expired: 0, failed: 1, purged: 0 }) |
| 177 | + expect(await db.select({ id: uploadSession.id }).from(uploadSession)).toHaveLength(2) |
| 178 | + fixture.deleteObject.mockResolvedValue(undefined) |
| 179 | + expect(await cleanupExpiredUploadSessions()).toEqual({ expired: 0, failed: 0, purged: 1 }) |
| 180 | + expect(await db.select({ id: uploadSession.id }).from(uploadSession)).toEqual([ |
| 181 | + { id: second.id }, |
| 182 | + ]) |
| 183 | + expect(await currentLogo()).toBe(current.value.path) |
| 184 | + expect(fixture.deleteObject).toHaveBeenLastCalledWith( |
| 185 | + expect.objectContaining({ |
| 186 | + key: first.finalKey, |
| 187 | + context: 'organization-logos', |
| 188 | + version: 'v1', |
| 189 | + }) |
| 190 | + ) |
| 191 | + }) |
| 192 | +}) |
0 commit comments