Skip to content

The open alternative to Salesforce, designed for AI.

fix(twenty-server): resolve uninstall hook from application column set at sync time (#23908)

nitina2bbb79c0118
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-32/2-32-instance-command-fast-1786959731000-add-uninstall-logic-function-id-to-application.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-32/2-32-instance-command-fast-1786959731000-add-uninstall-logic-function-id-to-application.ts
new file mode 100644
index 00000000000..7d250a17529
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-32/2-32-instance-command-fast-1786959731000-add-uninstall-logic-function-id-to-application.ts
@@ -0,0 +1,21 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.32.0', 1786959731000)
+export class AddUninstallLogicFunctionIdToApplicationFastInstanceCommand
+ implements FastInstanceCommand
+{
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."application" ADD COLUMN IF NOT EXISTS "uninstallLogicFunctionId" uuid',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."application" DROP COLUMN IF EXISTS "uninstallLogicFunctionId"',
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-32/2-32-instance-command-slow-1786959731001-backfill-uninstall-logic-function-id-on-application.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-32/2-32-instance-command-slow-1786959731001-backfill-uninstall-logic-function-id-on-application.ts
new file mode 100644
index 00000000000..b40791c8470
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-32/2-32-instance-command-slow-1786959731001-backfill-uninstall-logic-function-id-on-application.ts
@@ -0,0 +1,45 @@
+import { Logger } from '@nestjs/common';
+
+import { DataSource, QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { SlowInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/slow-instance-command.interface';
+
+// The CASE guard keeps a malformed manifest identifier from aborting the
+// upgrade; unresolvable declarations stay NULL and self-heal on next sync.
+@RegisteredInstanceCommand('2.32.0', 1786959731001, { type: 'slow' })
+export class BackfillUninstallLogicFunctionIdOnApplicationSlowInstanceCommand
+ implements SlowInstanceCommand
+{
+ private readonly logger = new Logger(
+ BackfillUninstallLogicFunctionIdOnApplicationSlowInstanceCommand.name,
+ );
+
+ async runDataMigration(dataSource: DataSource): Promise<void> {
+ const updatedRows: { id: string }[] = await dataSource.query(
+ `UPDATE "core"."application" "application"
+ SET "uninstallLogicFunctionId" = "logicFunction"."id"
+ FROM "core"."applicationRegistration" "applicationRegistration",
+ "core"."logicFunction" "logicFunction"
+ WHERE "applicationRegistration"."id" = "application"."applicationRegistrationId"
+ AND "logicFunction"."workspaceId" = "application"."workspaceId"
+ AND "logicFunction"."applicationId" = "application"."id"
+ AND "logicFunction"."universalIdentifier" = CASE
+ WHEN "applicationRegistration"."manifest" -> 'application' -> 'uninstallLogicFunction' ->> 'universalIdentifier' ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
+ THEN ("applicationRegistration"."manifest" -> 'application' -> 'uninstallLogicFunction' ->> 'universalIdentifier')::uuid
+ END
+ AND "logicFunction"."deletedAt" IS NULL
+ AND "application"."deletedAt" IS NULL
+ RETURNING "application"."id"`,
+ );
+
+ this.logger.log(
+ `core.application: backfilled uninstallLogicFunctionId on ${updatedRows.length} row(s)`,
+ );
+ }
+
+ public async up(_queryRunner: QueryRunner): Promise<void> {}
+
+ // The paired fast command's down drops the column; nothing to undo here.
+ public async down(_queryRunner: QueryRunner): Promise<void> {}
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 3fa3a51b9f0..4788d9e8ef9 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -146,6 +146,8 @@ import { AddPreviousPeriodStartToBillingSubscriptionFastInstanceCommand } from '
import { AddIsDeprecatedToApplicationVariablesFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-31/2-31-instance-command-fast-1786533439000-add-is-deprecated-to-application-variables';
import { EncryptEmptyApplicationVariablesSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-31/2-31-instance-command-slow-1786533438000-encrypt-empty-application-variables';
import { AddWritabilityToMetadataFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-32/2-32-instance-command-fast-1786713600000-add-writability-to-metadata';
+import { AddUninstallLogicFunctionIdToApplicationFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-32/2-32-instance-command-fast-1786959731000-add-uninstall-logic-function-id-to-application';
+import { BackfillUninstallLogicFunctionIdOnApplicationSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-32/2-32-instance-command-slow-1786959731001-backfill-uninstall-logic-function-id-on-application';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -294,4 +296,6 @@ export const INSTANCE_COMMANDS = [
AddIsDeprecatedToApplicationVariablesFastInstanceCommand,
EncryptEmptyApplicationVariablesSlowInstanceCommand,
AddWritabilityToMetadataFastInstanceCommand,
+ AddUninstallLogicFunctionIdToApplicationFastInstanceCommand,
+ BackfillUninstallLogicFunctionIdOnApplicationSlowInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
index d9df8780bc7..d655cfc917d 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
@@ -8,6 +8,7 @@ import { ComputeApplicationManifestAllUniversalFlatEntityMapsService } from 'src
import { buildAllFlatEntityOperationRecordByMetadataNameFromFromTo } from 'src/engine/core-modules/application/application-manifest/utils/build-all-flat-entity-operation-record-by-metadata-name-from-from-to.util';
import { buildFromToAllUniversalFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/build-from-to-all-universal-flat-entity-maps.util';
import { getApplicationSubAllFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/get-application-sub-all-flat-entity-maps.util';
+import { resolveApplicationReferenceIdOrThrow } from 'src/engine/core-modules/application/application-manifest/utils/resolve-application-reference-id-or-throw.util';
import {
ApplicationException,
ApplicationExceptionCode,
@@ -15,7 +16,6 @@ import {
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { LoggerService } from 'src/engine/core-modules/logger/logger.service';
-import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
import { getMetadataFlatEntityMapsKey } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-flat-entity-maps-key.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';
@@ -249,7 +249,7 @@ export class ApplicationManifestMigrationService {
);
if (!dryRun) {
- await this.syncDefaultRoleAndSettingsFrontComponent({
+ await this.syncApplicationReferencesFromManifest({
manifest,
workspaceId,
ownerFlatApplication,
@@ -262,7 +262,7 @@ export class ApplicationManifestMigrationService {
};
}
- private async syncDefaultRoleAndSettingsFrontComponent({
+ private async syncApplicationReferencesFromManifest({
manifest,
workspaceId,
ownerFlatApplication,
@@ -274,58 +274,64 @@ export class ApplicationManifestMigrationService {
const {
flatRoleMaps: refreshedFlatRoleMaps,
flatFrontComponentMaps: refreshedFlatFrontComponentMaps,
+ flatLogicFunctionMaps: refreshedFlatLogicFunctionMaps,
} = await this.workspaceCacheService.getOrRecompute(workspaceId, [
'flatRoleMaps',
'flatFrontComponentMaps',
+ 'flatLogicFunctionMaps',
]);
let defaultRoleId: string | null = null;
for (const role of manifest.roles) {
- const flatRole = findFlatEntityByUniversalIdentifier({
+ const flatRoleId = resolveApplicationReferenceIdOrThrow({
flatEntityMaps: refreshedFlatRoleMaps,
universalIdentifier: role.universalIdentifier,
+ referenceLabel: 'role',
+ exceptionCode: ApplicationExceptionCode.ENTITY_NOT_FOUND,
});
- if (!isDefined(flatRole)) {
- throw new ApplicationException(
- `Failed to resolve role for universalIdentifier ${role.universalIdentifier}`,
- ApplicationExceptionCode.ENTITY_NOT_FOUND,
- );
- }
-
if (
role.universalIdentifier ===
manifest.application.defaultRoleUniversalIdentifier
) {
- defaultRoleId = flatRole.id;
+ defaultRoleId = flatRoleId;
}
}
- let settingsCustomTabFrontComponentId: string | null = null;
-
const settingsFrontComponentUniversalIdentifier =
manifest.application.settingsFrontComponent?.universalIdentifier;
- if (isDefined(settingsFrontComponentUniversalIdentifier)) {
- const flatFrontComponent = findFlatEntityByUniversalIdentifier({
- flatEntityMaps: refreshedFlatFrontComponentMaps,
- universalIdentifier: settingsFrontComponentUniversalIdentifier,
- });
-
- if (!isDefined(flatFrontComponent)) {
- throw new ApplicationException(
- `Failed to resolve front component for settings front component universalIdentifier ${settingsFrontComponentUniversalIdentifier}`,
- ApplicationExceptionCode.ENTITY_NOT_FOUND,
- );
- }
-
- settingsCustomTabFrontComponentId = flatFrontComponent.id;
- }
+ const settingsCustomTabFrontComponentId = isDefined(
+ settingsFrontComponentUniversalIdentifier,
+ )
+ ? resolveApplicationReferenceIdOrThrow({
+ flatEntityMaps: refreshedFlatFrontComponentMaps,
+ universalIdentifier: settingsFrontComponentUniversalIdentifier,
+ referenceLabel: 'settings front component',
+ exceptionCode: ApplicationExceptionCode.ENTITY_NOT_FOUND,
+ })
+ : null;
+
+ const uninstallLogicFunctionUniversalIdentifier =
+ manifest.application.uninstallLogicFunction?.universalIdentifier;
+
+ const uninstallLogicFunctionId = isDefined(
+ uninstallLogicFunctionUniversalIdentifier,
+ )
+ ? resolveApplicationReferenceIdOrThrow({
+ flatEntityMaps: refreshedFlatLogicFunctionMaps,
+ universalIdentifier: uninstallLogicFunctionUniversalIdentifier,
+ referenceLabel: 'uninstall logic function',
+ exceptionCode: ApplicationExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
+ ownerApplicationId: ownerFlatApplication.id,
+ })
+ : null;
await this.applicationService.update(ownerFlatApplication.id, {
workspaceId,
settingsCustomTabFrontComponentId,
+ uninstallLogicFunctionId,
...(isDefined(defaultRoleId) ? { defaultRoleId } : {}),
});
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts
index f3b1cbc7fe5..6baaf177104 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts
@@ -6,7 +6,6 @@ import { ApplicationManifestApplyService } from 'src/engine/core-modules/applica
import { ApplicationManifestMigrationService } from 'src/engine/core-modules/application/application-manifest/application-manifest-migration.service';
import { ComputeApplicationManifestAllUniversalFlatEntityMapsService } from 'src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service';
import { ApplicationSyncService } from 'src/engine/core-modules/application/application-manifest/application-sync.service';
-import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
import { ApplicationRegistrationModule } from 'src/engine/core-modules/application/application-registration/application-registration.module';
import { ApplicationTranslationModule } from 'src/engine/core-modules/application/application-translation/application-translation.module';
import { ApplicationVariableEntityModule } from 'src/engine/core-modules/application/application-variable/application-variable.module';
@@ -22,10 +21,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
@Module({
imports: [
- TypeOrmModule.forFeature([
- ApplicationRegistrationEntity,
- FrontComponentEntity,
- ]),
+ TypeOrmModule.forFeature([FrontComponentEntity]),
ApplicationModule,
ApplicationRegistrationModule,
ApplicationTranslationModule,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
index 03c5167d9a2..c258434a41e 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
@@ -9,7 +9,6 @@ import { isDefined } from 'twenty-shared/utils';
import { PackageJson } from 'type-fest';
import { v4 } from 'uuid';
-import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
import { ApplicationManifestMigrationService } from 'src/engine/core-modules/application/application-manifest/application-manifest-migration.service';
import { enrichApplicationManifestSyncError } from 'src/engine/core-modules/application/application-manifest/utils/enrich-application-manifest-sync-error.util';
@@ -51,8 +50,6 @@ export class ApplicationSyncService {
@Inject(LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN)
private readonly logicFunctionDriverFactory: LogicFunctionDriverFactory,
private readonly logicFunctionExecutorService: LogicFunctionExecutorService,
- @InjectRepository(ApplicationRegistrationEntity)
- private readonly appRegistrationRepository: Repository<ApplicationRegistrationEntity>,
@InjectRepository(FrontComponentEntity)
private readonly frontComponentRepository: Repository<FrontComponentEntity>,
private readonly workspaceEventBroadcaster: WorkspaceEventBroadcaster,
@@ -172,6 +169,7 @@ export class ApplicationSyncService {
defaultRoleId: null,
defaultRole: null,
settingsCustomTabFrontComponentId: null,
+ uninstallLogicFunctionId: null,
canBeUninstalled: true,
autoUpgrade: false,
isSdkLayerStale: false,
@@ -415,7 +413,9 @@ export class ApplicationSyncService {
// migration is applied, the hook's logic function metadata, code, and the
// application's data are gone, so nothing can be executed anymore. It is
// best-effort cleanup: a failure must never prevent the application from
- // being removed.
+ // being removed. uninstallLogicFunctionId is resolved from the manifest at
+ // sync time, so it always points at the installed release, not at whatever
+ // the application registration currently publishes.
private async runUninstallHook({
application,
workspaceId,
@@ -423,46 +423,17 @@ export class ApplicationSyncService {
application: ApplicationEntity;
workspaceId: string;
}): Promise<void> {
- if (!isDefined(application.applicationRegistrationId)) {
+ if (!isDefined(application.uninstallLogicFunctionId)) {
return;
}
try {
- const appRegistration = await this.appRegistrationRepository.findOne({
- where: { id: application.applicationRegistrationId },
- });
-
- const uninstallLogicFunction =
- appRegistration?.manifest?.application.uninstallLogicFunction;
-
- if (!isDefined(uninstallLogicFunction)) {
- return;
- }
-
- const { flatLogicFunctionMaps } =
- await this.workspaceCacheService.getOrRecompute(workspaceId, [
- 'flatLogicFunctionMaps',
- ]);
-
- const flatLogicFunction =
- flatLogicFunctionMaps.byUniversalIdentifier[
- uninstallLogicFunction.universalIdentifier
- ];
-
- if (!isDefined(flatLogicFunction)) {
- this.logger.warn(
- `Uninstall logic function "${uninstallLogicFunction.universalIdentifier}" not found for application "${application.universalIdentifier}"; skipping hook`,
- );
-
- return;
- }
-
this.logger.log(
`Executing uninstall hook for app ${application.universalIdentifier}`,
);
const result = await this.logicFunctionExecutorService.execute({
- logicFunctionId: flatLogicFunction.id,
+ logicFunctionId: application.uninstallLogicFunctionId,
workspaceId,
payload: { version: application.version ?? undefined },
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/resolve-application-reference-id-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/resolve-application-reference-id-or-throw.util.spec.ts
new file mode 100644
index 00000000000..03171efc854
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/resolve-application-reference-id-or-throw.util.spec.ts
@@ -0,0 +1,75 @@
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import { resolveApplicationReferenceIdOrThrow } from 'src/engine/core-modules/application/application-manifest/utils/resolve-application-reference-id-or-throw.util';
+import { type SyncableFlatEntity } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
+import { type UniversalFlatEntityMaps } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-maps.type';
+
+const LOGIC_FUNCTION_ID = 'logic-function-id';
+const LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
+ 'logic-function-universal-identifier';
+const OWNER_APPLICATION_ID = 'owner-application-id';
+const OTHER_APPLICATION_ID = 'other-application-id';
+const WORKSPACE_ID = 'workspace-id';
+
+const flatEntityMaps: UniversalFlatEntityMaps<SyncableFlatEntity> = {
+ byUniversalIdentifier: {
+ [LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER]: {
+ id: LOGIC_FUNCTION_ID,
+ universalIdentifier: LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ applicationId: OWNER_APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ },
+ },
+};
+
+describe('resolveApplicationReferenceIdOrThrow', () => {
+ it('should return the entity id when the universal identifier resolves', () => {
+ expect(
+ resolveApplicationReferenceIdOrThrow({
+ flatEntityMaps,
+ universalIdentifier: LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ referenceLabel: 'uninstall logic function',
+ exceptionCode: ApplicationExceptionCode.ENTITY_NOT_FOUND,
+ }),
+ ).toBe(LOGIC_FUNCTION_ID);
+ });
+
+ it('should return the entity id when the entity belongs to the owner application', () => {
+ expect(
+ resolveApplicationReferenceIdOrThrow({
+ flatEntityMaps,
+ universalIdentifier: LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ referenceLabel: 'uninstall logic function',
+ exceptionCode: ApplicationExceptionCode.ENTITY_NOT_FOUND,
+ ownerApplicationId: OWNER_APPLICATION_ID,
+ }),
+ ).toBe(LOGIC_FUNCTION_ID);
+ });
+
+ it('should throw when the universal identifier is unknown', () => {
+ expect(() =>
+ resolveApplicationReferenceIdOrThrow({
+ flatEntityMaps,
+ universalIdentifier: 'unknown-universal-identifier',
+ referenceLabel: 'uninstall logic function',
+ exceptionCode: ApplicationExceptionCode.ENTITY_NOT_FOUND,
+ }),
+ ).toThrow(ApplicationException);
+ });
+
+ it('should throw when the entity belongs to another application', () => {
+ expect(() =>
+ resolveApplicationReferenceIdOrThrow({
+ flatEntityMaps,
+ universalIdentifier: LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ referenceLabel: 'uninstall logic function',
+ exceptionCode: ApplicationExceptionCode.ENTITY_NOT_FOUND,
+ ownerApplicationId: OTHER_APPLICATION_ID,
+ }),
+ ).toThrow(
+ `Failed to resolve uninstall logic function for universalIdentifier ${LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER}`,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/resolve-application-reference-id-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/resolve-application-reference-id-or-throw.util.ts
new file mode 100644
index 00000000000..8babe92ede8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/resolve-application-reference-id-or-throw.util.ts
@@ -0,0 +1,43 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import { type SyncableFlatEntity } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
+import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
+import { type UniversalFlatEntityMaps } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-maps.type';
+
+export const resolveApplicationReferenceIdOrThrow = <
+ T extends SyncableFlatEntity,
+>({
+ flatEntityMaps,
+ universalIdentifier,
+ referenceLabel,
+ exceptionCode,
+ ownerApplicationId,
+}: {
+ flatEntityMaps: UniversalFlatEntityMaps<T>;
+ universalIdentifier: string;
+ referenceLabel: string;
+ exceptionCode: ApplicationExceptionCode;
+ ownerApplicationId?: string;
+}): string => {
+ const flatEntity = findFlatEntityByUniversalIdentifier({
+ flatEntityMaps,
+ universalIdentifier,
+ });
+
+ if (
+ !isDefined(flatEntity) ||
+ (isDefined(ownerApplicationId) &&
+ flatEntity.applicationId !== ownerApplicationId)
+ ) {
+ throw new ApplicationException(
+ `Failed to resolve ${referenceLabel} for universalIdentifier ${universalIdentifier}`,
+ exceptionCode,
+ );
+ }
+
+ return flatEntity.id;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.entity.ts b/packages/twenty-server/src/engine/core-modules/application/application.entity.ts
index 4eed5edc7d6..bafcb464673 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.entity.ts
@@ -116,6 +116,13 @@ export class ApplicationEntity extends WorkspaceRelatedEntity {
@Column({ nullable: true, type: 'uuid' })
settingsCustomTabFrontComponentId: string | null;
+ @Column({ nullable: true, type: 'uuid' })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.32.0_AddUninstallLogicFunctionIdToApplicationFastInstanceCommand_1786959731000',
+ })
+ uninstallLogicFunctionId: string | null;
+
@Column({ nullable: false, type: 'boolean', default: true })
canBeUninstalled: boolean;
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/__tests__/morph-relation-from-create-field-input-to-flat-field-metadatas-to-create.spec.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/__tests__/morph-relation-from-create-field-input-to-flat-field-metadatas-to-create.spec.ts
index deeaac7312e..1a735751fd5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/__tests__/morph-relation-from-create-field-input-to-flat-field-metadatas-to-create.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/__tests__/morph-relation-from-create-field-input-to-flat-field-metadatas-to-create.spec.ts
@@ -40,6 +40,7 @@ const MOCK_FLAT_APPLICATION: FlatApplication = {
defaultRoleId: null,
defaultRole: null,
settingsCustomTabFrontComponentId: null,
+ uninstallLogicFunctionId: null,
canBeUninstalled: false,
autoUpgrade: false,
applicationRegistrationId: null,
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/generate-morph-or-relation-flat-field-metadata-pair.spec.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/generate-morph-or-relation-flat-field-metadata-pair.spec.ts
index 276c487a904..9fa4dc49f3f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/generate-morph-or-relation-flat-field-metadata-pair.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/generate-morph-or-relation-flat-field-metadata-pair.spec.ts
@@ -35,6 +35,7 @@ const MOCK_FLAT_APPLICATION: FlatApplication = {
defaultRoleId: null,
defaultRole: null,
settingsCustomTabFrontComponentId: null,
+ uninstallLogicFunctionId: null,
canBeUninstalled: false,
autoUpgrade: false,
applicationRegistrationId: null,
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-uninstall-application-logic-function-hook.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-uninstall-application-logic-function-hook.integration-spec.ts
index cc7ed01d0b7..59cb5a612ec 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/successful-uninstall-application-logic-function-hook.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-uninstall-application-logic-function-hook.integration-spec.ts
@@ -56,6 +56,41 @@ describe('Uninstall application logic function hook', () => {
let logicFunctionId: string;
let executeSpy: jest.SpyInstance;
+ const syncTestApplication = ({
+ withUninstallHook,
+ }: {
+ withUninstallHook: boolean;
+ }) =>
+ syncApplication({
+ manifest: buildManifestWithLogicFunction({
+ appId,
+ roleId,
+ logicFunctionId,
+ withUninstallHook,
+ }),
+ expectToFail: false,
+ });
+
+ const setRegistrationManifest = (manifest: Manifest | null) =>
+ globalThis.testDataSource.query(
+ `UPDATE core."applicationRegistration"
+ SET "manifest" = $1::jsonb
+ WHERE "universalIdentifier" = $2`,
+ [manifest ? JSON.stringify(manifest) : null, appId],
+ );
+
+ const findInstalledUninstallLogicFunctionId = async (): Promise<string> => {
+ const [installedLogicFunction] = await globalThis.testDataSource.query(
+ `SELECT id FROM core."logicFunction"
+ WHERE "universalIdentifier" = $1 AND "deletedAt" IS NULL`,
+ [logicFunctionId],
+ );
+
+ expect(installedLogicFunction).toBeDefined();
+
+ return installedLogicFunction.id;
+ };
+
beforeEach(async () => {
appId = uuidv4();
roleId = uuidv4();
@@ -92,15 +127,7 @@ describe('Uninstall application logic function hook', () => {
});
it('executes the uninstall hook before deleting the application', async () => {
- await syncApplication({
- manifest: buildManifestWithLogicFunction({
- appId,
- roleId,
- logicFunctionId,
- withUninstallHook: true,
- }),
- expectToFail: false,
- });
+ await syncTestApplication({ withUninstallHook: true });
const { data, errors } = await uninstallApplication({
universalIdentifier: appId,
@@ -119,17 +146,64 @@ describe('Uninstall application logic function hook', () => {
);
}, 60000);
- it('does not execute any hook when the manifest declares no uninstall logic function', async () => {
- await syncApplication({
- manifest: buildManifestWithLogicFunction({
+ it('executes the hook when the registration manifest is unavailable', async () => {
+ await syncTestApplication({ withUninstallHook: true });
+
+ const installedUninstallLogicFunctionId =
+ await findInstalledUninstallLogicFunctionId();
+
+ await setRegistrationManifest(null);
+
+ const { data, errors } = await uninstallApplication({
+ universalIdentifier: appId,
+ expectToFail: false,
+ });
+
+ expect(errors).toBeUndefined();
+ expect(data?.uninstallApplication).toBe(true);
+ expect(executeSpy).toHaveBeenCalledTimes(1);
+ expect(executeSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ logicFunctionId: installedUninstallLogicFunctionId,
+ payload: { version: '1.0.0' },
+ }),
+ );
+ }, 60000);
+
+ it('executes the hook resolved at sync time when the registration manifest advances', async () => {
+ await syncTestApplication({ withUninstallHook: true });
+
+ const installedUninstallLogicFunctionId =
+ await findInstalledUninstallLogicFunctionId();
+
+ await setRegistrationManifest(
+ buildManifestWithLogicFunction({
appId,
roleId,
- logicFunctionId,
- withUninstallHook: false,
+ logicFunctionId: uuidv4(),
+ withUninstallHook: true,
}),
+ );
+
+ const { data, errors } = await uninstallApplication({
+ universalIdentifier: appId,
expectToFail: false,
});
+ expect(errors).toBeUndefined();
+ expect(data?.uninstallApplication).toBe(true);
+ expect(executeSpy).toHaveBeenCalledTimes(1);
+ expect(executeSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ logicFunctionId: installedUninstallLogicFunctionId,
+ payload: { version: '1.0.0' },
+ }),
+ );
+ }, 60000);
+
+ it('does not execute any hook when the manifest declares no uninstall logic function', async () => {
+ await syncTestApplication({ withUninstallHook: false });
+
const { data, errors } = await uninstallApplication({
universalIdentifier: appId,
expectToFail: false,
@@ -141,6 +215,28 @@ describe('Uninstall application logic function hook', () => {
expect(executeSpy).not.toHaveBeenCalled();
}, 60000);
+ it('does not execute any hook when an upgrade removes the uninstall logic function from the manifest', async () => {
+ await syncTestApplication({ withUninstallHook: true });
+ await syncTestApplication({ withUninstallHook: false });
+
+ const [application] = await globalThis.testDataSource.query(
+ `SELECT "uninstallLogicFunctionId" FROM core."application"
+ WHERE "universalIdentifier" = $1 AND "deletedAt" IS NULL`,
+ [appId],
+ );
+
+ expect(application.uninstallLogicFunctionId).toBeNull();
+
+ const { data, errors } = await uninstallApplication({
+ universalIdentifier: appId,
+ expectToFail: false,
+ });
+
+ expect(errors).toBeUndefined();
+ expect(data?.uninstallApplication).toBe(true);
+ expect(executeSpy).not.toHaveBeenCalled();
+ }, 60000);
+
it('uninstalls the application even when the uninstall hook returns an error (best-effort)', async () => {
executeSpy.mockResolvedValue({
data: null,
@@ -154,15 +250,7 @@ describe('Uninstall application logic function hook', () => {
},
});
- await syncApplication({
- manifest: buildManifestWithLogicFunction({
- appId,
- roleId,
- logicFunctionId,
- withUninstallHook: true,
- }),
- expectToFail: false,
- });
+ await syncTestApplication({ withUninstallHook: true });
const { data, errors } = await uninstallApplication({
universalIdentifier: appId,