The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Skip identical file writes using a stored content hash (#28213)
neo77374118a0ecdf3
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-instance-command-fast-1792581115000-add-content-sha256-to-file.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-instance-command-fast-1792581115000-add-content-sha256-to-file.tsnew file mode 100644index 00000000000..7f895679ab5--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-instance-command-fast-1792581115000-add-content-sha256-to-file.ts@@ -0,0 +1,19 @@+import { type QueryRunner } from 'typeorm';++import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';+import { type FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';++@RegisteredInstanceCommand('2.51.0', 1792581115000)+export class AddContentSha256ToFileFastInstanceCommand implements FastInstanceCommand {+ public async up(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(+ 'ALTER TABLE "core"."file" ADD "contentSha256" character varying',+ );+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(+ 'ALTER TABLE "core"."file" DROP COLUMN "contentSha256"',+ );+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.tsindex d4a85354b0e..20690f4c464 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts@@ -250,6 +250,7 @@ import { AddConnectedAccountScopeFastInstanceCommand } from 'src/database/commanimport { AddExcludePrivateEventsToCalendarChannelFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-49/2-49-instance-command-fast-1792319637000-add-exclude-private-events-to-calendar-channel';import { AddPeriodMaxSeatsToBillingSubscriptionFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-50/2-50-instance-command-fast-1792410699010-add-period-max-seats-to-billing-subscription';import { DropBillingMeterTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-50/2-50-instance-command-fast-1792480059403-drop-billing-meter-table';+import { AddContentSha256ToFileFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-51/2-51-instance-command-fast-1792581115000-add-content-sha256-to-file';export const INSTANCE_COMMANDS = [AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,@@ -502,4 +503,5 @@ export const INSTANCE_COMMANDS = [AddExcludePrivateEventsToCalendarChannelFastInstanceCommand,AddPeriodMaxSeatsToBillingSubscriptionFastInstanceCommand,DropBillingMeterTableFastInstanceCommand,+ AddContentSha256ToFileFastInstanceCommand,];diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/file-storage.module.ts b/packages/twenty-server/src/engine/core-modules/file-storage/file-storage.module.tsindex 6754ebfd872..44fea4231da 100644--- a/packages/twenty-server/src/engine/core-modules/file-storage/file-storage.module.ts+++ b/packages/twenty-server/src/engine/core-modules/file-storage/file-storage.module.ts@@ -2,6 +2,7 @@ import { type DynamicModule, Global } from '@nestjs/common';import { APP_FILTER } from '@nestjs/core';import { TypeOrmModule } from '@nestjs/typeorm';+import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';import { FileStorageExceptionFilter } from 'src/engine/core-modules/file-storage/file-storage-exception-filter';import { FileStorageDriverFactory } from 'src/engine/core-modules/file-storage/file-storage-driver.factory';import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';@@ -18,6 +19,7 @@ export class FileStorageModule {module: FileStorageModule,imports: [TwentyConfigModule,+ CacheLockModule,TypeOrmModule.forFeature([FileEntity]),WorkspaceCacheModule,UsageLimitModule,diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.tsindex 3d9bea49943..7f4c6fc8bf1 100644--- a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts+++ b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts@@ -1,6 +1,7 @@import { Injectable } from '@nestjs/common';-import { isString } from '@sniptt/guards';+import { isNonEmptyString, isString } from '@sniptt/guards';+import { createHash } from 'crypto';import { basename, dirname, join } from 'path';import { type Readable } from 'stream';import { v4 } from 'uuid';@@ -17,6 +18,8 @@ import {import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';import { findActiveFlatApplicationById } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-id.util';import { findActiveFlatApplicationByUniversalIdentifier } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-universal-identifier.util';+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';+import { type StorageDriver } from 'src/engine/core-modules/file-storage/drivers/interfaces/storage-driver.interface';import { FileStorageDriverFactory } from 'src/engine/core-modules/file-storage/file-storage-driver.factory';import {FileStorageException,@@ -24,6 +27,7 @@ import {} from 'src/engine/core-modules/file-storage/interfaces/file-storage-exception';import { type ByteRange } from 'src/engine/core-modules/file-storage/types/byte-range.type';import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';+import { buildFileWriteLockKey } from 'src/engine/core-modules/file-storage/utils/build-file-write-lock-key.util';import { buildReleasedStockByApplication } from 'src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util';import { buildStockDelta } from 'src/engine/core-modules/file-storage/utils/build-stock-delta.util';import { prepareFileForStorageOrThrow } from 'src/engine/core-modules/file-storage/utils/prepare-file-for-storage-or-throw.util';@@ -60,6 +64,7 @@ export class FileStorageService {private readonly fileRepository: WorkspaceScopedRepository<FileEntity>,private readonly workspaceCacheService: WorkspaceCacheService,private readonly usageLimitStockService: UsageLimitStockService,+ private readonly cacheLockService: CacheLockService,) {}async releaseStorageStock({@@ -423,6 +428,35 @@ export class FileStorageService {};}+ private async isStoredContentUnchanged({+ driver,+ onStorageFilePath,+ existingFile,+ contentSha256,+ mimeType,+ }: {+ driver: StorageDriver;+ onStorageFilePath: string;+ existingFile: Pick<+ FileEntity,+ 'deletedAt' | 'status' | 'mimeType' | 'contentSha256'+ > | null;+ contentSha256: string;+ mimeType: string;+ }): Promise<boolean> {+ if (+ !isDefined(existingFile) ||+ isDefined(existingFile.deletedAt) ||+ existingFile.status !== FILE_STATUS.UPLOADED ||+ existingFile.mimeType !== mimeType ||+ existingFile.contentSha256 !== contentSha256+ ) {+ return false;+ }++ return driver.checkFileExists({ filePath: onStorageFilePath });+ }+async writeFile({sourceFile,fileFolder,@@ -472,47 +506,85 @@ export class FileStorageService {? Buffer.byteLength(persistedSourceFile): persistedSourceFile.length;- const existingFile = await this.findFileByPath({- fileRepository: fileRepository,- workspaceId,- filePath,- applicationId: resolvedApplicationId,- });+ const contentSha256 = createHash('sha256')+ .update(persistedSourceFile)+ .digest('hex');++ return this.cacheLockService.withLock(+ async () => {+ const existingFile = await this.findFileByPath({+ fileRepository,+ workspaceId,+ filePath,+ applicationId: resolvedApplicationId,+ });- const delta = buildStockDelta({ existingFile, size });+ const delta = buildStockDelta({ existingFile, size });- await this.assertStorageStockAvailable({- workspaceId,- applicationId: resolvedApplicationId,- delta,- });+ await this.assertStorageStockAvailable({+ workspaceId,+ applicationId: resolvedApplicationId,+ delta,+ });- await driver.writeFile({- filePath: onStorageFilePath,- mimeType,- sourceFile: persistedSourceFile,- });+ const isStoredContentUnchanged =+ !isDefined(queryRunner) &&+ (await this.isStoredContentUnchanged({+ driver,+ onStorageFilePath,+ existingFile,+ contentSha256,+ mimeType,+ }));++ if (!isStoredContentUnchanged) {+ if (+ isNonEmptyString(existingFile?.contentSha256) &&+ (isDefined(queryRunner) ||+ existingFile.contentSha256 !== contentSha256)+ ) {+ await this.fileRepository.update(+ workspaceId,+ { id: existingFile.id },+ { contentSha256: null },+ );+ }++ await driver.writeFile({+ filePath: onStorageFilePath,+ mimeType,+ sourceFile: persistedSourceFile,+ });+ }++ const file = await fileRepository.upsertAndReturnOne(+ workspaceId,+ {+ path: filePath,+ applicationId: resolvedApplicationId,+ id: existingFile?.id ?? fileId,+ mimeType,+ size,+ settings,+ contentSha256: isDefined(queryRunner) ? null : contentSha256,+ },+ ['path', 'workspaceId', 'applicationId'],+ );- const file = await fileRepository.upsertAndReturnOne(- workspaceId,- {- path: filePath,- applicationId: resolvedApplicationId,- id: existingFile?.id ?? fileId,- mimeType,- size,- settings,+ await this.applyStorageStockDelta({+ workspaceId,+ applicationId: resolvedApplicationId,+ delta,+ });++ return file;},- ['path', 'workspaceId', 'applicationId'],+ buildFileWriteLockKey({+ workspaceId,+ applicationId: resolvedApplicationId,+ filePath,+ }),);-- await this.applyStorageStockDelta({- workspaceId,- applicationId: resolvedApplicationId,- delta,- });-- return file;}// Stays PENDING until completeFileUpload confirms it or the cleanup cron reaps it.@@ -572,6 +644,7 @@ export class FileStorageService {size,settings,status: FILE_STATUS.PENDING,+ contentSha256: null,},['path', 'workspaceId', 'applicationId'],);@@ -585,7 +658,52 @@ export class FileStorageService {return file;}- async markFileUploaded({+ async promotePendingFile({+ workspaceId,+ file,+ from,+ to,+ ifMatchChecksum,+ size,+ mimeType,+ }: {+ workspaceId: string;+ file: Pick<FileEntity, 'id' | 'path' | 'applicationId' | 'size'>;+ from: ResourceIdentifier;+ to: ResourceIdentifier;+ ifMatchChecksum?: string;+ size: number;+ mimeType: string;+ }): Promise<UpdateResult> {+ return this.cacheLockService.withLock(+ async () => {+ await this.fileRepository.update(+ workspaceId,+ { path: file.path, applicationId: file.applicationId },+ { contentSha256: null },+ );++ // The presigned PUT can still overwrite quarantine after the sniff, so only the inspected version is promoted.+ await this.move({ from, to, ifMatchChecksum });++ return this.markFileUploaded({+ workspaceId,+ applicationId: file.applicationId,+ fileId: file.id,+ chargedSize: Number(file.size),+ size,+ mimeType,+ });+ },+ buildFileWriteLockKey({+ workspaceId,+ applicationId: file.applicationId,+ filePath: file.path,+ }),+ );+ }++ private async markFileUploaded({workspaceId,applicationId,fileId,@@ -992,7 +1110,7 @@ export class FileStorageService {});}- async move({+ private async move({from,to,ifMatchChecksum,diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-file-write-lock-key.util.ts b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-file-write-lock-key.util.tsnew file mode 100644index 00000000000..d80c239faf0--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-file-write-lock-key.util.ts@@ -0,0 +1,9 @@+export const buildFileWriteLockKey = ({+ workspaceId,+ applicationId,+ filePath,+}: {+ workspaceId: string;+ applicationId: string;+ filePath: string;+}): string => `file-write:${workspaceId}:${applicationId}:${filePath}`;diff --git a/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts b/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.tsindex 566360eef15..768d77cc479 100644--- a/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts+++ b/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts@@ -128,4 +128,11 @@ export class FileEntity {default: FILE_STATUS.UPLOADED,})status: FileStatus;++ @WasIntroducedInUpgrade({+ upgradeCommandName:+ '2.51.0_AddContentSha256ToFileFastInstanceCommand_1792581115000',+ })+ @Column({ type: 'varchar', nullable: true })+ contentSha256: string | null;}diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.tsindex 80df6a539a5..d61653cad2a 100644--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts@@ -126,18 +126,12 @@ export class FileUploadCompletionService {metadata,});- // The presigned PUT can still overwrite quarantine after the sniff, so only the inspected version is promoted.- await this.fileStorageService.move({+ const { affected } = await this.fileStorageService.promotePendingFile({+ workspaceId,+ file,from: pendingLocation,to: storageLocation,ifMatchChecksum: checksum,- });-- const { affected } = await this.fileStorageService.markFileUploaded({- workspaceId,- applicationId: file.applicationId,- fileId: file.id,- chargedSize: declaredSize,size,mimeType,});diff --git a/packages/twenty-server/test/integration/file-storage/write-file-unchanged-content.integration-spec.ts b/packages/twenty-server/test/integration/file-storage/write-file-unchanged-content.integration-spec.tsnew file mode 100644index 00000000000..9ce3b0ff2f3--- /dev/null+++ b/packages/twenty-server/test/integration/file-storage/write-file-unchanged-content.integration-spec.ts@@ -0,0 +1,251 @@+import { createHash } from 'crypto';+import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';+import { dirname, join } from 'path';++import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { FileFolder } from 'twenty-shared/types';+import { type DataSource, type QueryRunner } from 'typeorm';+import { v4 } from 'uuid';++import { type FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';+import { buildPendingUploadResourcePath } from 'src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++const STORAGE_LOCAL_PATH = join(process.cwd(), '.local-storage');+const FILE_FOLDER = FileFolder.Workflow;+const FILE_SETTINGS = { isTemporaryFile: false, toDelete: false };++const computeSha256 = (content: string | Buffer) =>+ createHash('sha256').update(content).digest('hex');++describe('Writing a file whose stored content is unchanged', () => {+ let fileStorageService: FileStorageService;+ let applicationUniversalIdentifier: string;+ const writtenResourcePaths = new Set<string>();++ const writeFile = ({+ resourcePath,+ content,+ queryRunner,+ }: {+ resourcePath: string;+ content: string;+ queryRunner?: QueryRunner;+ }) => {+ writtenResourcePaths.add(resourcePath);++ return fileStorageService.writeFile({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ applicationUniversalIdentifier,+ fileFolder: FILE_FOLDER,+ resourcePath,+ sourceFile: content,+ settings: FILE_SETTINGS,+ queryRunner,+ });+ };++ const getStoredFilePath = (resourcePath: string) =>+ join(+ STORAGE_LOCAL_PATH,+ SEED_APPLE_WORKSPACE_ID,+ applicationUniversalIdentifier,+ FILE_FOLDER,+ resourcePath,+ );++ const findRowContentSha256 = async (+ resourcePath: string,+ ): Promise<string | null> => {+ const [file]: { contentSha256: string | null }[] =+ await global.testDataSource.query(+ `SELECT "contentSha256" FROM core."file" WHERE "workspaceId" = $1 AND path = $2`,+ [SEED_APPLE_WORKSPACE_ID, `${FILE_FOLDER}/${resourcePath}`],+ );++ return file.contentSha256;+ };++ const waitForMtimeResolution = () =>+ new Promise((resolve) => setTimeout(resolve, 20));++ beforeAll(async () => {+ jest.useRealTimers();++ fileStorageService =+ getAppProviderByClassName<FileStorageService>('FileStorageService');++ const [workspaceCustomApplication]: { universalIdentifier: string }[] =+ await global.testDataSource.query(+ `SELECT application."universalIdentifier"+ FROM core."workspace" workspace+ JOIN core."application" application+ ON application.id = workspace."workspaceCustomApplicationId"+ WHERE workspace.id = $1`,+ [SEED_APPLE_WORKSPACE_ID],+ );++ applicationUniversalIdentifier =+ workspaceCustomApplication.universalIdentifier;+ });++ afterEach(async () => {+ for (const resourcePath of writtenResourcePaths) {+ await fileStorageService.deleteFile({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ applicationUniversalIdentifier,+ fileFolder: FILE_FOLDER,+ resourcePath,+ });+ }++ writtenResourcePaths.clear();+ });++ it('leaves the stored object untouched when the content is identical', async () => {+ const resourcePath = `unchanged-content/${v4()}.txt`;++ await writeFile({ resourcePath, content: 'same' });+ const firstModifiedAt = statSync(getStoredFilePath(resourcePath)).mtimeMs;++ await waitForMtimeResolution();+ await writeFile({ resourcePath, content: 'same' });++ expect(statSync(getStoredFilePath(resourcePath)).mtimeMs).toBe(+ firstModifiedAt,+ );+ expect(await findRowContentSha256(resourcePath)).toBe(+ computeSha256('same'),+ );+ });++ it('overwrites the stored object when same-size content differs', async () => {+ const resourcePath = `unchanged-content/${v4()}.txt`;++ await writeFile({ resourcePath, content: 'aaaa' });+ await writeFile({ resourcePath, content: 'bbbb' });++ expect(readFileSync(getStoredFilePath(resourcePath), 'utf-8')).toBe('bbbb');+ expect(await findRowContentSha256(resourcePath)).toBe(+ computeSha256('bbbb'),+ );+ });++ it('writes identical content again when the stored object is gone but its row remains', async () => {+ const resourcePath = `unchanged-content/${v4()}.txt`;++ await writeFile({ resourcePath, content: 'same' });+ rmSync(getStoredFilePath(resourcePath));++ await writeFile({ resourcePath, content: 'same' });++ expect(readFileSync(getStoredFilePath(resourcePath), 'utf-8')).toBe('same');+ });++ it('hashes the sanitized bytes so resending the same unsafe svg is skipped', async () => {+ const resourcePath = `unchanged-content/${v4()}.svg`;+ const unsafeSvg =+ '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><rect width="1" height="1"/></svg>';++ await writeFile({ resourcePath, content: unsafeSvg });+ const storedSvg = readFileSync(getStoredFilePath(resourcePath));+ const firstModifiedAt = statSync(getStoredFilePath(resourcePath)).mtimeMs;++ await waitForMtimeResolution();+ await writeFile({ resourcePath, content: unsafeSvg });++ expect(storedSvg.toString('utf-8')).not.toContain('<script>');+ expect(await findRowContentSha256(resourcePath)).toBe(+ computeSha256(storedSvg),+ );+ expect(statSync(getStoredFilePath(resourcePath)).mtimeMs).toBe(+ firstModifiedAt,+ );+ });++ it('rewrites the original content after a direct upload replaced the stored object', async () => {+ const resourcePath = `unchanged-content/${v4()}.txt`;++ await writeFile({ resourcePath, content: 'aaaa' });++ const pendingFile = await fileStorageService.createPendingFile({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ applicationUniversalIdentifier,+ fileFolder: FILE_FOLDER,+ resourcePath,+ fileId: v4(),+ size: 4,+ mimeType: 'application/octet-stream',+ settings: FILE_SETTINGS,+ });++ const pendingResourcePath = buildPendingUploadResourcePath({+ fileId: pendingFile.id,+ resourcePath,+ });++ mkdirSync(dirname(getStoredFilePath(pendingResourcePath)), {+ recursive: true,+ });+ writeFileSync(getStoredFilePath(pendingResourcePath), 'bbbb');++ const storageLocation = {+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ applicationUniversalIdentifier,+ fileFolder: FILE_FOLDER,+ };++ await fileStorageService.promotePendingFile({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ file: pendingFile,+ from: { ...storageLocation, resourcePath: pendingResourcePath },+ to: { ...storageLocation, resourcePath },+ size: 4,+ mimeType: 'text/plain',+ });++ expect(readFileSync(getStoredFilePath(resourcePath), 'utf-8')).toBe('bbbb');++ await writeFile({ resourcePath, content: 'aaaa' });++ expect(readFileSync(getStoredFilePath(resourcePath), 'utf-8')).toBe('aaaa');+ });++ it('keeps the row hash in step with the stored bytes when writes race on one path', async () => {+ const resourcePath = `unchanged-content/${v4()}.txt`;++ await Promise.all(+ ['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee'].map((content) =>+ writeFile({ resourcePath, content }),+ ),+ );++ expect(await findRowContentSha256(resourcePath)).toBe(+ computeSha256(readFileSync(getStoredFilePath(resourcePath))),+ );+ });++ it('rewrites the original content after transactional writes were rolled back', async () => {+ const resourcePath = `unchanged-content/${v4()}.txt`;++ await writeFile({ resourcePath, content: 'aaaa' });++ const queryRunner =+ getAppProviderByClassName<DataSource>('DataSource').createQueryRunner();++ await queryRunner.connect();+ await queryRunner.startTransaction();++ try {+ await writeFile({ resourcePath, content: 'aaaa', queryRunner });+ await writeFile({ resourcePath, content: 'bbbb', queryRunner });+ } finally {+ await queryRunner.rollbackTransaction();+ await queryRunner.release();+ }++ await writeFile({ resourcePath, content: 'aaaa' });++ expect(readFileSync(getStoredFilePath(resourcePath), 'utf-8')).toBe('aaaa');+ });+});