Skip to content

The open alternative to Salesforce, designed for AI.

fix(logic-function): backfill missing file rows of logic function files (#26554)

martmullf07491552146
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-upgrade-version-command.module.ts
index b4a6e66a63f..304e83dac1b 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-upgrade-version-command.module.ts
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
import { AgentHistoryMigrationModule } from 'src/database/commands/agent-history/agent-history-migration.module';
import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';
@@ -6,7 +7,10 @@ import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai
import { AttributeChatMessageSendersCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790171503075-attribute-chat-message-senders.command';
import { DeleteSystemReadableObjectNavigationCommandMenuItemsCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790180964414-delete-system-readable-object-navigation-command-menu-items.command';
import { MoveCampaignSendingTablesToWorkspaceCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790203235337-move-campaign-sending-tables-to-workspace.command';
+import { BackfillLogicFunctionFileRowsCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790262034322-backfill-logic-function-file-rows.command';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
+import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
+import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
@@ -15,6 +19,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
AgentHistoryMigrationModule,
AgentHistoryModule,
ApplicationModule,
+ TypeOrmModule.forFeature([FileEntity]),
WorkspaceCacheModule,
WorkspaceIteratorModule,
WorkspaceMigrationModule,
@@ -23,6 +28,8 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
AttributeChatMessageSendersCommand,
DeleteSystemReadableObjectNavigationCommandMenuItemsCommand,
MoveCampaignSendingTablesToWorkspaceCommand,
+ BackfillLogicFunctionFileRowsCommand,
+ provideWorkspaceScopedRepository(FileEntity),
],
})
export class V2_43_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790262034322-backfill-logic-function-file-rows.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790262034322-backfill-logic-function-file-rows.command.ts
new file mode 100644
index 00000000000..f2c605e2280
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790262034322-backfill-logic-function-file-rows.command.ts
@@ -0,0 +1,216 @@
+import chunk from 'lodash.chunk';
+import { Command } from 'nest-commander';
+import { isDefined } from 'twenty-shared/utils';
+import { In } from 'typeorm';
+
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import {
+ buildLogicFunctionFiles,
+ type LogicFunctionFile,
+} from 'src/database/commands/upgrade-version-command/2-43/utils/build-logic-function-files.util';
+import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
+import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
+import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.types';
+import { extractFileInfoOrThrow } from 'src/engine/core-modules/file/utils/extract-file-info-or-throw.utils';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const FILE_ROW_LOOKUP_BATCH_SIZE = 500;
+const STORAGE_LOOKUP_BATCH_SIZE = 20;
+const FILE_ROW_INSERT_BATCH_SIZE = 500;
+
+type StoredLogicFunctionFile = LogicFunctionFile & {
+ size: number;
+};
+
+@RegisteredWorkspaceCommand('2.43.0', 1790262034322)
+@Command({
+ name: 'upgrade:2-43:backfill-logic-function-file-rows',
+ description:
+ 'Create the missing file rows of logic function source and built files, which workflow code step duplication requires',
+})
+export class BackfillLogicFunctionFileRowsCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly fileStorageService: FileStorageService,
+ @InjectWorkspaceScopedRepository(FileEntity)
+ private readonly fileRepository: WorkspaceScopedRepository<FileEntity>,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace({
+ workspaceId,
+ options,
+ }: RunOnWorkspaceArgs): Promise<void> {
+ const { flatLogicFunctionMaps, flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatLogicFunctionMaps',
+ 'flatApplicationMaps',
+ ]);
+
+ const logicFunctionFiles = buildLogicFunctionFiles({
+ flatLogicFunctions: Object.values(
+ flatLogicFunctionMaps.byUniversalIdentifier,
+ ),
+ flatApplicationMaps,
+ });
+
+ if (logicFunctionFiles.length === 0) {
+ return;
+ }
+
+ const filesWithoutFileRow = await this.findFilesWithoutFileRow({
+ workspaceId,
+ files: logicFunctionFiles,
+ });
+
+ const storedFiles = await this.findStoredFiles({
+ workspaceId,
+ files: filesWithoutFileRow,
+ });
+
+ const missingFromStorageCount =
+ filesWithoutFileRow.length - storedFiles.length;
+
+ if (missingFromStorageCount > 0) {
+ this.logger.warn(
+ `Skipping ${missingFromStorageCount} logic function file(s) missing from storage for workspace ${workspaceId}`,
+ );
+ }
+
+ if (storedFiles.length > 0) {
+ this.logger.log(
+ `${options.dryRun ? '[DRY RUN] ' : ''}Backfilling ${storedFiles.length} logic function file row(s) for workspace ${workspaceId}`,
+ );
+ }
+
+ if (options.dryRun) {
+ return;
+ }
+
+ try {
+ await this.insertFileRows({ workspaceId, storedFiles });
+ } finally {
+ // Rows inserted here bypass the storage stock counters, and a rerun
+ // cannot see what a partial run inserted, so always drop them.
+ const applicationIds = new Set(
+ logicFunctionFiles.map(({ applicationId }) => applicationId),
+ );
+
+ for (const applicationId of applicationIds) {
+ await this.fileStorageService.invalidateStorageStock({
+ workspaceId,
+ applicationId,
+ });
+ }
+ }
+ }
+
+ private async findFilesWithoutFileRow({
+ workspaceId,
+ files,
+ }: {
+ workspaceId: string;
+ files: LogicFunctionFile[];
+ }): Promise<LogicFunctionFile[]> {
+ const filesWithoutFileRow: LogicFunctionFile[] = [];
+
+ for (const batch of chunk(files, FILE_ROW_LOOKUP_BATCH_SIZE)) {
+ const existingFileRows = await this.fileRepository.find(workspaceId, {
+ select: { applicationId: true, path: true },
+ where: { path: In(batch.map(({ path }) => path)) },
+ withDeleted: true,
+ });
+
+ const existingFileRowKeys = new Set(
+ existingFileRows.map(
+ ({ applicationId, path }) => `${applicationId}:${path}`,
+ ),
+ );
+
+ filesWithoutFileRow.push(
+ ...batch.filter(
+ ({ applicationId, path }) =>
+ !existingFileRowKeys.has(`${applicationId}:${path}`),
+ ),
+ );
+ }
+
+ return filesWithoutFileRow;
+ }
+
+ private async findStoredFiles({
+ workspaceId,
+ files,
+ }: {
+ workspaceId: string;
+ files: LogicFunctionFile[];
+ }): Promise<StoredLogicFunctionFile[]> {
+ const storedFiles: StoredLogicFunctionFile[] = [];
+
+ for (const batch of chunk(files, STORAGE_LOOKUP_BATCH_SIZE)) {
+ const fileMetadatas = await Promise.all(
+ batch.map((file) =>
+ this.fileStorageService.getFileMetadata({
+ workspaceId,
+ applicationUniversalIdentifier: file.applicationUniversalIdentifier,
+ fileFolder: file.fileFolder,
+ resourcePath: file.resourcePath,
+ }),
+ ),
+ );
+
+ batch.forEach((file, index) => {
+ const fileMetadata = fileMetadatas[index];
+
+ if (isDefined(fileMetadata)) {
+ storedFiles.push({ ...file, size: fileMetadata.size });
+ }
+ });
+ }
+
+ return storedFiles;
+ }
+
+ private async insertFileRows({
+ workspaceId,
+ storedFiles,
+ }: {
+ workspaceId: string;
+ storedFiles: StoredLogicFunctionFile[];
+ }): Promise<void> {
+ for (const batch of chunk(storedFiles, FILE_ROW_INSERT_BATCH_SIZE)) {
+ const fileRows = await Promise.all(
+ batch.map(async ({ applicationId, path, resourcePath, size }) => {
+ const { mimeType } = await extractFileInfoOrThrow({
+ file: Buffer.alloc(0),
+ filename: resourcePath,
+ });
+
+ return {
+ workspaceId,
+ applicationId,
+ path,
+ size,
+ mimeType,
+ status: FILE_STATUS.UPLOADED,
+ settings: { isTemporaryFile: false, toDelete: false },
+ };
+ }),
+ );
+
+ await this.fileRepository
+ .createQueryBuilder()
+ .insert()
+ .values(fileRows)
+ .orIgnore()
+ .execute();
+ }
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/__tests__/2-43-workspace-command-1790262034322-backfill-logic-function-file-rows.command.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/__tests__/2-43-workspace-command-1790262034322-backfill-logic-function-file-rows.command.spec.ts
new file mode 100644
index 00000000000..d129355eaae
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/__tests__/2-43-workspace-command-1790262034322-backfill-logic-function-file-rows.command.spec.ts
@@ -0,0 +1,205 @@
+import { FileFolder } from 'twenty-shared/types';
+import { In } from 'typeorm';
+
+import { type WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { BackfillLogicFunctionFileRowsCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790262034322-backfill-logic-function-file-rows.command';
+import { type FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
+import { type FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
+import { type WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const WORKSPACE_ID = '20202020-0000-0000-0000-000000000001';
+const APPLICATION = {
+ id: '20202020-0000-0000-0000-0000000000aa',
+ universalIdentifier: '20202020-0000-0000-0000-0000000000bb',
+ deletedAt: null,
+};
+const LOGIC_FUNCTION_ID = '20202020-0000-0000-0000-000000000010';
+
+const SOURCE_FILE_PATH = `source/${LOGIC_FUNCTION_ID}/src/index.ts`;
+const BUILT_FILE_PATH = `built-logic-function/${LOGIC_FUNCTION_ID}/src/index.mjs`;
+
+describe('BackfillLogicFunctionFileRowsCommand', () => {
+ let command: BackfillLogicFunctionFileRowsCommand;
+ let findFileRowsMock: jest.Mock;
+ let getFileMetadataMock: jest.Mock;
+ let invalidateStorageStockMock: jest.Mock;
+ let insertValuesMock: jest.Mock;
+ let insertExecuteMock: jest.Mock;
+ let loggerWarnMock: jest.SpyInstance;
+
+ beforeEach(() => {
+ findFileRowsMock = jest.fn().mockResolvedValue([]);
+ getFileMetadataMock = jest.fn().mockResolvedValue({ size: 42 });
+ invalidateStorageStockMock = jest.fn();
+
+ const insertQueryBuilder = {
+ insert: jest.fn().mockReturnThis(),
+ values: jest.fn().mockReturnThis(),
+ orIgnore: jest.fn().mockReturnThis(),
+ execute: jest.fn().mockResolvedValue({}),
+ };
+
+ insertValuesMock = insertQueryBuilder.values;
+ insertExecuteMock = insertQueryBuilder.execute;
+
+ command = new BackfillLogicFunctionFileRowsCommand(
+ {} as WorkspaceIteratorService,
+ {
+ getOrRecompute: jest.fn().mockResolvedValue({
+ flatLogicFunctionMaps: {
+ byUniversalIdentifier: {
+ 'logic-function': {
+ id: LOGIC_FUNCTION_ID,
+ applicationId: APPLICATION.id,
+ sourceHandlerPath: `${LOGIC_FUNCTION_ID}/src/index.ts`,
+ builtHandlerPath: `${LOGIC_FUNCTION_ID}/src/index.mjs`,
+ },
+ },
+ },
+ flatApplicationMaps: {
+ byId: { [APPLICATION.id]: APPLICATION },
+ idByUniversalIdentifier: {
+ [APPLICATION.universalIdentifier]: APPLICATION.id,
+ },
+ },
+ }),
+ } as unknown as WorkspaceCacheService,
+ {
+ getFileMetadata: getFileMetadataMock,
+ invalidateStorageStock: invalidateStorageStockMock,
+ } as unknown as FileStorageService,
+ {
+ find: findFileRowsMock,
+ createQueryBuilder: jest.fn().mockReturnValue(insertQueryBuilder),
+ } as unknown as WorkspaceScopedRepository<FileEntity>,
+ );
+
+ loggerWarnMock = jest.spyOn(command['logger'], 'warn').mockImplementation();
+ jest.spyOn(command['logger'], 'log').mockImplementation();
+ });
+
+ const runOnWorkspace = (dryRun = false) =>
+ command.runOnWorkspace({
+ workspaceId: WORKSPACE_ID,
+ options: { dryRun },
+ index: 0,
+ total: 1,
+ });
+
+ const getInsertedPaths = () =>
+ insertValuesMock.mock.calls
+ .flatMap(([fileRows]) => fileRows)
+ .map(({ path }: { path: string }) => path);
+
+ it('creates the missing file rows of stored logic function files', async () => {
+ getFileMetadataMock
+ .mockResolvedValueOnce({ size: 120 })
+ .mockResolvedValueOnce({ size: 340 });
+
+ await runOnWorkspace();
+
+ expect(getFileMetadataMock).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ applicationUniversalIdentifier: APPLICATION.universalIdentifier,
+ fileFolder: FileFolder.Source,
+ resourcePath: `${LOGIC_FUNCTION_ID}/src/index.ts`,
+ });
+ expect(insertValuesMock).toHaveBeenCalledWith([
+ {
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION.id,
+ path: SOURCE_FILE_PATH,
+ size: 120,
+ mimeType: 'application/typescript',
+ status: 'UPLOADED',
+ settings: { isTemporaryFile: false, toDelete: false },
+ },
+ {
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION.id,
+ path: BUILT_FILE_PATH,
+ size: 340,
+ mimeType: 'text/javascript',
+ status: 'UPLOADED',
+ settings: { isTemporaryFile: false, toDelete: false },
+ },
+ ]);
+ expect(invalidateStorageStockMock).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION.id,
+ });
+ });
+
+ it('only looks up the file rows of logic function files', async () => {
+ await runOnWorkspace();
+
+ expect(findFileRowsMock).toHaveBeenCalledWith(
+ WORKSPACE_ID,
+ expect.objectContaining({
+ where: { path: In([SOURCE_FILE_PATH, BUILT_FILE_PATH]) },
+ withDeleted: true,
+ }),
+ );
+ });
+
+ it('only backfills the files that have no file row', async () => {
+ findFileRowsMock.mockResolvedValue([
+ { applicationId: APPLICATION.id, path: SOURCE_FILE_PATH },
+ ]);
+
+ await runOnWorkspace();
+
+ expect(getFileMetadataMock).toHaveBeenCalledTimes(1);
+ expect(getInsertedPaths()).toEqual([BUILT_FILE_PATH]);
+ });
+
+ it('skips the files missing from storage', async () => {
+ getFileMetadataMock
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({ size: 340 });
+
+ await runOnWorkspace();
+
+ expect(getInsertedPaths()).toEqual([BUILT_FILE_PATH]);
+ expect(loggerWarnMock).toHaveBeenCalledWith(
+ expect.stringContaining(
+ 'Skipping 1 logic function file(s) missing from storage',
+ ),
+ );
+ });
+
+ it('writes nothing in dry run', async () => {
+ await runOnWorkspace(true);
+
+ expect(insertValuesMock).not.toHaveBeenCalled();
+ expect(invalidateStorageStockMock).not.toHaveBeenCalled();
+ });
+
+ it('drops the storage stock counters when an insert fails', async () => {
+ insertExecuteMock.mockRejectedValue(new Error('insert failed'));
+
+ await expect(runOnWorkspace()).rejects.toThrow('insert failed');
+
+ expect(invalidateStorageStockMock).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION.id,
+ });
+ });
+
+ it('drops the storage stock counters when a previous run already inserted every row', async () => {
+ findFileRowsMock.mockResolvedValue([
+ { applicationId: APPLICATION.id, path: SOURCE_FILE_PATH },
+ { applicationId: APPLICATION.id, path: BUILT_FILE_PATH },
+ ]);
+
+ await runOnWorkspace();
+
+ expect(getFileMetadataMock).not.toHaveBeenCalled();
+ expect(insertValuesMock).not.toHaveBeenCalled();
+ expect(invalidateStorageStockMock).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION.id,
+ });
+ });
+});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/__tests__/build-logic-function-files.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/__tests__/build-logic-function-files.util.spec.ts
new file mode 100644
index 00000000000..6cd5dc5318e
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/__tests__/build-logic-function-files.util.spec.ts
@@ -0,0 +1,112 @@
+import { FileFolder } from 'twenty-shared/types';
+
+import { buildLogicFunctionFiles } from 'src/database/commands/upgrade-version-command/2-43/utils/build-logic-function-files.util';
+import { type FlatApplicationCacheMaps } from 'src/engine/core-modules/application/types/flat-application-cache-maps.type';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+
+const APPLICATION_ID = 'application-id';
+const APPLICATION_UNIVERSAL_IDENTIFIER = 'application-universal-identifier';
+
+const buildFlatApplicationMaps = (
+ applications: Partial<FlatApplication>[],
+): FlatApplicationCacheMaps =>
+ ({
+ byId: Object.fromEntries(
+ applications.map((application) => [application.id, application]),
+ ),
+ idByUniversalIdentifier: Object.fromEntries(
+ applications.map((application) => [
+ application.universalIdentifier,
+ application.id,
+ ]),
+ ),
+ }) as FlatApplicationCacheMaps;
+
+const FLAT_APPLICATION_MAPS = buildFlatApplicationMaps([
+ {
+ id: APPLICATION_ID,
+ universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ deletedAt: null,
+ },
+]);
+
+const buildFlatLogicFunction = (
+ logicFunctionId: string,
+ overrides: Partial<FlatLogicFunction> = {},
+): FlatLogicFunction =>
+ ({
+ id: logicFunctionId,
+ applicationId: APPLICATION_ID,
+ sourceHandlerPath: `${logicFunctionId}/src/index.ts`,
+ builtHandlerPath: `${logicFunctionId}/src/index.mjs`,
+ ...overrides,
+ }) as FlatLogicFunction;
+
+describe('buildLogicFunctionFiles', () => {
+ it('returns the source and built files of each logic function', () => {
+ const result = buildLogicFunctionFiles({
+ flatLogicFunctions: [buildFlatLogicFunction('logic-function'), undefined],
+ flatApplicationMaps: FLAT_APPLICATION_MAPS,
+ });
+
+ expect(result).toEqual([
+ {
+ applicationId: APPLICATION_ID,
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ fileFolder: FileFolder.Source,
+ resourcePath: 'logic-function/src/index.ts',
+ path: 'source/logic-function/src/index.ts',
+ },
+ {
+ applicationId: APPLICATION_ID,
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ fileFolder: FileFolder.BuiltLogicFunction,
+ resourcePath: 'logic-function/src/index.mjs',
+ path: 'built-logic-function/logic-function/src/index.mjs',
+ },
+ ]);
+ });
+
+ it('skips logic functions whose application is missing or deleted', () => {
+ const result = buildLogicFunctionFiles({
+ flatLogicFunctions: [
+ buildFlatLogicFunction('unknown-application-logic-function', {
+ applicationId: 'unknown-application-id',
+ }),
+ buildFlatLogicFunction('deleted-application-logic-function', {
+ applicationId: 'deleted-application-id',
+ }),
+ ],
+ flatApplicationMaps: buildFlatApplicationMaps([
+ {
+ id: 'deleted-application-id',
+ universalIdentifier: 'deleted-application',
+ deletedAt: new Date('2026-09-01T00:00:00.000Z'),
+ },
+ ]),
+ });
+
+ expect(result).toEqual([]);
+ });
+
+ it('returns a file shared by several logic functions once', () => {
+ const sharedHandlerPaths = {
+ sourceHandlerPath: 'shared/src/index.ts',
+ builtHandlerPath: 'shared/src/index.mjs',
+ };
+
+ const result = buildLogicFunctionFiles({
+ flatLogicFunctions: [
+ buildFlatLogicFunction('first-logic-function', sharedHandlerPaths),
+ buildFlatLogicFunction('second-logic-function', sharedHandlerPaths),
+ ],
+ flatApplicationMaps: FLAT_APPLICATION_MAPS,
+ });
+
+ expect(result.map(({ path }) => path)).toEqual([
+ 'source/shared/src/index.ts',
+ 'built-logic-function/shared/src/index.mjs',
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/build-logic-function-files.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/build-logic-function-files.util.ts
new file mode 100644
index 00000000000..b6b8b97ee33
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/build-logic-function-files.util.ts
@@ -0,0 +1,66 @@
+import { join } from 'path';
+
+import { FileFolder } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatApplicationCacheMaps } from 'src/engine/core-modules/application/types/flat-application-cache-maps.type';
+import { findActiveFlatApplicationById } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-id.util';
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+
+export type LogicFunctionFile = {
+ applicationId: string;
+ applicationUniversalIdentifier: string;
+ fileFolder: FileFolder;
+ resourcePath: string;
+ path: string;
+};
+
+export const buildLogicFunctionFiles = ({
+ flatLogicFunctions,
+ flatApplicationMaps,
+}: {
+ flatLogicFunctions: (FlatLogicFunction | undefined)[];
+ flatApplicationMaps: FlatApplicationCacheMaps;
+}): LogicFunctionFile[] => {
+ const logicFunctionFileByKey = new Map<string, LogicFunctionFile>();
+
+ for (const flatLogicFunction of flatLogicFunctions) {
+ if (!isDefined(flatLogicFunction)) {
+ continue;
+ }
+
+ const flatApplication = findActiveFlatApplicationById(
+ flatApplicationMaps,
+ flatLogicFunction.applicationId,
+ );
+
+ if (!isDefined(flatApplication)) {
+ continue;
+ }
+
+ const handlerFiles = [
+ {
+ fileFolder: FileFolder.Source,
+ resourcePath: flatLogicFunction.sourceHandlerPath,
+ },
+ {
+ fileFolder: FileFolder.BuiltLogicFunction,
+ resourcePath: flatLogicFunction.builtHandlerPath,
+ },
+ ];
+
+ for (const { fileFolder, resourcePath } of handlerFiles) {
+ const path = join(fileFolder, resourcePath);
+
+ logicFunctionFileByKey.set(`${flatApplication.id}:${path}`, {
+ applicationId: flatApplication.id,
+ applicationUniversalIdentifier: flatApplication.universalIdentifier,
+ fileFolder,
+ resourcePath,
+ path,
+ });
+ }
+ }
+
+ return [...logicFunctionFileByKey.values()];
+};