Skip to content

The open alternative to Salesforce, designed for AI.

refactor(server): warm up prebuilt logic functions after the install migration commits (#25672)

Paul Rastoin12a91d180773
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/workspace-graphql-schema-sdl.service.ts b/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/workspace-graphql-schema-sdl.service.ts
index 3eff6678ce4..7770663d49b 100644
--- a/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/workspace-graphql-schema-sdl.service.ts
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/workspace-graphql-schema-sdl.service.ts
@@ -5,8 +5,7 @@ import { printSchema } from 'graphql';
import { isDefined } from 'twenty-shared/utils';
import { ScalarsExplorerService } from 'src/engine/api/graphql/services/scalars-explorer.service';
-import { SCHEMA_SDL_CACHE_DEPENDENCIES } from 'src/engine/api/graphql/workspace-graphql-schema-sdl/constants/schema-sdl-cache-dependencies.constant';
-import { type ObjectFieldIndexFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type';
+import { type SchemaGenerationContext } from 'src/engine/api/graphql/workspace-schema-builder/types/schema-generation-context.type';
import { WorkspaceGraphQLSchemaGenerator } from 'src/engine/api/graphql/workspace-schema-builder/workspace-graphql-schema.factory';
import { FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
import {
@@ -19,6 +18,7 @@ import { getSubFlatEntityMapsByApplicationIdsOrThrow } from 'src/engine/metadata
import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { SCHEMA_SDL_CACHE_DEPENDENCIES } from 'src/engine/api/graphql/workspace-graphql-schema-sdl/constants/schema-sdl-cache-dependencies.constant';
import { WorkspaceCacheStorageService } from 'src/engine/workspace-cache-storage/workspace-cache-storage.service';
import { combineCacheHashes } from 'src/engine/workspace-cache/utils/combine-cache-hashes.util';
import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';
@@ -43,36 +43,27 @@ export class WorkspaceGraphqlSchemaSDLService {
async getOrComputeSchemaSDL(
workspace: FlatWorkspace,
applicationId?: string,
- flatEntityMapsOverride?: ObjectFieldIndexFlatEntityMaps,
): Promise<WorkspaceGraphqlSchemaSDLResult | null> {
if (!isNonEmptyString(workspace.databaseSchema)) {
return null;
}
- const shouldUseStoredSdl = !isDefined(flatEntityMapsOverride);
-
- const { data, hashes } =
+ const {
+ data: {
+ flatObjectMetadataMaps: allFlatObjectMetadataMaps,
+ flatFieldMetadataMaps: allFlatFieldMetadataMaps,
+ flatIndexMaps: allFlatIndexMaps,
+ flatApplicationMaps,
+ },
+ hashes,
+ } =
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMapsWithHashes(
{
workspaceId: workspace.id,
- flatMapsKeys: shouldUseStoredSdl
- ? [...SCHEMA_SDL_CACHE_DEPENDENCIES]
- : isDefined(flatEntityMapsOverride?.flatIndexMaps)
- ? ['flatApplicationMaps']
- : ['flatApplicationMaps', 'flatIndexMaps'],
+ flatMapsKeys: [...SCHEMA_SDL_CACHE_DEPENDENCIES],
},
);
- const { flatApplicationMaps } = data;
- const allFlatObjectMetadataMaps =
- flatEntityMapsOverride?.flatObjectMetadataMaps ??
- data.flatObjectMetadataMaps;
- const allFlatFieldMetadataMaps =
- flatEntityMapsOverride?.flatFieldMetadataMaps ??
- data.flatFieldMetadataMaps;
- const allFlatIndexMaps =
- flatEntityMapsOverride?.flatIndexMaps ?? data.flatIndexMaps;
-
if (!isDefined(allFlatObjectMetadataMaps)) {
throw new FlatEntityMapsException(
'Object metadata collection not found',
@@ -124,52 +115,37 @@ export class WorkspaceGraphqlSchemaSDLService {
}
}
- const metadataCacheHash = shouldUseStoredSdl
- ? combineCacheHashes(hashes, SCHEMA_SDL_CACHE_DEPENDENCIES)
- : undefined;
-
- let sdl = isDefined(metadataCacheHash)
- ? await this.workspaceCacheStorageService.getGraphQLTypeDefs(
- workspace.id,
- metadataCacheHash,
- applicationId,
- )
- : undefined;
- let usedScalarNames = isDefined(metadataCacheHash)
- ? await this.workspaceCacheStorageService.getGraphQLUsedScalarNames(
- workspace.id,
- metadataCacheHash,
- applicationId,
- )
- : undefined;
-
- if (!sdl || !usedScalarNames) {
- const autoGeneratedSchema =
- await this.workspaceGraphQLSchemaGenerator.generateSchema({
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- flatIndexMaps,
- });
-
- usedScalarNames =
- this.scalarsExplorerService.getUsedScalarNames(autoGeneratedSchema);
- sdl = printSchema(autoGeneratedSchema);
-
- if (isDefined(metadataCacheHash)) {
- await this.workspaceCacheStorageService.setGraphQLTypeDefs(
- workspace.id,
- metadataCacheHash,
- sdl,
- applicationId,
- );
- await this.workspaceCacheStorageService.setGraphQLUsedScalarNames(
- workspace.id,
- metadataCacheHash,
- usedScalarNames,
- applicationId,
- );
- }
- }
+ const metadataCacheHash = combineCacheHashes(
+ hashes,
+ SCHEMA_SDL_CACHE_DEPENDENCIES,
+ );
+
+ const [cachedSdl, cachedUsedScalarNames] = await Promise.all([
+ this.workspaceCacheStorageService.getGraphQLTypeDefs(
+ workspace.id,
+ metadataCacheHash,
+ applicationId,
+ ),
+ this.workspaceCacheStorageService.getGraphQLUsedScalarNames(
+ workspace.id,
+ metadataCacheHash,
+ applicationId,
+ ),
+ ]);
+
+ const { sdl, usedScalarNames } =
+ isNonEmptyString(cachedSdl) && isDefined(cachedUsedScalarNames)
+ ? { sdl: cachedSdl, usedScalarNames: cachedUsedScalarNames }
+ : await this.computeAndCacheSchemaSDL({
+ workspaceId: workspace.id,
+ metadataCacheHash,
+ applicationId,
+ schemaGenerationContext: {
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ flatIndexMaps,
+ },
+ });
return {
sdl,
@@ -180,6 +156,44 @@ export class WorkspaceGraphqlSchemaSDLService {
};
}
+ private async computeAndCacheSchemaSDL({
+ workspaceId,
+ metadataCacheHash,
+ applicationId,
+ schemaGenerationContext,
+ }: {
+ workspaceId: string;
+ metadataCacheHash: string;
+ applicationId?: string;
+ schemaGenerationContext: SchemaGenerationContext;
+ }): Promise<{ sdl: string; usedScalarNames: string[] }> {
+ const autoGeneratedSchema =
+ await this.workspaceGraphQLSchemaGenerator.generateSchema(
+ schemaGenerationContext,
+ );
+
+ const usedScalarNames =
+ this.scalarsExplorerService.getUsedScalarNames(autoGeneratedSchema);
+ const sdl = printSchema(autoGeneratedSchema);
+
+ await Promise.all([
+ this.workspaceCacheStorageService.setGraphQLTypeDefs(
+ workspaceId,
+ metadataCacheHash,
+ sdl,
+ applicationId,
+ ),
+ this.workspaceCacheStorageService.setGraphQLUsedScalarNames(
+ workspaceId,
+ metadataCacheHash,
+ usedScalarNames,
+ applicationId,
+ ),
+ ]);
+
+ return { sdl, usedScalarNames };
+ }
+
private reconcileObjectFieldIdsWithFilteredFieldMaps(
flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>,
flatFieldMetadataMaps: FlatEntityMaps<FlatFieldMetadata>,
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-schema.factory.ts b/packages/twenty-server/src/engine/api/graphql/workspace-schema.factory.ts
index bb8d6664bcd..2934e220ef8 100644
--- a/packages/twenty-server/src/engine/api/graphql/workspace-schema.factory.ts
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-schema.factory.ts
@@ -6,7 +6,6 @@ import { gql } from 'graphql-tag';
import { isDefined } from 'twenty-shared/utils';
import { ScalarsExplorerService } from 'src/engine/api/graphql/services/scalars-explorer.service';
-import { type ObjectFieldIndexFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type';
import { WorkspaceGraphqlSchemaSDLService } from 'src/engine/api/graphql/workspace-graphql-schema-sdl/workspace-graphql-schema-sdl.service';
import { workspaceResolverBuilderMethodNames } from 'src/engine/api/graphql/workspace-resolver-builder/factories/factories';
import { WorkspaceResolverFactory } from 'src/engine/api/graphql/workspace-resolver-builder/workspace-resolver.factory';
@@ -24,13 +23,11 @@ export class WorkspaceSchemaFactory {
async createGraphQLSchema(
workspace: FlatWorkspace,
applicationId?: string,
- flatEntityMapsOverride?: ObjectFieldIndexFlatEntityMaps,
): Promise<GraphQLSchema> {
const schemaSDLResult =
await this.workspaceGraphqlSchemaSDLService.getOrComputeSchemaSDL(
workspace,
applicationId,
- flatEntityMapsOverride,
);
if (!isDefined(schemaSDLResult)) {
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts
index 7081951c79f..b2c1df0aad1 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts
@@ -40,6 +40,12 @@ import {
LogicFunctionTriggerJob,
type LogicFunctionTriggerJobData,
} from 'src/engine/core-modules/logic-function/logic-function-trigger/jobs/logic-function-trigger.job';
+import {
+ WARM_UP_APPLICATION_LOGIC_FUNCTIONS_JOB_NAME,
+ WARM_UP_APPLICATION_LOGIC_FUNCTIONS_JOB_OPTIONS,
+ type WarmUpApplicationLogicFunctionsJobData,
+} from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/jobs/warm-up-application-logic-functions.job-constants';
+import { findLogicFunctionUniversalIdentifiersToWarmUp } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/utils/find-logic-function-universal-identifiers-to-warm-up.util';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
@@ -64,6 +70,8 @@ export class ApplicationInstallService {
private readonly cacheLockService: CacheLockService,
@InjectMessageQueue(MessageQueue.logicFunctionQueue)
private readonly messageQueueService: MessageQueueService,
+ @InjectMessageQueue(MessageQueue.workspaceQueue)
+ private readonly workspaceQueueService: MessageQueueService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly metricsService: MetricsService,
) {}
@@ -359,14 +367,15 @@ export class ApplicationInstallService {
universalIdentifier,
});
- await this.applicationManifestApplyService.applyManifestToWorkspace({
- workspaceId: params.workspaceId,
- manifest: resolvedPackage.manifest,
- applicationRegistrationId: appRegistration.id,
- application,
- forceSdkClientGeneration: true,
- persistVersion: false,
- });
+ const { workspaceMigration } =
+ await this.applicationManifestApplyService.applyManifestToWorkspace({
+ workspaceId: params.workspaceId,
+ manifest: resolvedPackage.manifest,
+ applicationRegistrationId: appRegistration.id,
+ application,
+ forceSdkClientGeneration: true,
+ persistVersion: false,
+ });
const isPostInstallHookSynchronous =
resolvedPackage.manifest.application.postInstallLogicFunction
@@ -406,6 +415,13 @@ export class ApplicationInstallService {
},
);
+ await this.enqueueLogicFunctionWarmUp({
+ workspaceId: params.workspaceId,
+ applicationId: application.id,
+ logicFunctionUniversalIdentifiers:
+ findLogicFunctionUniversalIdentifiersToWarmUp(workspaceMigration),
+ });
+
this.logger.log(
`Successfully installed app ${universalIdentifier} v${resolvedPackage.packageJson.version ?? 'unknown'}`,
);
@@ -517,6 +533,28 @@ export class ApplicationInstallService {
}
}
+ private async enqueueLogicFunctionWarmUp(
+ data: WarmUpApplicationLogicFunctionsJobData,
+ ): Promise<void> {
+ if (data.logicFunctionUniversalIdentifiers.length === 0) {
+ return;
+ }
+
+ try {
+ await this.workspaceQueueService.add<WarmUpApplicationLogicFunctionsJobData>(
+ WARM_UP_APPLICATION_LOGIC_FUNCTIONS_JOB_NAME,
+ data,
+ WARM_UP_APPLICATION_LOGIC_FUNCTIONS_JOB_OPTIONS,
+ );
+ } catch (error) {
+ this.logger.error(
+ `Failed to enqueue prebuilt warm-up for application ${data.applicationId} in workspace ${data.workspaceId}: ` +
+ `${error instanceof Error ? error.message : String(error)}`,
+ error instanceof Error ? error.stack : undefined,
+ );
+ }
+ }
+
private async markInstallCompleted({
applicationId,
version,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda.driver.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda.driver.ts
index 79972f7d00c..e03f52dcf21 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda.driver.ts
@@ -67,6 +67,8 @@ export class LambdaDriver implements LogicFunctionDriver {
this.toolFunctions,
options.logicFunctionResourceService,
options.sdkClientArchiveService,
+ options.cacheLockService,
+ options.workspaceCacheService,
);
this.executorManager = new LambdaExecutorManagerService(
options,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/__tests__/lambda-layer-manager.service.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/__tests__/lambda-layer-manager.service.spec.ts
new file mode 100644
index 00000000000..9ea91ded841
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/__tests__/lambda-layer-manager.service.spec.ts
@@ -0,0 +1,208 @@
+import {
+ DeleteLayerVersionCommand,
+ ListLayerVersionsCommand,
+ PublishLayerVersionCommand,
+} from '@aws-sdk/client-lambda';
+
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { type CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import { type LambdaAwsClientService } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-aws-client.service';
+import { LambdaLayerManagerService } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-layer-manager.service';
+import { type LambdaToolFunctionsService } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-tool-functions.service';
+import { type LogicFunctionResourceService } from 'src/engine/core-modules/logic-function/logic-function-resource/logic-function-resource.service';
+import { type SdkClientArchiveService } from 'src/engine/core-modules/sdk-client/sdk-client-archive.service';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+jest.mock(
+ 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/utils/reprefix-lambda-zip-entries.util',
+ () => ({
+ reprefixLambdaZipEntries: jest.fn(async ({ sourceBuffer }) => sourceBuffer),
+ }),
+);
+
+const WORKSPACE_ID = '20202020-0000-0000-0000-000000000001';
+const APPLICATION_ID = '20202020-0000-0000-0000-000000000002';
+const APPLICATION_UNIVERSAL_IDENTIFIER = 'test-app';
+
+describe('LambdaLayerManagerService.ensureSdkLayer', () => {
+ let flatApplication: FlatApplication;
+ let publishedVersion: number;
+ let liveVersions: number[];
+ let publishInFlight: Promise<void>;
+ let resolvePublish: () => void;
+
+ const send = jest.fn();
+ const awsClient = {
+ getLambdaClient: async () => ({ send }),
+ getExistingLayerArn: jest.fn(),
+ };
+ const sdkClientArchiveService = {
+ downloadArchiveBuffer: jest.fn(async () => Buffer.from('zip')),
+ markSdkLayerFresh: jest.fn(async () => {
+ flatApplication = { ...flatApplication, isSdkLayerStale: false };
+ }),
+ };
+ const workspaceCacheService = {
+ getOrRecompute: jest.fn(async () => ({
+ flatApplicationMaps: { byId: { [APPLICATION_ID]: flatApplication } },
+ })),
+ };
+ const lockChains = new Map<string, Promise<unknown>>();
+ const cacheLockService = {
+ withLock: jest.fn(async <T>(fn: () => Promise<T>, key: string) => {
+ const previous = lockChains.get(key) ?? Promise.resolve();
+ const run = previous.then(fn, fn);
+
+ lockChains.set(
+ key,
+ run.catch(() => undefined),
+ );
+
+ return run;
+ }),
+ };
+
+ const buildService = () =>
+ new LambdaLayerManagerService(
+ { layerBucket: 'bucket', resourceNamespace: 'test' },
+ awsClient as unknown as LambdaAwsClientService,
+ {} as LambdaToolFunctionsService,
+ {} as LogicFunctionResourceService,
+ sdkClientArchiveService as unknown as SdkClientArchiveService,
+ cacheLockService as unknown as CacheLockService,
+ workspaceCacheService as unknown as WorkspaceCacheService,
+ );
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ lockChains.clear();
+ awsClient.getExistingLayerArn.mockImplementation(
+ async (layerName: string) =>
+ liveVersions.length > 0
+ ? `arn:${layerName}:${liveVersions[liveVersions.length - 1]}`
+ : undefined,
+ );
+ flatApplication = {
+ id: APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ isSdkLayerStale: true,
+ } as FlatApplication;
+ publishedVersion = 0;
+ liveVersions = [1];
+ publishInFlight = new Promise((resolve) => {
+ resolvePublish = resolve;
+ });
+
+ send.mockImplementation(async (command) => {
+ if (command instanceof ListLayerVersionsCommand) {
+ return {
+ LayerVersions: liveVersions.map((version) => ({ Version: version })),
+ };
+ }
+
+ if (command instanceof DeleteLayerVersionCommand) {
+ liveVersions = liveVersions.filter(
+ (version) => version !== command.input.VersionNumber,
+ );
+
+ return {};
+ }
+
+ if (command instanceof PublishLayerVersionCommand) {
+ await publishInFlight;
+ publishedVersion += 1;
+ liveVersions = [...liveVersions, publishedVersion + 1];
+
+ return {
+ LayerVersionArn: `arn:${command.input.LayerName}:${publishedVersion + 1}`,
+ };
+ }
+
+ throw new Error(`Unexpected command ${command.constructor.name}`);
+ });
+ });
+
+ it('returns the existing layer without touching AWS when the layer is fresh', async () => {
+ flatApplication = { ...flatApplication, isSdkLayerStale: false };
+
+ const arn = await buildService().ensureSdkLayer({
+ flatApplication,
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(arn).toMatch(/:1$/);
+ expect(send).not.toHaveBeenCalled();
+ expect(cacheLockService.withLock).not.toHaveBeenCalled();
+ });
+
+ it('creates the dependencies layer once when two functions of the application build concurrently', async () => {
+ const service = buildService();
+ let depsLayerExists = false;
+ let finishCreation: () => void = () => undefined;
+ const creationInFlight = new Promise<void>((resolve) => {
+ finishCreation = resolve;
+ });
+ const createDepsLayer = jest
+ .spyOn(
+ service as unknown as { createDepsLayer: () => Promise<void> },
+ 'createDepsLayer',
+ )
+ .mockImplementation(async () => {
+ await creationInFlight;
+ depsLayerExists = true;
+ });
+
+ awsClient.getExistingLayerArn.mockImplementation(
+ async (layerName: string) =>
+ depsLayerExists ? `arn:${layerName}:1` : undefined,
+ );
+
+ const context = {
+ flatApplication,
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ };
+
+ const firstBuild = service.ensureDepsLayer(context);
+ const secondBuild = service.ensureDepsLayer(context);
+
+ finishCreation();
+
+ const [firstArn, secondArn] = await Promise.all([firstBuild, secondBuild]);
+
+ expect(firstArn).toBe(secondArn);
+ expect(createDepsLayer).toHaveBeenCalledTimes(1);
+ });
+
+ it('publishes the stale layer once when two functions of the application build concurrently', async () => {
+ const service = buildService();
+ const context = {
+ flatApplication,
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ };
+
+ const firstBuild = service.ensureSdkLayer(context);
+ const secondBuild = service.ensureSdkLayer(context);
+
+ resolvePublish();
+
+ const [firstArn, secondArn] = await Promise.all([firstBuild, secondBuild]);
+
+ expect(firstArn).toBe(secondArn);
+ expect(
+ send.mock.calls.filter(
+ ([command]) => command instanceof PublishLayerVersionCommand,
+ ),
+ ).toHaveLength(1);
+ expect(
+ send.mock.calls.filter(
+ ([command]) => command instanceof DeleteLayerVersionCommand,
+ ),
+ ).toHaveLength(1);
+ expect(sdkClientArchiveService.markSdkLayerFresh).toHaveBeenCalledTimes(1);
+ expect(cacheLockService.withLock).toHaveBeenCalledTimes(2);
+ expect(cacheLockService.withLock.mock.calls[0][1]).toBe(
+ cacheLockService.withLock.mock.calls[1][1],
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-executor-manager.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-executor-manager.service.ts
index 067240f7aff..d88cffad511 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-executor-manager.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-executor-manager.service.ts
@@ -16,7 +16,6 @@ import { Logger } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
-import { type ObjectFieldIndexFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { type CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
import {
@@ -51,7 +50,6 @@ type ExecutorBuildContext = {
flatLogicFunction: FlatLogicFunction;
flatApplication: FlatApplication;
applicationUniversalIdentifier: string;
- flatEntityMapsOverride?: ObjectFieldIndexFlatEntityMaps;
};
export class LambdaExecutorManagerService {
@@ -308,7 +306,6 @@ export class LambdaExecutorManagerService {
flatLogicFunction,
flatApplication,
applicationUniversalIdentifier,
- flatEntityMapsOverride,
lambdaExecutor,
}: ExecutorBuildContext & {
lambdaExecutor: GetFunctionCommandOutput | undefined;
@@ -345,7 +342,6 @@ export class LambdaExecutorManagerService {
sdkLayerArn = await this.layerManager.ensureSdkLayer({
flatApplication,
applicationUniversalIdentifier,
- flatEntityMapsOverride,
});
} catch (error) {
this.logger.error(
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-layer-manager.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-layer-manager.service.ts
index 301717189d4..160e4f7a515 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-layer-manager.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-layer-manager.service.ts
@@ -11,8 +11,8 @@ import {
import { Logger } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
-import { type ObjectFieldIndexFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { type CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
import { SDK_LAYER_PREFIX_IN_ZIP } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/constants/lambda-driver.constant';
import { type LambdaAwsClientService } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-aws-client.service';
import { type LambdaToolFunctionsService } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-tool-functions.service';
@@ -23,6 +23,7 @@ import { reprefixLambdaZipEntries } from 'src/engine/core-modules/logic-function
import { TemporaryDirManager } from 'src/engine/core-modules/logic-function/logic-function-drivers/utils/temporary-dir-manager';
import { type LogicFunctionResourceService } from 'src/engine/core-modules/logic-function/logic-function-resource/logic-function-resource.service';
import { type SdkClientArchiveService } from 'src/engine/core-modules/sdk-client/sdk-client-archive.service';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { LogicFunctionRuntime } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
import {
LogicFunctionException,
@@ -32,7 +33,12 @@ import {
type LayerAppContext = {
flatApplication: FlatApplication;
applicationUniversalIdentifier: string;
- flatEntityMapsOverride?: ObjectFieldIndexFlatEntityMaps;
+};
+
+const LAYER_LOCK_OPTIONS = {
+ ttl: 120_000,
+ ms: 500,
+ maxRetries: 240,
};
export class LambdaLayerManagerService {
@@ -47,6 +53,8 @@ export class LambdaLayerManagerService {
private readonly toolFunctions: LambdaToolFunctionsService,
private readonly logicFunctionResourceService: LogicFunctionResourceService,
private readonly sdkClientArchiveService: SdkClientArchiveService,
+ private readonly cacheLockService: CacheLockService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
) {}
async ensureDepsLayer(context: LayerAppContext): Promise<string> {
@@ -61,38 +69,104 @@ export class LambdaLayerManagerService {
return existingArn;
}
- await this.createDepsLayer({ ...context, layerName });
+ return this.cacheLockService.withLock(
+ async () => {
+ const arnCreatedWhileWaiting =
+ await this.awsClient.getExistingLayerArn(layerName);
- const newArn = await this.awsClient.getExistingLayerArn(layerName);
+ if (isDefined(arnCreatedWhileWaiting)) {
+ return arnCreatedWhileWaiting;
+ }
- if (!isDefined(newArn)) {
- throw new Error(
- `Layer '${layerName}' was not created by the yarn install Lambda`,
- );
- }
+ await this.createDepsLayer({ ...context, layerName });
+
+ const newArn = await this.awsClient.getExistingLayerArn(layerName);
- return newArn;
+ if (!isDefined(newArn)) {
+ throw new Error(
+ `Layer '${layerName}' was not created by the yarn install Lambda`,
+ );
+ }
+
+ return newArn;
+ },
+ `lambda-deps-layer:${layerName}`,
+ LAYER_LOCK_OPTIONS,
+ );
}
async ensureSdkLayer(context: LayerAppContext): Promise<string> {
- const {
- flatApplication,
- applicationUniversalIdentifier,
- flatEntityMapsOverride,
- } = context;
+ const { flatApplication, applicationUniversalIdentifier } = context;
const layerName = getLambdaSdkLayerName({
workspaceId: flatApplication.workspaceId,
applicationUniversalIdentifier,
});
- if (!flatApplication.isSdkLayerStale) {
- const existingArn = await this.awsClient.getExistingLayerArn(layerName);
+ const existingArn = await this.findFreshSdkLayerArn({
+ flatApplication,
+ layerName,
+ });
- if (isDefined(existingArn)) {
- return existingArn;
- }
+ if (isDefined(existingArn)) {
+ return existingArn;
}
+ return this.cacheLockService.withLock(
+ async () => {
+ const refreshedFlatApplication =
+ await this.refreshFlatApplication(flatApplication);
+
+ const arnPublishedWhileWaiting = await this.findFreshSdkLayerArn({
+ flatApplication: refreshedFlatApplication,
+ layerName,
+ });
+
+ if (isDefined(arnPublishedWhileWaiting)) {
+ return arnPublishedWhileWaiting;
+ }
+
+ return this.rebuildSdkLayer({
+ flatApplication: refreshedFlatApplication,
+ applicationUniversalIdentifier,
+ layerName,
+ });
+ },
+ `lambda-sdk-layer:${layerName}`,
+ LAYER_LOCK_OPTIONS,
+ );
+ }
+
+ private async findFreshSdkLayerArn({
+ flatApplication,
+ layerName,
+ }: {
+ flatApplication: FlatApplication;
+ layerName: string;
+ }): Promise<string | undefined> {
+ if (flatApplication.isSdkLayerStale) {
+ return undefined;
+ }
+
+ return this.awsClient.getExistingLayerArn(layerName);
+ }
+
+ private async refreshFlatApplication(
+ flatApplication: FlatApplication,
+ ): Promise<FlatApplication> {
+ const { flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(
+ flatApplication.workspaceId,
+ ['flatApplicationMaps'],
+ );
+
+ return flatApplicationMaps.byId[flatApplication.id] ?? flatApplication;
+ }
+
+ private async rebuildSdkLayer({
+ flatApplication,
+ applicationUniversalIdentifier,
+ layerName,
+ }: LayerAppContext & { layerName: string }): Promise<string> {
await this.deleteAllLayerVersions(layerName);
const sdkArchiveBuffer =
@@ -100,7 +174,6 @@ export class LambdaLayerManagerService {
workspaceId: flatApplication.workspaceId,
applicationId: flatApplication.id,
applicationUniversalIdentifier,
- flatEntityMapsOverride,
});
const zipBuffer = await reprefixLambdaZipEntries({
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface.ts
index 994c67b9188..a4da7c3e760 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface.ts
@@ -1,6 +1,5 @@
import { type LogicFunctionExecutionContext } from 'twenty-shared/logic-function';
-import { type ObjectFieldIndexFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { type LogicFunctionExecutionStatus } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-execution-result.dto';
import { type LogicFunctionExecutionMode } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
@@ -36,7 +35,6 @@ export type LogicFunctionInstallPrebuiltBundleParams = {
flatLogicFunction: FlatLogicFunction;
flatApplication: FlatApplication;
applicationUniversalIdentifier: string;
- flatEntityMapsOverride?: ObjectFieldIndexFlatEntityMaps;
};
export type LogicFunctionTranspileParams = {
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.module.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.module.ts
index b65b1947dd9..37105cf5727 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.module.ts
@@ -16,6 +16,7 @@ import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.mod
import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { SubscriptionsModule } from 'src/engine/subscriptions/subscriptions.module';
+import { LogicFunctionPrebuiltWarmUpModule } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
@@ -27,6 +28,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
SecretEncryptionModule,
SubscriptionsModule,
WorkspaceCacheModule,
+ LogicFunctionPrebuiltWarmUpModule,
BillingModule,
FeatureFlagModule,
WorkspaceDomainsModule,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
index 58293abdbbc..1b9d88cfa71 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
@@ -60,6 +60,7 @@ import { FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/ty
import { SubscriptionChannel } from 'src/engine/subscriptions/enums/subscription-channel.enum';
import { SubscriptionService } from 'src/engine/subscriptions/subscription.service';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { LogicFunctionPrebuiltWarmUpService } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service';
import { cleanServerUrl } from 'src/utils/clean-server-url';
export class LogicFunctionExecutionException extends Error {
@@ -83,6 +84,7 @@ export class LogicFunctionExecutorService {
constructor(
private readonly logicFunctionDriverFactory: LogicFunctionDriverFactory,
+ private readonly logicFunctionPrebuiltWarmUpService: LogicFunctionPrebuiltWarmUpService,
private readonly throttlerService: ThrottlerService,
private readonly twentyConfigService: TwentyConfigService,
private readonly workspaceCacheService: WorkspaceCacheService,
@@ -160,11 +162,12 @@ export class LogicFunctionExecutorService {
});
if (effectiveExecutionMode === LogicFunctionExecutionMode.PREBUILT) {
- await this.ensurePrebuiltBundleInstalled({
- driver,
- flatLogicFunction,
- flatApplication,
- });
+ await this.logicFunctionPrebuiltWarmUpService.ensurePrebuiltBundleInstalled(
+ {
+ flatLogicFunction,
+ flatApplication,
+ },
+ );
}
let resultLogicFunction: LogicFunctionExecuteResult;
@@ -229,46 +232,6 @@ export class LogicFunctionExecutorService {
return flatLogicFunction.executionMode ?? LogicFunctionExecutionMode.LIVE;
}
- private async ensurePrebuiltBundleInstalled({
- driver,
- flatLogicFunction,
- flatApplication,
- }: {
- driver: ReturnType<LogicFunctionDriverFactory['getCurrentDriver']>;
- flatLogicFunction: FlatLogicFunction;
- flatApplication: FlatApplication;
- }): Promise<void> {
- const installedChecksum =
- await driver.getInstalledBundleChecksum(flatLogicFunction);
-
- if (installedChecksum === flatLogicFunction.checksum) {
- return;
- }
-
- try {
- await driver.installPrebuiltBundle({
- flatLogicFunction,
- flatApplication,
- applicationUniversalIdentifier: flatApplication.universalIdentifier,
- });
- } catch (error) {
- const cause = error instanceof Error ? error.message : String(error);
-
- this.logger.error(
- `Failed to install prebuilt bundle on-demand for function '${flatLogicFunction.id}' ` +
- `(installed=${installedChecksum ?? 'none'}, expected=${flatLogicFunction.checksum ?? 'none'}): ` +
- `${cause}`,
- error instanceof Error ? error.stack : undefined,
- );
- throw new LogicFunctionException(
- `Failed to install the prebuilt bundle for function '${flatLogicFunction.id}' ` +
- `(installed=${installedChecksum ?? 'none'}, expected=${flatLogicFunction.checksum ?? 'none'}): ` +
- `${cause}`,
- LogicFunctionExceptionCode.LOGIC_FUNCTION_PREBUILT_BUNDLE_NOT_INSTALLED,
- );
- }
- }
-
async transpile(
params: LogicFunctionTranspileParams,
): Promise<LogicFunctionTranspileResult> {
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/__tests__/logic-function-prebuilt-warm-up.service.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/__tests__/logic-function-prebuilt-warm-up.service.spec.ts
new file mode 100644
index 00000000000..a174fa04c1e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/__tests__/logic-function-prebuilt-warm-up.service.spec.ts
@@ -0,0 +1,251 @@
+import { Test, type TestingModule } from '@nestjs/testing';
+
+import { LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN } from 'src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-driver-factory.token';
+import { LogicFunctionPrebuiltWarmUpService } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service';
+import { LogicFunctionExecutionMode } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
+import { 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-000000000002';
+const OTHER_APPLICATION_ID = '20202020-0000-0000-0000-000000000003';
+
+const flatApplication = {
+ id: APPLICATION_ID,
+ universalIdentifier: 'test-app',
+};
+
+const ALL_UNIVERSAL_IDENTIFIERS = [
+ 'universal-ready-1',
+ 'universal-ready-2',
+ 'universal-live',
+ 'universal-not-built',
+ 'universal-other-app',
+ 'universal-installed',
+ 'universal-outdated',
+ 'universal-failing',
+ 'universal-unknown',
+];
+
+const buildFlatLogicFunction = (overrides: {
+ id: string;
+ applicationId?: string;
+ checksum?: string | null;
+ executionMode?: LogicFunctionExecutionMode;
+ isBuildUpToDate?: boolean;
+}) => ({
+ universalIdentifier: `universal-${overrides.id}`,
+ applicationId: APPLICATION_ID,
+ checksum: 'checksum-new',
+ executionMode: LogicFunctionExecutionMode.PREBUILT,
+ isBuildUpToDate: true,
+ ...overrides,
+});
+
+describe('LogicFunctionPrebuiltWarmUpService', () => {
+ let service: LogicFunctionPrebuiltWarmUpService;
+
+ const workspaceCacheService = { getOrRecompute: jest.fn() };
+ const driver = {
+ getInstalledBundleChecksum: jest.fn(),
+ installPrebuiltBundle: jest.fn(),
+ };
+ const logicFunctionDriverFactory = { getCurrentDriver: () => driver };
+
+ const setFlatLogicFunctions = (
+ flatLogicFunctions: ReturnType<typeof buildFlatLogicFunction>[],
+ options: { withApplication?: boolean } = {},
+ ) => {
+ workspaceCacheService.getOrRecompute.mockResolvedValue({
+ flatApplicationMaps: {
+ byId:
+ options.withApplication === false
+ ? {}
+ : { [APPLICATION_ID]: flatApplication },
+ },
+ flatLogicFunctionMaps: {
+ byUniversalIdentifier: Object.fromEntries(
+ flatLogicFunctions.map((flatLogicFunction) => [
+ flatLogicFunction.universalIdentifier,
+ flatLogicFunction,
+ ]),
+ ),
+ universalIdentifiersByApplicationId: {
+ [APPLICATION_ID]: flatLogicFunctions
+ .filter(
+ (flatLogicFunction) =>
+ flatLogicFunction.applicationId === APPLICATION_ID,
+ )
+ .map((flatLogicFunction) => flatLogicFunction.universalIdentifier),
+ },
+ },
+ });
+ };
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+ driver.getInstalledBundleChecksum.mockResolvedValue(null);
+ driver.installPrebuiltBundle.mockResolvedValue(undefined);
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ LogicFunctionPrebuiltWarmUpService,
+ { provide: WorkspaceCacheService, useValue: workspaceCacheService },
+ {
+ provide: LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN,
+ useValue: logicFunctionDriverFactory,
+ },
+ ],
+ }).compile();
+
+ service = module.get(LogicFunctionPrebuiltWarmUpService);
+ });
+
+ it('installs the prebuilt bundle of the listed ready functions of the application', async () => {
+ setFlatLogicFunctions([
+ buildFlatLogicFunction({ id: 'ready-1' }),
+ buildFlatLogicFunction({ id: 'ready-2' }),
+ buildFlatLogicFunction({
+ id: 'live',
+ executionMode: LogicFunctionExecutionMode.LIVE,
+ }),
+ buildFlatLogicFunction({ id: 'not-built', isBuildUpToDate: false }),
+ buildFlatLogicFunction({
+ id: 'other-app',
+ applicationId: OTHER_APPLICATION_ID,
+ }),
+ ]);
+
+ await service.warmUpApplicationLogicFunctions({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION_ID,
+ logicFunctionUniversalIdentifiers: ALL_UNIVERSAL_IDENTIFIERS,
+ });
+
+ expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(2);
+ expect(
+ driver.installPrebuiltBundle.mock.calls.map(
+ ([params]) => params.flatLogicFunction.id,
+ ),
+ ).toEqual(['ready-1', 'ready-2']);
+ expect(driver.installPrebuiltBundle).toHaveBeenCalledWith(
+ expect.objectContaining({
+ flatApplication,
+ applicationUniversalIdentifier: 'test-app',
+ }),
+ );
+ });
+
+ it('skips functions whose installed bundle already matches the checksum', async () => {
+ setFlatLogicFunctions([
+ buildFlatLogicFunction({ id: 'installed', checksum: 'checksum-same' }),
+ buildFlatLogicFunction({ id: 'outdated', checksum: 'checksum-new' }),
+ ]);
+ driver.getInstalledBundleChecksum.mockImplementation(
+ async (flatLogicFunction: { id: string }) =>
+ flatLogicFunction.id === 'installed' ? 'checksum-same' : 'old',
+ );
+
+ await service.warmUpApplicationLogicFunctions({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION_ID,
+ logicFunctionUniversalIdentifiers: ALL_UNIVERSAL_IDENTIFIERS,
+ });
+
+ expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(1);
+ expect(driver.installPrebuiltBundle).toHaveBeenCalledWith(
+ expect.objectContaining({
+ flatLogicFunction: expect.objectContaining({ id: 'outdated' }),
+ }),
+ );
+ });
+
+ it('only touches the listed functions', async () => {
+ setFlatLogicFunctions([
+ buildFlatLogicFunction({ id: 'ready-1' }),
+ buildFlatLogicFunction({ id: 'ready-2' }),
+ ]);
+
+ await service.warmUpApplicationLogicFunctions({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION_ID,
+ logicFunctionUniversalIdentifiers: ['universal-ready-2'],
+ });
+
+ expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(1);
+ expect(driver.installPrebuiltBundle).toHaveBeenCalledWith(
+ expect.objectContaining({
+ flatLogicFunction: expect.objectContaining({ id: 'ready-2' }),
+ }),
+ );
+ });
+
+ it('builds the functions in chunks of ten', async () => {
+ const flatLogicFunctions = Array.from({ length: 15 }, (_, index) =>
+ buildFlatLogicFunction({ id: `function-${index}` }),
+ );
+
+ setFlatLogicFunctions(flatLogicFunctions);
+
+ let inFlight = 0;
+ let maxInFlight = 0;
+
+ driver.installPrebuiltBundle.mockImplementation(async () => {
+ inFlight += 1;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await Promise.resolve();
+ inFlight -= 1;
+ });
+
+ await service.warmUpApplicationLogicFunctions({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION_ID,
+ logicFunctionUniversalIdentifiers: flatLogicFunctions.map(
+ (flatLogicFunction) => flatLogicFunction.universalIdentifier,
+ ),
+ });
+
+ expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(15);
+ expect(maxInFlight).toBe(10);
+ });
+
+ it('does nothing when the application is no longer installed', async () => {
+ setFlatLogicFunctions([buildFlatLogicFunction({ id: 'ready-1' })], {
+ withApplication: false,
+ });
+
+ await service.warmUpApplicationLogicFunctions({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION_ID,
+ logicFunctionUniversalIdentifiers: ALL_UNIVERSAL_IDENTIFIERS,
+ });
+
+ expect(driver.installPrebuiltBundle).not.toHaveBeenCalled();
+ });
+
+ it('keeps installing the other functions and throws when one install fails', async () => {
+ setFlatLogicFunctions([
+ buildFlatLogicFunction({ id: 'ready-1' }),
+ buildFlatLogicFunction({ id: 'failing' }),
+ buildFlatLogicFunction({ id: 'ready-2' }),
+ ]);
+ driver.installPrebuiltBundle.mockImplementation(
+ async ({ flatLogicFunction }: { flatLogicFunction: { id: string } }) => {
+ if (flatLogicFunction.id === 'failing') {
+ throw new Error('lambda unavailable');
+ }
+ },
+ );
+
+ await expect(
+ service.warmUpApplicationLogicFunctions({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION_ID,
+ logicFunctionUniversalIdentifiers: ALL_UNIVERSAL_IDENTIFIERS,
+ }),
+ ).rejects.toThrow(
+ /Failed to warm up 1 of 3 prebuilt logic functions .*: failing: Failed to install the prebuilt bundle for function 'failing'/,
+ );
+
+ expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/jobs/warm-up-application-logic-functions.job-constants.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/jobs/warm-up-application-logic-functions.job-constants.ts
new file mode 100644
index 00000000000..f700735e891
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/jobs/warm-up-application-logic-functions.job-constants.ts
@@ -0,0 +1,16 @@
+import { type QueueJobOptions } from 'src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface';
+
+export const WARM_UP_APPLICATION_LOGIC_FUNCTIONS_JOB_NAME =
+ 'WarmUpApplicationLogicFunctionsJob';
+
+export const WARM_UP_APPLICATION_LOGIC_FUNCTIONS_JOB_OPTIONS: QueueJobOptions =
+ {
+ retryLimit: 1,
+ backoff: { strategy: 'exponential', initialDelayMilliseconds: 1_000 },
+ };
+
+export type WarmUpApplicationLogicFunctionsJobData = {
+ workspaceId: string;
+ applicationId: string;
+ logicFunctionUniversalIdentifiers: string[];
+};
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/jobs/warm-up-application-logic-functions.job.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/jobs/warm-up-application-logic-functions.job.ts
new file mode 100644
index 00000000000..02984b15a81
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/jobs/warm-up-application-logic-functions.job.ts
@@ -0,0 +1,22 @@
+import { LogicFunctionPrebuiltWarmUpService } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service';
+import {
+ WARM_UP_APPLICATION_LOGIC_FUNCTIONS_JOB_NAME,
+ type WarmUpApplicationLogicFunctionsJobData,
+} from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/jobs/warm-up-application-logic-functions.job-constants';
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+
+@Processor(MessageQueue.workspaceQueue)
+export class WarmUpApplicationLogicFunctionsJob {
+ constructor(
+ private readonly logicFunctionPrebuiltWarmUpService: LogicFunctionPrebuiltWarmUpService,
+ ) {}
+
+ @Process(WARM_UP_APPLICATION_LOGIC_FUNCTIONS_JOB_NAME)
+ async handle(data: WarmUpApplicationLogicFunctionsJobData): Promise<void> {
+ await this.logicFunctionPrebuiltWarmUpService.warmUpApplicationLogicFunctions(
+ data,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.module.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.module.ts
new file mode 100644
index 00000000000..3aae68627b6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.module.ts
@@ -0,0 +1,11 @@
+import { Module } from '@nestjs/common';
+
+import { LogicFunctionPrebuiltWarmUpService } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+
+@Module({
+ imports: [WorkspaceCacheModule],
+ providers: [LogicFunctionPrebuiltWarmUpService],
+ exports: [LogicFunctionPrebuiltWarmUpService],
+})
+export class LogicFunctionPrebuiltWarmUpModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service.ts
new file mode 100644
index 00000000000..a85652e6a32
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service.ts
@@ -0,0 +1,138 @@
+import { Inject, Injectable, Logger } from '@nestjs/common';
+
+import chunk from 'lodash.chunk';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN } from 'src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-driver-factory.token';
+import { type LogicFunctionDriverFactory } from 'src/engine/core-modules/logic-function/logic-function-drivers/logic-function-driver.factory';
+import {
+ LogicFunctionException,
+ LogicFunctionExceptionCode,
+} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+import { isLogicFunctionReadyForPrebuiltInstall } from 'src/engine/metadata-modules/logic-function/utils/is-logic-function-ready-for-prebuilt-install.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const WARM_UP_CHUNK_SIZE = 10;
+
+@Injectable()
+export class LogicFunctionPrebuiltWarmUpService {
+ private readonly logger = new Logger(LogicFunctionPrebuiltWarmUpService.name);
+
+ constructor(
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ @Inject(LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN)
+ private readonly logicFunctionDriverFactory: LogicFunctionDriverFactory,
+ ) {}
+
+ async ensurePrebuiltBundleInstalled({
+ flatLogicFunction,
+ flatApplication,
+ }: {
+ flatLogicFunction: FlatLogicFunction;
+ flatApplication: FlatApplication;
+ }): Promise<void> {
+ const driver = this.logicFunctionDriverFactory.getCurrentDriver();
+ let installedChecksum: string | null = null;
+
+ try {
+ installedChecksum =
+ await driver.getInstalledBundleChecksum(flatLogicFunction);
+
+ if (installedChecksum === flatLogicFunction.checksum) {
+ return;
+ }
+
+ await driver.installPrebuiltBundle({
+ flatLogicFunction,
+ flatApplication,
+ applicationUniversalIdentifier: flatApplication.universalIdentifier,
+ });
+ } catch (error) {
+ const cause = error instanceof Error ? error.message : String(error);
+
+ this.logger.error(
+ `Failed to install prebuilt bundle on-demand for function '${flatLogicFunction.id}' ` +
+ `(installed=${installedChecksum ?? 'none'}, expected=${flatLogicFunction.checksum ?? 'none'}): ` +
+ `${cause}`,
+ error instanceof Error ? error.stack : undefined,
+ );
+ throw new LogicFunctionException(
+ `Failed to install the prebuilt bundle for function '${flatLogicFunction.id}' ` +
+ `(installed=${installedChecksum ?? 'none'}, expected=${flatLogicFunction.checksum ?? 'none'})`,
+ LogicFunctionExceptionCode.LOGIC_FUNCTION_PREBUILT_BUNDLE_NOT_INSTALLED,
+ );
+ }
+ }
+
+ async warmUpApplicationLogicFunctions({
+ workspaceId,
+ applicationId,
+ logicFunctionUniversalIdentifiers,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ logicFunctionUniversalIdentifiers: string[];
+ }): Promise<void> {
+ const { flatLogicFunctionMaps, flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatLogicFunctionMaps',
+ 'flatApplicationMaps',
+ ]);
+
+ const flatApplication = flatApplicationMaps.byId[applicationId];
+
+ if (!isDefined(flatApplication)) {
+ this.logger.warn(
+ `Skipping prebuilt warm-up: application ${applicationId} not found in workspace ${workspaceId}`,
+ );
+
+ return;
+ }
+
+ const flatLogicFunctions = logicFunctionUniversalIdentifiers
+ .map(
+ (universalIdentifier) =>
+ flatLogicFunctionMaps.byUniversalIdentifier[universalIdentifier],
+ )
+ .filter(isDefined)
+ .filter(
+ (flatLogicFunction) =>
+ flatLogicFunction.applicationId === applicationId &&
+ isLogicFunctionReadyForPrebuiltInstall(flatLogicFunction),
+ );
+
+ const failures: string[] = [];
+
+ for (const flatLogicFunctionsChunk of chunk(
+ flatLogicFunctions,
+ WARM_UP_CHUNK_SIZE,
+ )) {
+ const results = await Promise.allSettled(
+ flatLogicFunctionsChunk.map((flatLogicFunction) =>
+ this.ensurePrebuiltBundleInstalled({
+ flatLogicFunction,
+ flatApplication,
+ }),
+ ),
+ );
+
+ results.forEach((result, index) => {
+ if (result.status === 'rejected') {
+ failures.push(
+ `${flatLogicFunctionsChunk[index].id}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,
+ );
+ }
+ });
+ }
+
+ if (failures.length > 0) {
+ throw new LogicFunctionException(
+ `Failed to warm up ${failures.length} of ${flatLogicFunctions.length} prebuilt logic functions ` +
+ `for application ${applicationId} in workspace ${workspaceId}: ${failures.join('; ')}`,
+ LogicFunctionExceptionCode.LOGIC_FUNCTION_PREBUILT_BUNDLE_NOT_INSTALLED,
+ );
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/utils/__tests__/find-logic-function-universal-identifiers-to-warm-up.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/utils/__tests__/find-logic-function-universal-identifiers-to-warm-up.util.spec.ts
new file mode 100644
index 00000000000..08f07cbb5a0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/utils/__tests__/find-logic-function-universal-identifiers-to-warm-up.util.spec.ts
@@ -0,0 +1,49 @@
+import { findLogicFunctionUniversalIdentifiersToWarmUp } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/utils/find-logic-function-universal-identifiers-to-warm-up.util';
+import { type WorkspaceMigration } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/workspace-migration.type';
+
+describe('findLogicFunctionUniversalIdentifiersToWarmUp', () => {
+ it('keeps created functions and updates that change the prebuilt bundle state', () => {
+ const workspaceMigration = {
+ applicationUniversalIdentifier: 'test-app',
+ actions: [
+ {
+ type: 'create',
+ metadataName: 'logicFunction',
+ flatEntity: { universalIdentifier: 'created' },
+ },
+ {
+ type: 'update',
+ metadataName: 'logicFunction',
+ universalIdentifier: 'checksum-changed',
+ update: { checksum: 'new' },
+ },
+ {
+ type: 'update',
+ metadataName: 'logicFunction',
+ universalIdentifier: 'became-prebuilt',
+ update: { executionMode: 'PREBUILT' },
+ },
+ {
+ type: 'update',
+ metadataName: 'logicFunction',
+ universalIdentifier: 'description-only',
+ update: { description: 'renamed' },
+ },
+ {
+ type: 'delete',
+ metadataName: 'logicFunction',
+ universalIdentifier: 'deleted',
+ },
+ {
+ type: 'create',
+ metadataName: 'objectMetadata',
+ flatEntity: { universalIdentifier: 'object' },
+ },
+ ],
+ } as unknown as WorkspaceMigration;
+
+ expect(
+ findLogicFunctionUniversalIdentifiersToWarmUp(workspaceMigration),
+ ).toEqual(['created', 'checksum-changed', 'became-prebuilt']);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/utils/find-logic-function-universal-identifiers-to-warm-up.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/utils/find-logic-function-universal-identifiers-to-warm-up.util.ts
new file mode 100644
index 00000000000..a092256ca56
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/utils/find-logic-function-universal-identifiers-to-warm-up.util.ts
@@ -0,0 +1,27 @@
+import { type LogicFunctionPrebuiltStateFields } from 'src/engine/metadata-modules/logic-function/utils/is-logic-function-ready-for-prebuilt-install.util';
+import { type WorkspaceMigration } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/workspace-migration.type';
+
+const LOGIC_FUNCTION_PREBUILT_STATE_KEYS: (keyof LogicFunctionPrebuiltStateFields)[] =
+ ['executionMode', 'isBuildUpToDate', 'checksum'];
+
+export const findLogicFunctionUniversalIdentifiersToWarmUp = (
+ workspaceMigration: WorkspaceMigration,
+): string[] =>
+ workspaceMigration.actions.flatMap((action) => {
+ if (action.metadataName !== 'logicFunction') {
+ return [];
+ }
+
+ if (action.type === 'create') {
+ return [action.flatEntity.universalIdentifier];
+ }
+
+ if (
+ action.type === 'update' &&
+ LOGIC_FUNCTION_PREBUILT_STATE_KEYS.some((key) => key in action.update)
+ ) {
+ return [action.universalIdentifier];
+ }
+
+ return [];
+ });
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts b/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
index be433cd75c3..6b82c7d7db6 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
@@ -49,6 +49,8 @@ import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.ent
import { WorkspaceModule } from 'src/engine/core-modules/workspace/workspace.module';
import { AiAgentMonitorModule } from 'src/engine/metadata-modules/ai/ai-agent-monitor/ai-agent-monitor.module';
import { AiChatModule } from 'src/engine/metadata-modules/ai/ai-chat/ai-chat.module';
+import { LogicFunctionPrebuiltWarmUpModule } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.module';
+import { WarmUpApplicationLogicFunctionsJob } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/jobs/warm-up-application-logic-functions.job';
import { LogicFunctionModule } from 'src/engine/metadata-modules/logic-function/logic-function.module';
import { NavigationMenuItemModule } from 'src/engine/metadata-modules/navigation-menu-item/navigation-menu-item.module';
import { ObjectMetadataModule } from 'src/engine/metadata-modules/object-metadata/object-metadata.module';
@@ -101,6 +103,7 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
AiAgentMonitorModule,
AiChatModule,
LogicFunctionModule,
+ LogicFunctionPrebuiltWarmUpModule,
EnterpriseModule,
EmailingModule,
ApplicationInstallModule,
@@ -135,6 +138,7 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
InstallPreInstalledAppsJob,
TriggerInstallApplicationJob,
TriggerUninstallApplicationJob,
+ WarmUpApplicationLogicFunctionsJob,
],
})
export class JobsModule {
diff --git a/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-archive.service.ts b/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-archive.service.ts
index 37b33f7f7b5..fb5149c97ed 100644
--- a/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-archive.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-archive.service.ts
@@ -6,7 +6,6 @@ import * as fs from 'fs/promises';
import { FileFolder } from 'twenty-shared/types';
import { Repository } from 'typeorm';
-import { type ObjectFieldIndexFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
import {
@@ -66,18 +65,15 @@ export class SdkClientArchiveService {
workspaceId,
applicationId,
applicationUniversalIdentifier,
- flatEntityMapsOverride,
}: {
workspaceId: string;
applicationId: string;
applicationUniversalIdentifier: string;
- flatEntityMapsOverride?: ObjectFieldIndexFlatEntityMaps;
}): Promise<Buffer> {
return this.downloadArchiveBufferOrGenerate({
workspaceId,
applicationId,
applicationUniversalIdentifier,
- flatEntityMapsOverride,
});
}
@@ -138,12 +134,10 @@ export class SdkClientArchiveService {
workspaceId,
applicationId,
applicationUniversalIdentifier,
- flatEntityMapsOverride,
}: {
workspaceId: string;
applicationId: string;
applicationUniversalIdentifier: string;
- flatEntityMapsOverride?: ObjectFieldIndexFlatEntityMaps;
}): Promise<Buffer> {
try {
const stream = await this.fileStorageService.readFile({
@@ -172,7 +166,6 @@ export class SdkClientArchiveService {
applicationId,
applicationUniversalIdentifier,
trigger: 'missing-archive',
- flatEntityMapsOverride,
});
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-generation.service.ts b/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-generation.service.ts
index 195278dc0d5..cd4055f16fb 100644
--- a/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-generation.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-generation.service.ts
@@ -10,7 +10,6 @@ import { replaceCoreClient } from 'twenty-client-sdk/generate';
import { FileFolder } from 'twenty-shared/types';
import { Repository } from 'typeorm';
-import { type ObjectFieldIndexFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type';
import { WorkspaceSchemaFactory } from 'src/engine/api/graphql/workspace-schema.factory';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import {
@@ -109,13 +108,11 @@ export class SdkClientGenerationService {
applicationId,
applicationUniversalIdentifier,
trigger = 'unknown',
- flatEntityMapsOverride,
}: {
workspaceId: string;
applicationId: string;
applicationUniversalIdentifier: string;
trigger?: SdkClientGenerationTrigger;
- flatEntityMapsOverride?: ObjectFieldIndexFlatEntityMaps;
}): Promise<Buffer> {
const generationStart = performance.now();
@@ -128,7 +125,6 @@ export class SdkClientGenerationService {
await this.workspaceSchemaFactory.createGraphQLSchema(
fromWorkspaceEntityToFlat(workspaceEntity),
applicationId,
- flatEntityMapsOverride,
);
const archiveBuffer = await this.generateAndStore({
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type.ts
deleted file mode 100644
index 6ff99568cd5..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
-
-export type ObjectFieldIndexFlatEntityMaps = Pick<
- AllFlatEntityMaps,
- 'flatObjectMetadataMaps' | 'flatFieldMetadataMaps'
-> &
- Partial<Pick<AllFlatEntityMaps, 'flatIndexMaps'>>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/find-object-field-index-flat-entity-maps-in-all-flat-entity-maps.util.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/find-object-field-index-flat-entity-maps-in-all-flat-entity-maps.util.ts
deleted file mode 100644
index 442c0668888..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/find-object-field-index-flat-entity-maps-in-all-flat-entity-maps.util.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-
-import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
-import { type ObjectFieldIndexFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/object-field-index-flat-entity-maps.type';
-
-export const findObjectFieldIndexFlatEntityMapsInAllFlatEntityMaps = (
- allFlatEntityMaps: Partial<AllFlatEntityMaps>,
-): ObjectFieldIndexFlatEntityMaps | undefined => {
- const { flatObjectMetadataMaps, flatFieldMetadataMaps, flatIndexMaps } =
- allFlatEntityMaps;
-
- if (!isDefined(flatObjectMetadataMaps) || !isDefined(flatFieldMetadataMaps)) {
- return undefined;
- }
-
- return { flatObjectMetadataMaps, flatFieldMetadataMaps, flatIndexMaps };
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/should-reinstall-logic-function-prebuilt-bundle.util.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/should-reinstall-logic-function-prebuilt-bundle.util.ts
deleted file mode 100644
index bb048bea6b2..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/should-reinstall-logic-function-prebuilt-bundle.util.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { LogicFunctionExecutionMode } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
-import {
- isLogicFunctionReadyForPrebuiltInstall,
- type LogicFunctionPrebuiltStateFields,
-} from 'src/engine/metadata-modules/logic-function/utils/is-logic-function-ready-for-prebuilt-install.util';
-
-export const shouldReinstallLogicFunctionPrebuiltBundle = ({
- existingLogicFunction,
- newLogicFunction,
-}: {
- existingLogicFunction: LogicFunctionPrebuiltStateFields;
- newLogicFunction: LogicFunctionPrebuiltStateFields;
-}): boolean => {
- if (!isLogicFunctionReadyForPrebuiltInstall(newLogicFunction)) {
- return false;
- }
-
- if (
- existingLogicFunction.executionMode ===
- LogicFunctionExecutionMode.PREBUILT &&
- existingLogicFunction.checksum === newLogicFunction.checksum
- ) {
- return false;
- }
-
- return true;
-};
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/create-logic-function-action-handler.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/create-logic-function-action-handler.service.ts
index 331c1764015..d41a28ecd42 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/create-logic-function-action-handler.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/create-logic-function-action-handler.service.ts
@@ -1,14 +1,9 @@
-import { Inject, Injectable } from '@nestjs/common';
+import { Injectable } from '@nestjs/common';
import { v4 } from 'uuid';
import { WorkspaceMigrationRunnerActionHandler } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface';
-import { LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN } from 'src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-driver-factory.token';
-import { findObjectFieldIndexFlatEntityMapsInAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-object-field-index-flat-entity-maps-in-all-flat-entity-maps.util';
-import { isLogicFunctionReadyForPrebuiltInstall } from 'src/engine/metadata-modules/logic-function/utils/is-logic-function-ready-for-prebuilt-install.util';
-
-import type { LogicFunctionDriverFactory } from 'src/engine/core-modules/logic-function/logic-function-drivers/logic-function-driver.factory';
import { getUniversalFlatEntityEmptyForeignKeyAggregators } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/reset-universal-flat-entity-foreign-key-aggregators.util';
import {
FlatCreateLogicFunctionAction,
@@ -24,13 +19,6 @@ export class CreateLogicFunctionActionHandlerService extends WorkspaceMigrationR
'create',
'logicFunction',
) {
- constructor(
- @Inject(LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN)
- private readonly logicFunctionDriverFactory: LogicFunctionDriverFactory,
- ) {
- super();
- }
-
override async transpileUniversalActionToFlatAction({
action,
flatApplication,
@@ -56,47 +44,13 @@ export class CreateLogicFunctionActionHandlerService extends WorkspaceMigrationR
async executeForMetadata(
context: WorkspaceMigrationActionRunnerContext<FlatCreateLogicFunctionAction>,
): Promise<void> {
- const { flatAction, queryRunner, flatApplication, allFlatEntityMaps } =
- context;
+ const { flatAction, queryRunner } = context;
const { flatEntity: logicFunction } = flatAction;
await this.insertFlatEntitiesInRepository({
queryRunner,
flatEntities: [logicFunction],
});
-
- if (isLogicFunctionReadyForPrebuiltInstall(logicFunction)) {
- const driver = this.logicFunctionDriverFactory.getCurrentDriver();
-
- const installStart = Date.now();
-
- try {
- await driver.installPrebuiltBundle({
- flatLogicFunction: logicFunction,
- flatApplication,
- applicationUniversalIdentifier: flatApplication.universalIdentifier,
- flatEntityMapsOverride:
- findObjectFieldIndexFlatEntityMapsInAllFlatEntityMaps(
- allFlatEntityMaps,
- ),
- });
-
- this.logger.log(
- `[lambda-timing] event=install_prebuilt fnId=${logicFunction.id} ` +
- `reason=app_install install_duration_ms=${Date.now() - installStart}`,
- CreateLogicFunctionActionHandlerService.name,
- );
- } catch (error) {
- this.logger.error(
- `Failed to install prebuilt bundle on app-install for function ${logicFunction.id} ` +
- `after ${Date.now() - installStart}ms: ` +
- `${error instanceof Error ? error.message : String(error)}`,
- CreateLogicFunctionActionHandlerService.name,
- error instanceof Error ? error.stack : undefined,
- );
- throw error;
- }
- }
}
async rollbackForMetadata(
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/update-logic-function-action-handler.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/update-logic-function-action-handler.service.ts
index f7fe2083b40..0aa1faab856 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/update-logic-function-action-handler.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/update-logic-function-action-handler.service.ts
@@ -1,23 +1,16 @@
-import { Inject, Injectable } from '@nestjs/common';
+import { Injectable } from '@nestjs/common';
import { FileFolder } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-import { findObjectFieldIndexFlatEntityMapsInAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-object-field-index-flat-entity-maps-in-all-flat-entity-maps.util';
import { WorkspaceMigrationRunnerActionHandler } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface';
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
-import { LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN } from 'src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-driver-factory.token';
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
-import type { LogicFunctionDriverFactory } from 'src/engine/core-modules/logic-function/logic-function-drivers/logic-function-driver.factory';
import { findFlatEntityByUniversalIdentifierOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier-or-throw.util';
-import {
- LogicFunctionEntity,
- LogicFunctionExecutionMode,
-} from 'src/engine/metadata-modules/logic-function/logic-function.entity';
+import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
-import { shouldReinstallLogicFunctionPrebuiltBundle } from 'src/engine/metadata-modules/logic-function/utils/should-reinstall-logic-function-prebuilt-bundle.util';
import { resolveUniversalUpdateRelationIdentifiersToIds } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/resolve-universal-update-relation-identifiers-to-ids.util';
import {
FlatUpdateLogicFunctionAction,
@@ -33,11 +26,7 @@ export class UpdateLogicFunctionActionHandlerService extends WorkspaceMigrationR
'update',
'logicFunction',
) {
- constructor(
- private readonly fileStorageService: FileStorageService,
- @Inject(LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN)
- private readonly logicFunctionDriverFactory: LogicFunctionDriverFactory,
- ) {
+ constructor(private readonly fileStorageService: FileStorageService) {
super();
}
@@ -99,13 +88,6 @@ export class UpdateLogicFunctionActionHandlerService extends WorkspaceMigrationR
update as Parameters<typeof logicFunctionRepository.update>[1],
);
- await this.installPrebuiltBundleIfNeeded({
- existingLogicFunction,
- update,
- applicationUniversalIdentifier,
- context,
- });
-
if (builtPathChanged) {
const deleteFileStart = performance.now();
@@ -124,75 +106,4 @@ export class UpdateLogicFunctionActionHandlerService extends WorkspaceMigrationR
);
}
}
-
- private async installPrebuiltBundleIfNeeded({
- existingLogicFunction,
- update,
- applicationUniversalIdentifier,
- context,
- }: {
- existingLogicFunction: FlatLogicFunction;
- update: FlatUpdateLogicFunctionAction['update'];
- applicationUniversalIdentifier: string;
- context: WorkspaceMigrationActionRunnerContext<FlatUpdateLogicFunctionAction>;
- }): Promise<void> {
- const newLogicFunction: FlatLogicFunction = {
- ...existingLogicFunction,
- ...update,
- executionMode:
- update.executionMode ?? existingLogicFunction.executionMode,
- isBuildUpToDate:
- update.isBuildUpToDate ?? existingLogicFunction.isBuildUpToDate,
- checksum: update.checksum ?? existingLogicFunction.checksum,
- };
-
- if (
- !shouldReinstallLogicFunctionPrebuiltBundle({
- existingLogicFunction,
- newLogicFunction,
- })
- ) {
- return;
- }
-
- const becamePrebuilt =
- existingLogicFunction.executionMode !==
- LogicFunctionExecutionMode.PREBUILT;
-
- const driver = this.logicFunctionDriverFactory.getCurrentDriver();
-
- const installStart = Date.now();
-
- try {
- await driver.installPrebuiltBundle({
- flatLogicFunction: {
- ...newLogicFunction,
- executionMode: LogicFunctionExecutionMode.PREBUILT,
- isBuildUpToDate: true,
- },
- flatApplication: context.flatApplication,
- applicationUniversalIdentifier,
- flatEntityMapsOverride:
- findObjectFieldIndexFlatEntityMapsInAllFlatEntityMaps(
- context.allFlatEntityMaps,
- ),
- });
-
- this.logger.log(
- `[lambda-timing] event=install_prebuilt fnId=${existingLogicFunction.id} ` +
- `reason=${becamePrebuilt ? 'mode_flip' : 'checksum_change'} ` +
- `install_duration_ms=${Date.now() - installStart}`,
- UpdateLogicFunctionActionHandlerService.name,
- );
- } catch (error) {
- this.logger.error(
- `Failed to install prebuilt bundle for function ${existingLogicFunction.id} ` +
- `after ${Date.now() - installStart}ms: ` +
- `${error instanceof Error ? error.message : String(error)}`,
- UpdateLogicFunctionActionHandlerService.name,
- error instanceof Error ? error.stack : undefined,
- );
- throw error;
- }
- }
}