Skip to content

The open alternative to Salesforce, designed for AI.

Delete logic function Lambdas and SDK layers on workspace deletion (#28813)

Paul Rastoin92c36ae6d5a6
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts b/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts
index 4fe3b19b591..137e0ff3f04 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, Logger } from '@nestjs/common';
+import { Inject, Injectable, Logger } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
@@ -7,6 +7,8 @@ import assert from 'assert';
import { isNonEmptyString } from '@sniptt/guards';
import { msg } from '@lingui/core/macro';
+import chunk from 'lodash.chunk';
+import { setTimeout } from 'node:timers/promises';
import { isAiModelTier, type AiModelTier } from 'twenty-shared/ai';
import {
MAX_ALLOWED_IFRAME_ORIGINS,
@@ -56,6 +58,8 @@ import {
FileWorkspaceFolderDeletionJob,
type FileWorkspaceFolderDeletionJobData,
} from 'src/engine/core-modules/file/jobs/file-workspace-folder-deletion.job';
+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 { LOGIC_FUNCTION_QUEUE_RETRY_BACKOFF } from 'src/engine/core-modules/logic-function/logic-function-trigger/constants/logic-function-queue-retry-backoff.constant';
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';
@@ -195,6 +199,8 @@ export class WorkspaceService {
private readonly sdkClientGenerationService: SdkClientGenerationService,
private readonly postgresAdvisoryLockService: PostgresAdvisoryLockService,
private readonly applicationUninstallService: ApplicationUninstallService,
+ @Inject(LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN)
+ private readonly logicFunctionDriverFactory: LogicFunctionDriverFactory,
private readonly eventLogRetentionService: EventLogRetentionService,
private readonly roleAssignmentValidationService: RoleAssignmentValidationService,
) {}
@@ -790,6 +796,10 @@ export class WorkspaceService {
workspace,
);
+ await this.deleteApplicationRuntimeResourcesBeforeHardDelete(
+ workspace.id,
+ );
+
await this.deleteWorkspaceSyncableMetadataEntities(workspace);
await this.workspaceSchemaService.deleteWorkspaceDBSchema(
@@ -878,6 +888,65 @@ export class WorkspaceService {
);
}
+ private async deleteApplicationRuntimeResourcesBeforeHardDelete(
+ workspaceId: string,
+ ): Promise<void> {
+ // Leaves most of Lambda's 15 req/s control plane quota to live function builds
+ const LOGIC_FUNCTION_DELETIONS_PER_SECOND = 5;
+
+ const logicFunctionDriver =
+ this.logicFunctionDriverFactory.getCurrentDriver();
+
+ const { flatLogicFunctionMaps } =
+ await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
+ {
+ workspaceId,
+ flatMapsKeys: ['flatLogicFunctionMaps'],
+ },
+ );
+
+ const flatLogicFunctions = Object.values(
+ flatLogicFunctionMaps.byUniversalIdentifier,
+ ).filter(isDefined);
+
+ for (const flatLogicFunctionBatch of chunk(
+ flatLogicFunctions,
+ LOGIC_FUNCTION_DELETIONS_PER_SECOND,
+ )) {
+ const batchStartedAt = Date.now();
+
+ await Promise.all(
+ flatLogicFunctionBatch.map(async (flatLogicFunction) => {
+ try {
+ await logicFunctionDriver.delete(flatLogicFunction);
+ } catch (error) {
+ this.logger.warn(
+ `Failed to delete logic function ${flatLogicFunction.id} before hard deleting workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }),
+ );
+
+ await setTimeout(Math.max(0, 1_000 - (Date.now() - batchStartedAt)));
+ }
+
+ const applications =
+ await this.applicationService.findManyApplications(workspaceId);
+
+ for (const application of applications) {
+ try {
+ await logicFunctionDriver.deleteApplicationResources({
+ workspaceId,
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ } catch (error) {
+ this.logger.warn(
+ `Failed to delete runtime resources of application ${application.universalIdentifier} before hard deleting workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+ }
+
private async deleteWorkspaceSyncableMetadataEntities(
workspace: WorkspaceEntity,
): Promise<void> {