Skip to content

The open alternative to Salesforce, designed for AI.

Defer slow workspace migration actions to a worker job (#26222)

Charles Bochet6d47d4406707
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index c0fa1bb2eff..e72fb311538 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2004,6 +2004,7 @@ enum FeatureFlagKey {
IS_RECORD_SHARING_ENABLED
IS_INITIAL_OBJECT_VIEW_ENABLED
IS_WEBHOOK_RATE_LIMIT_ENABLED
+ IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED
}
type WorkspaceUrls {
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index fd6896893db..39289fb74df 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1611,7 +1611,7 @@ export interface FeatureFlag {
__typename: 'FeatureFlag'
}
-export type FeatureFlagKey = 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED' | 'IS_RECORD_SHARING_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED'
+export type FeatureFlagKey = 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED' | 'IS_RECORD_SHARING_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED' | 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED'
export interface WorkspaceUrls {
customUrl?: Scalars['String']
@@ -10848,7 +10848,8 @@ export const enumFeatureFlagKey = {
IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED: 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED' as const,
IS_RECORD_SHARING_ENABLED: 'IS_RECORD_SHARING_ENABLED' as const,
IS_INITIAL_OBJECT_VIEW_ENABLED: 'IS_INITIAL_OBJECT_VIEW_ENABLED' as const,
- IS_WEBHOOK_RATE_LIMIT_ENABLED: 'IS_WEBHOOK_RATE_LIMIT_ENABLED' as const
+ IS_WEBHOOK_RATE_LIMIT_ENABLED: 'IS_WEBHOOK_RATE_LIMIT_ENABLED' as const,
+ IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED: 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' as const
}
export const enumIdentityProviderType = {
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index a015ec7387c..43728b134d3 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -426,6 +426,7 @@ export type FeatureFlag = {
export enum FeatureFlagKey {
IS_ASYNC_CSV_EXPORT_ENABLED = 'IS_ASYNC_CSV_EXPORT_ENABLED',
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED = 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED',
+ IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED = 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED',
IS_INITIAL_OBJECT_VIEW_ENABLED = 'IS_INITIAL_OBJECT_VIEW_ENABLED',
IS_JSON_FILTER_ENABLED = 'IS_JSON_FILTER_ENABLED',
IS_JUNCTION_RELATIONS_ENABLED = 'IS_JUNCTION_RELATIONS_ENABLED',
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 784664098c7..ff9ec6865a7 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -2074,6 +2074,7 @@ export type FeatureFlag = {
export enum FeatureFlagKey {
IS_ASYNC_CSV_EXPORT_ENABLED = 'IS_ASYNC_CSV_EXPORT_ENABLED',
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED = 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED',
+ IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED = 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED',
IS_INITIAL_OBJECT_VIEW_ENABLED = 'IS_INITIAL_OBJECT_VIEW_ENABLED',
IS_JSON_FILTER_ENABLED = 'IS_JSON_FILTER_ENABLED',
IS_JUNCTION_RELATIONS_ENABLED = 'IS_JUNCTION_RELATIONS_ENABLED',
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
index 563f3dea6c9..0cab8238a17 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
@@ -54,4 +54,8 @@ export const SETTINGS_ADMIN_FEATURE_FLAG_METADATA: Partial<
label: msg`Webhook rate limits`,
description: msg`Limit the rate of outgoing webhook deliveries.`,
},
+ [FeatureFlagKey.IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED]: {
+ label: msg`Deferred workspace migration actions`,
+ description: msg`Run the slow parts of data model changes in the background after they are saved.`,
+ },
};
diff --git a/packages/twenty-server/docs/DEFERRED_WORKSPACE_MIGRATION_ACTIONS.md b/packages/twenty-server/docs/DEFERRED_WORKSPACE_MIGRATION_ACTIONS.md
new file mode 100644
index 00000000000..180e082250d
--- /dev/null
+++ b/packages/twenty-server/docs/DEFERRED_WORKSPACE_MIGRATION_ACTIONS.md
@@ -0,0 +1,163 @@
+# Deferred workspace migration actions
+
+Implementation: [twentyhq/twenty#26222](https://github.com/twentyhq/twenty/pull/26222) (PR 1 of 6, behind a feature flag). In-repo copy: `packages/twenty-server/docs/DEFERRED_WORKSPACE_MIGRATION_ACTIONS.md`.
+
+## Problem
+
+Data model changes (settings UI, metadata API, application installs) become unusable on workspaces with large tables. A self-hosted customer with 15M `timelineActivity` rows saw each new object cost about 6 minutes; an application install with dozens of objects was estimated at 7 hours, hit the query timeout and rolled back while the application version bump survived. Their workaround is to empty `timelineActivity` before every deployment. Cloud runs the same code path; 23 cloud workspaces had more than 1M `timelineActivity` rows (up to 17.9M) before they were trimmed on 2026-09-19, so they would pay the same cost on a slower disk.
+
+## Context
+
+A workspace migration runs every action in one Postgres transaction: `WorkspaceMigrationRunnerService.executeRun` opens it (`workspace-migration-runner.service.ts:349`), sets `lock_timeout = 8s` (`:365`) and commits once after the whole action loop (`:427`). Each action handler runs two steps inside that transaction, `executeForMetadata` and `executeForWorkspaceSchema` (`workspace-migration-runner-action-handler-service.interface.ts`).
+
+Every new object gets system relations: a `target<Object>Id` join column on `timelineActivity`, `attachment`, `noteTarget` and `taskTarget` (`build-system-relation-flat-field-metadatas-for-object.util.ts`). For each one the runner issues, in the same transaction:
+
+1. `ADD COLUMN`: instant, but takes an `ACCESS EXCLUSIVE` lock held until commit, blocking every read and write on that table for the rest of the migration;
+2. `ADD CONSTRAINT ... FOREIGN KEY` (`create-field-action-handler.service.ts:274`), which scans the whole table to validate a column that is `NULL` on every row;
+3. a blocking `CREATE INDEX` (`create-index-action-handler.service.ts`), which scans and sorts the whole table again.
+
+The cost is two full table scans per new object, proportional to table size rather than to the size of the change. The runner uses the core datasource, whose client-side `query_timeout` defaults to 10s (`core.datasource.ts:81`); a timed-out query keeps running on the server while holding its locks.
+
+The runner already has one mechanism for work outside the transaction: `afterCommitSideEffects` (introduced in #21845). Its only user is `DeleteLogicFunctionActionHandlerService`, which deletes a logic function's storage files and runtime resource after commit as in-process closures; a failure is logged and forgotten (`workspace-migration-runner.service.ts:545` on main). The #21845 description already anticipated moving this to "jobs and metadata boolean state tracker in db".
+
+## Goals and non-goals
+
+Goals:
+
+- Move the slow, non-correctness-critical part of selected migration actions out of the migration transaction, starting with join column index creation.
+- Make that deferred work durable: recorded in the same transaction as the metadata, retried, observable.
+- One mechanism for all post-transaction work, replacing `afterCommitSideEffects`.
+- Same orchestration as the runner: deferred work is executed by the action handler that produced it, found through the same registry.
+
+Non-goals (this doc and PR 1):
+
+- Unique indexes, enum migrations, index updates (drop and rebuild), search vector rebuilds. Each can become a deferrable action later with the same contract.
+- Serializing concurrent metadata migrations, blocking changes while work is pending, and surfacing that state to users (PRs 3 and 4 below).
+- Recovery of stranded rows and retry of failed ones (PR 2).
+
+## Design
+
+### Principles
+
+- **Metadata storage is the source of truth.** Decisions come from metadata and from the deferred action table, never from `information_schema`, `pg_index` or `pg_class`.
+- **Deferred work is persisted in the migration transaction.** The migration either commits with its deferred work recorded or rolls back without it.
+- **Correctness stays inline, cost moves out.** Unique indexes and foreign key enforcement stay in the transaction.
+- **Behind `IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED`**, a workspace feature flag, off by default. With the flag off, behavior is unchanged.
+
+### Deferrable actions
+
+`DEFERRABLE_WORKSPACE_MIGRATION_ACTIONS` lists the action handler keys (`<actionType>_<metadataName>`, the key the runner registry already uses) that may defer work. Each declares its payload type; adding a key without a payload fails to compile.
+
+| Action | Deferred work | Payload |
+| --- | --- | --- |
+| `create_index` | `CREATE INDEX CONCURRENTLY` for a non-unique, non-partial index covering only `MANY_TO_ONE` join columns | `{ indexMetadataId }`, a reference: the index metadata still exists after commit |
+| `delete_logicFunction` | delete the source folder and built handler from storage, delete the runtime resource | `{ flatLogicFunction }`, a snapshot: the metadata is gone after commit |
+
+### Action handler contract
+
+`BaseWorkspaceMigrationRunnerActionHandlerService` gets two methods next to `executeForMetadata` and `executeForWorkspaceSchema`:
+
+- `getDeferredAction(context)` returns the deferred action of this action instance, typed so a handler can only return its own key, or `undefined` (default). The handler owns the decision and skips the matching inline work. `create_index` defers only when `IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED` is on in the `featureFlagsMap` the runner passes in the context; `delete_logicFunction` always returns its cleanup.
+- `executeDeferredAction({ workspaceId, applicationUniversalIdentifier, payload, allFlatEntityMaps, attempt, queryRunner })` performs the deferred work outside any transaction. Like transactional actions, it receives the flat entity maps it needs and never reads or recomputes the workspace cache itself. It must be idempotent and treats metadata that no longer exists as an obsolete action rather than a failure.
+
+`execute()` returns `deferredActions` next to `partialOptimisticCache` and `metadataEvents`. `afterCommitSideEffects` is removed.
+
+### Runner
+
+```mermaid
+sequenceDiagram
+ participant Client
+ participant Runner as WorkspaceMigrationRunnerService
+ participant Handler as Action handler
+ participant DB as Postgres (core + workspace schema)
+ participant Queue as workspaceQueue
+ participant Worker as DeferredWorkspaceMigrationActionRunnerService
+
+ Client->>Runner: run(workspaceMigration)
+ Runner->>DB: BEGIN
+ loop each action
+ Runner->>Handler: execute(context)
+ Handler->>DB: metadata rows + inline DDL (deferred part skipped)
+ Handler-->>Runner: deferredActions
+ end
+ Runner->>DB: INSERT core.deferredWorkspaceMigrationAction (flag on)
+ Runner->>DB: COMMIT
+ Runner->>Queue: RunDeferredWorkspaceMigrationActionsJob (one per workspace)
+ Runner-->>Client: success
+ Queue->>Worker: runPendingActions(workspaceId)
+ loop each PENDING row
+ Worker->>DB: claim (PENDING to IN_PROGRESS)
+ Worker->>Handler: executeDeferredAction(payload) via registry
+ Handler->>DB: CREATE INDEX CONCURRENTLY / storage cleanup
+ Worker->>DB: delete row, or back to PENDING / FAILED
+ end
+```
+
+The runner delegates both steps to `DeferredWorkspaceMigrationActionRunnerService`:
+
+- **Flag on:** `persist` inserts the collected deferred actions inside the migration transaction (`workspace-migration-runner.service.ts:417`), and after commit `dispatchAfterCommit` (`:556`) enqueues one job for the workspace.
+- **Flag off:** nothing is persisted. `create_index` does not defer, so only the logic function cleanup produces a deferred action, and `dispatchAfterCommit` executes it in process right after commit, which is the previous `afterCommitSideEffects` behavior.
+
+### Storage: `core.deferredWorkspaceMigrationAction`
+
+| Column | Purpose |
+| --- | --- |
+| `workspaceId` | owning workspace, `ON DELETE CASCADE` |
+| `applicationUniversalIdentifier` | application of the migration, passed back to the handler |
+| `actionHandlerKey` | one of the deferrable actions, used to find the handler |
+| `payload` | `jsonb`, the handler payload |
+| `position` | order of the action within its migration |
+| `runByVersion` | `APP_VERSION` of the server that ran the migration |
+| `status` | `PENDING`, `IN_PROGRESS` or `FAILED` |
+| `attempts`, `lastError`, `startedAt` | retry bookkeeping |
+
+Index on `(workspaceId, status)`. A row is deleted once its action succeeds. The table is not part of the flat entity maps or the migration builder.
+
+### Execution
+
+`RunDeferredWorkspaceMigrationActionsJob` runs on `workspaceQueue`, deduplicated per workspace, 3 attempts retried immediately. `DeferredWorkspaceMigrationActionRunnerService.runPendingActions`:
+
+1. loads the workspace's `PENDING` rows once, ordered by creation then `position` (actions created later come with their own job);
+2. claims each row with a conditional update (`PENDING` to `IN_PROGRESS`, `attempts + 1`);
+3. resolves the handler with `actionHandlerKey` (`executeDeferredActionHandler`, registry `:118`) and calls `executeDeferredAction` with the flat entity maps loaded once per run through `WorkspaceManyOrAllFlatEntityMapsCacheService`, for the same metadata names the migration runner would load (`getMetadataNamesToLoadForWorkspaceMigration`), on a dedicated connection without the client `query_timeout` and with a server-side `statement_timeout` of one hour, so Postgres cancels a stuck statement itself;
+4. deletes the row on success, or sets it back to `PENDING` (`FAILED` after the last attempt) with `lastError`;
+5. stops at the first failure and fails the job, so the queue retries it and the remaining actions keep running in order.
+
+`create_index` reads the index from the maps it receives and completes as obsolete if it is absent. The maps are fresh because the runner invalidates the cache after commit, before enqueueing the job. On a retry it runs `DROP INDEX CONCURRENTLY IF EXISTS` first, since a failed concurrent build leaves an invalid index behind.
+
+## Alternatives considered
+
+- **Keep deferred work on `afterCommitSideEffects`.** It is in-process and fire-and-forget: a crash after commit loses the work and leaves metadata describing an index that does not exist. Lost because the work must be durable.
+- **Per-type state columns on `indexMetadata` / `fieldMetadata`.** Adding a column to a syncable entity touches the flat entity plumbing, cache codec and builder comparison in about 25 files, and changing `fieldMetadata` bumps the metadata version for every client. Lost to a dedicated table that also serves as the job's queue.
+- **An index-specific `deferredSchemaOperation` table** (first iteration of the PR). It did not cover the logic function cleanup and required a separate orchestration next to the runner. Lost to one generic table keyed by action.
+- **A size threshold (defer only above N rows via `pg_class.reltuples`).** Lost because it reads Postgres catalogs instead of metadata. Every eligible index is deferred instead, including indexes on tables created by the same migration, which the worker builds in milliseconds since those tables are empty.
+- **Skip the index and keep only a partial `WHERE col IS NOT NULL` index inline.** A partial index still reads the whole table to build. Lost because it does not remove the scan.
+
+## Rollout and testing
+
+Delivery, each PR merged on its own behind the flag:
+
+| PR | Scope |
+| --- | --- |
+| 1 | Table, `DEFERRABLE_WORKSPACE_MIGRATION_ACTIONS`, handler contract, runner persistence, deferred action runner and job with retries and timeout; `create_index` and `delete_logicFunction`; `afterCommitSideEffects` removed. |
+| 2 | Recovery: sweeper cron resetting `IN_PROGRESS` rows past the timeout and re-enqueueing workspaces with `PENDING` rows; retry of `FAILED` rows (admin mutation, CLI); metrics on pending, failed and duration. |
+| 3 | Workspace migration lock: `schemaMigrationStatus` (`IDLE`, `MIGRATING`) and `schemaMigrationStartedAt` on `core.workspace`, taken with a conditional update before migrations touching objects, fields or indexes, released in `finally` with a takeover timeout. While taken, or while schema-affecting deferred actions are pending (`create_index`, not `delete_logicFunction`), such migrations fail with `SCHEMA_MIGRATION_IN_PROGRESS` or `DEFERRED_WORKSPACE_MIGRATION_ACTIONS_IN_PROGRESS`. `FAILED` rows do not block. |
+| 4 | Error surfacing: runner codes sent as `subCode` (today `extensions.code` is overwritten by the GraphQL error code), object and field exception handlers map the new codes to `ConflictError`, dedicated front message with the pending count, SDK CLI reads `subCode` and `userFriendlyMessage`. |
+| 5 | Foreign keys: `ADD CONSTRAINT ... NOT VALID` for join columns created in the same action, plus a deferrable `create_fieldMetadata` action running `VALIDATE CONSTRAINT` with the constraint name in its payload. |
+| 6 | Enable the flag for the affected self-hosted workspace, then cloud, then default on and remove the flag. |
+
+Migration: one fast instance command in 2.42 creating the table. No backfill.
+
+Tested in PR 1:
+
+- unit: the deferral decision (unique, partial, non-relation, one-to-many side, mixed columns, unresolved field);
+- integration, through the public APIs only: with the flag on, creating an object adds one join column index to each system relation object, records of the new object get timeline activities, and deleting a logic function succeeds; existing object, field, index and logic function suites pass;
+- manual, 3M `timelineActivity` rows: flag off logic function deletion removes files right after commit; flag on persists actions with the worker stopped and processes them once started (`timelineActivity` index built in 2.4s outside the transaction); an object deleted before the worker ran completes its actions as obsolete; a broken column fails three times then `FAILED` while the other indexes build immediately; restoring it before a retry drops and rebuilds the index.
+
+Known limitations until PRs 2 and 3: a worker crash leaves a row `IN_PROGRESS`; `FAILED` rows need a manual reset and no longer hold back the actions after them; metadata changes are not blocked while actions are pending, so a deletion racing an in-flight build can leave a physical index without metadata.
+
+## Open questions
+
+1. **Should deferral be decided by the runner at step level instead of by each handler?** Today `create_index` defers its `executeForWorkspaceSchema` step while `delete_logicFunction` defers work that was never a runner step, each handler builds its own payload, and the handler has to remember to skip its own inline work. A more consistent shape: the runner skips the step for deferrable actions and persists the flat action itself (plus the pre-delete flat entity for deletes), and the worker replays the same step with a rebuilt context. Logic function cleanup would then need a real step, either (a) its currently empty `executeForWorkspaceSchema`, or (b) a new `executeForExternalResources` step that always runs after commit. Recommendation: runner-owned deferral with option (b), done in PR 1 before merge.
+2. **Should logic function cleanup be durable for everyone now, not only behind the flag?** It is low risk and fixes silent orphans in storage. Recommendation: keep it behind the flag until PR 2 (recovery) lands.
+3. **Should the one-hour statement timeout be a config variable?** Recommendation: constant for now, config variable if a self-hosted instance needs more.
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1790085198967-add-deferred-workspace-migration-action-table.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1790085198967-add-deferred-workspace-migration-action-table.ts
new file mode 100644
index 00000000000..bf9658554ba
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1790085198967-add-deferred-workspace-migration-action-table.ts
@@ -0,0 +1,19 @@
+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.42.0', 1790085198967)
+export class AddDeferredWorkspaceMigrationActionTableFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('CREATE TABLE "core"."deferredWorkspaceMigrationAction" ("workspaceId" uuid NOT NULL, "id" uuid NOT NULL DEFAULT uuid_generate_v4(), "applicationUniversalIdentifier" character varying NOT NULL, "actionHandlerKey" character varying NOT NULL, "payload" jsonb NOT NULL, "position" integer NOT NULL, "runByVersion" character varying, "status" character varying NOT NULL DEFAULT \'PENDING\', "attempts" integer NOT NULL DEFAULT \'0\', "lastError" text, "startedAt" TIMESTAMP WITH TIME ZONE, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_eb96f18b805c453f3375b9d1aea" PRIMARY KEY ("id"))');
+ await queryRunner.query('CREATE INDEX "IDX_DEFERRED_WORKSPACE_MIGRATION_ACTION_WORKSPACE_ID_STATUS" ON "core"."deferredWorkspaceMigrationAction" ("workspaceId", "status") ');
+ await queryRunner.query('ALTER TABLE "core"."deferredWorkspaceMigrationAction" ADD CONSTRAINT "FK_c3810cd3a6109f5e1bf6f84c60f" FOREIGN KEY ("workspaceId") REFERENCES "core"."workspace"("id") ON DELETE CASCADE ON UPDATE NO ACTION');
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('ALTER TABLE "core"."deferredWorkspaceMigrationAction" DROP CONSTRAINT "FK_c3810cd3a6109f5e1bf6f84c60f"');
+ await queryRunner.query('DROP INDEX "core"."IDX_DEFERRED_WORKSPACE_MIGRATION_ACTION_WORKSPACE_ID_STATUS"');
+ await queryRunner.query('DROP TABLE "core"."deferredWorkspaceMigrationAction"');
+ }
+}
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 7e398c6acfb..97dd1328946 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
@@ -199,6 +199,7 @@ import { CoreWorkflowCommandMenuItemsFastInstanceCommand } from 'src/database/co
import { AddWorkflowVisibilityFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1789893300000-add-workflow-visibility';
import { AddAiEvaluationModelToWorkspaceFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1789918648347-add-ai-evaluation-model-to-workspace';
import { AddIsRequiredToApplicationVariablesFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1789920900000-add-is-required-to-application-variables';
+import { AddDeferredWorkspaceMigrationActionTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1790085198967-add-deferred-workspace-migration-action-table';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -400,4 +401,5 @@ export const INSTANCE_COMMANDS = [
AddAppMessageChannelUniqueHandleFastInstanceCommand,
AddAiEvaluationModelToWorkspaceFastInstanceCommand,
AddIsRequiredToApplicationVariablesFastInstanceCommand,
+ AddDeferredWorkspaceMigrationActionTableFastInstanceCommand,
];
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 4c228e712b9..9f94bf453d9 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
@@ -57,6 +57,8 @@ import { LogicFunctionModule } from 'src/engine/metadata-modules/logic-function/
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';
import { WebhookJobModule } from 'src/engine/metadata-modules/webhook/jobs/webhook-job.module';
+import { RunDeferredWorkspaceMigrationActionsJob } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/jobs/run-deferred-workspace-migration-actions.job';
+import { WorkspaceMigrationRunnerModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/workspace-migration-runner.module';
import { SubscriptionsModule } from 'src/engine/subscriptions/subscriptions.module';
import { CleanOnboardingWorkspacesJob } from 'src/engine/workspace-manager/workspace-cleaner/crons/clean-onboarding-workspaces.job';
import { CleanSuspendedWorkspacesJob } from 'src/engine/workspace-manager/workspace-cleaner/crons/clean-suspended-workspaces.job';
@@ -117,6 +119,7 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
OnboardingModule,
BillingReminderModule,
ApplicationRecurringChargeModule,
+ WorkspaceMigrationRunnerModule,
],
providers: [
ApplicationRecurringChargeCronJob,
@@ -143,6 +146,7 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
TriggerInstallApplicationJob,
TriggerUninstallApplicationJob,
WarmUpApplicationLogicFunctionsJob,
+ RunDeferredWorkspaceMigrationActionsJob,
],
})
export class JobsModule {
diff --git a/packages/twenty-server/src/engine/metadata-modules/deferred-workspace-migration-action/deferred-workspace-migration-action.entity.ts b/packages/twenty-server/src/engine/metadata-modules/deferred-workspace-migration-action/deferred-workspace-migration-action.entity.ts
new file mode 100644
index 00000000000..5dbacc797b0
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/deferred-workspace-migration-action/deferred-workspace-migration-action.entity.ts
@@ -0,0 +1,55 @@
+import {
+ Column,
+ CreateDateColumn,
+ Entity,
+ Index,
+ PrimaryGeneratedColumn,
+ UpdateDateColumn,
+} from 'typeorm';
+
+import { type PersistedDeferredWorkspaceMigrationAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type';
+import { type DeferredWorkspaceMigrationActionStatus } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-status.type';
+import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity';
+
+@Index('IDX_DEFERRED_WORKSPACE_MIGRATION_ACTION_WORKSPACE_ID_STATUS', [
+ 'workspaceId',
+ 'status',
+])
+@Entity({ name: 'deferredWorkspaceMigrationAction', schema: 'core' })
+export class DeferredWorkspaceMigrationActionEntity extends WorkspaceRelatedEntity {
+ @PrimaryGeneratedColumn('uuid')
+ id: string;
+
+ @Column({ type: 'varchar' })
+ applicationUniversalIdentifier: string;
+
+ @Column({ type: 'varchar' })
+ actionHandlerKey: PersistedDeferredWorkspaceMigrationAction['actionHandlerKey'];
+
+ @Column({ type: 'jsonb' })
+ payload: PersistedDeferredWorkspaceMigrationAction['payload'];
+
+ @Column({ type: 'integer' })
+ position: number;
+
+ @Column({ type: 'varchar', nullable: true })
+ runByVersion: string | null;
+
+ @Column({ type: 'varchar', default: 'PENDING' })
+ status: DeferredWorkspaceMigrationActionStatus;
+
+ @Column({ type: 'integer', default: 0 })
+ attempts: number;
+
+ @Column({ type: 'text', nullable: true })
+ lastError: string | null;
+
+ @Column({ type: 'timestamptz', nullable: true })
+ startedAt: Date | null;
+
+ @CreateDateColumn({ type: 'timestamptz' })
+ createdAt: Date;
+
+ @UpdateDateColumn({ type: 'timestamptz' })
+ updatedAt: Date;
+}
diff --git a/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/services/workspace-schema-index-manager.service.ts b/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/services/workspace-schema-index-manager.service.ts
index 6392e6a3d1d..3f4b7d19d78 100644
--- a/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/services/workspace-schema-index-manager.service.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/services/workspace-schema-index-manager.service.ts
@@ -81,12 +81,14 @@ export class WorkspaceSchemaIndexManagerService {
queryRunner,
schemaName,
indexName,
+ concurrently = false,
}: {
queryRunner: QueryRunner;
schemaName: string;
indexName: string;
+ concurrently?: boolean;
}): Promise<void> {
- const sql = `DROP INDEX IF EXISTS ${escapeIdentifier(schemaName)}.${escapeIdentifier(indexName)}`;
+ const sql = `DROP INDEX ${concurrently ? 'CONCURRENTLY ' : ''}IF EXISTS ${escapeIdentifier(schemaName)}.${escapeIdentifier(indexName)}`;
await queryRunner.query(sql);
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/services/create-index-action-handler.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/services/create-index-action-handler.service.ts
index 121985b6a46..52a096e01da 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/services/create-index-action-handler.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/services/create-index-action-handler.service.ts
@@ -1,10 +1,14 @@
import { Injectable } from '@nestjs/common';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
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 { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
+import { findManyFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-many-flat-entity-by-id-in-flat-entity-maps.util';
import { IndexFieldMetadataEntity } from 'src/engine/metadata-modules/index-metadata/index-field-metadata.entity';
import { WorkspaceSchemaManagerService } from 'src/engine/twenty-orm/workspace-schema-manager/workspace-schema-manager.service';
import {
@@ -13,6 +17,10 @@ import {
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/index/types/workspace-migration-index-action';
import { fromUniversalFlatIndexToFlatIndex } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/from-universal-flat-index-to-flat-index.util';
import { createIndexInWorkspaceSchema } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/index-action-handler.utils';
+import { isIndexCreationDeferrable } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/is-index-creation-deferrable.util';
+import { type DeferredWorkspaceMigrationActionPayload } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type';
+import { type DeferredWorkspaceMigrationActionExecutionArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-execution-args.type';
+import { getWorkspaceSchemaContextForMigration } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/get-workspace-schema-context-for-migration.util';
import {
type WorkspaceMigrationActionRunnerArgs,
type WorkspaceMigrationActionRunnerContext,
@@ -79,6 +87,10 @@ export class CreateIndexActionHandlerService extends WorkspaceMigrationRunnerAct
workspaceId,
} = context;
+ if (this.shouldDeferIndexCreation(context)) {
+ return;
+ }
+
const flatObjectMetadata = findFlatEntityByIdInFlatEntityMapsOrThrow({
flatEntityMaps: flatObjectMetadataMaps,
flatEntityId: flatIndexMetadata.objectMetadataId,
@@ -93,4 +105,93 @@ export class CreateIndexActionHandlerService extends WorkspaceMigrationRunnerAct
workspaceId,
});
}
+
+ protected override getDeferredAction(
+ context: WorkspaceMigrationActionRunnerContext<FlatCreateIndexAction>,
+ ) {
+ if (!this.shouldDeferIndexCreation(context)) {
+ return undefined;
+ }
+
+ return {
+ actionHandlerKey: 'create_index' as const,
+ payload: { indexMetadataId: context.flatAction.flatEntity.id },
+ };
+ }
+
+ override async executeDeferredAction({
+ workspaceId,
+ payload: { indexMetadataId },
+ allFlatEntityMaps: {
+ flatIndexMaps,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ },
+ attempt,
+ queryRunner,
+ }: DeferredWorkspaceMigrationActionExecutionArgs<
+ DeferredWorkspaceMigrationActionPayload<'create_index'>
+ >): Promise<void> {
+ const flatIndexMetadata = findFlatEntityByIdInFlatEntityMaps({
+ flatEntityMaps: flatIndexMaps,
+ flatEntityId: indexMetadataId,
+ });
+
+ if (!isDefined(flatIndexMetadata)) {
+ return;
+ }
+
+ const flatObjectMetadata = findFlatEntityByIdInFlatEntityMapsOrThrow({
+ flatEntityMaps: flatObjectMetadataMaps,
+ flatEntityId: flatIndexMetadata.objectMetadataId,
+ });
+
+ if (attempt > 1) {
+ const { schemaName } = getWorkspaceSchemaContextForMigration({
+ workspaceId,
+ objectMetadata: flatObjectMetadata,
+ });
+
+ await this.workspaceSchemaManagerService.indexManager.dropIndex({
+ queryRunner,
+ schemaName,
+ indexName: flatIndexMetadata.name,
+ concurrently: true,
+ });
+ }
+
+ await createIndexInWorkspaceSchema({
+ flatIndexMetadata,
+ flatObjectMetadata,
+ flatFieldMetadataMaps,
+ workspaceSchemaManagerService: this.workspaceSchemaManagerService,
+ queryRunner,
+ workspaceId,
+ concurrently: true,
+ });
+ }
+
+ private shouldDeferIndexCreation({
+ featureFlagsMap,
+ allFlatEntityMaps: { flatFieldMetadataMaps },
+ flatAction: { flatEntity: flatIndexMetadata },
+ }: WorkspaceMigrationActionRunnerContext<FlatCreateIndexAction>): boolean {
+ if (
+ !featureFlagsMap?.[
+ FeatureFlagKey.IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED
+ ]
+ ) {
+ return false;
+ }
+
+ return isIndexCreationDeferrable({
+ flatIndexMetadata,
+ indexedFlatFieldMetadatas: findManyFlatEntityByIdInFlatEntityMaps({
+ flatEntityMaps: flatFieldMetadataMaps,
+ flatEntityIds: flatIndexMetadata.flatIndexFieldMetadatas.map(
+ (flatIndexFieldMetadata) => flatIndexFieldMetadata.fieldMetadataId,
+ ),
+ }),
+ });
+ }
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/__tests__/is-index-creation-deferrable.util.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/__tests__/is-index-creation-deferrable.util.spec.ts
new file mode 100644
index 00000000000..dc4a5fb4eee
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/__tests__/is-index-creation-deferrable.util.spec.ts
@@ -0,0 +1,142 @@
+import { FieldMetadataType, RelationType } from 'twenty-shared/types';
+
+import { isIndexCreationDeferrable } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/is-index-creation-deferrable.util';
+import { getFlatFieldMetadataMock } from 'src/engine/metadata-modules/flat-field-metadata/__mocks__/get-flat-field-metadata.mock';
+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
+import { getFlatIndexMetadataMock } from 'src/engine/metadata-modules/flat-index-metadata/__mocks__/get-flat-index-metadata.mock';
+import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';
+
+const TIMELINE_ACTIVITY_OBJECT_UNIVERSAL_IDENTIFIER = 'timeline-activity';
+
+const buildJoinColumnField = (
+ overrides: Partial<FlatFieldMetadata> = {},
+): FlatFieldMetadata =>
+ getFlatFieldMetadataMock({
+ universalIdentifier: 'target-new-app-object',
+ objectMetadataId: 'timeline-activity-id',
+ type: FieldMetadataType.MORPH_RELATION,
+ name: 'targetNewAppObject',
+ settings: {
+ relationType: RelationType.MANY_TO_ONE,
+ joinColumnName: 'targetNewAppObjectId',
+ },
+ ...overrides,
+ });
+
+const buildIndex = (
+ indexedFlatFieldMetadatas: FlatFieldMetadata[],
+ overrides: Partial<FlatIndexMetadata> = {},
+): FlatIndexMetadata =>
+ getFlatIndexMetadataMock({
+ universalIdentifier: 'index',
+ objectMetadataId: 'timeline-activity-id',
+ objectMetadataUniversalIdentifier:
+ TIMELINE_ACTIVITY_OBJECT_UNIVERSAL_IDENTIFIER,
+ applicationUniversalIdentifier: 'application',
+ flatIndexFieldMetadatas: indexedFlatFieldMetadatas.map(
+ (flatFieldMetadata, order) => ({
+ id: `index-field-${order}`,
+ workspaceId: 'workspace-id',
+ indexMetadataId: 'index-id',
+ fieldMetadataId: flatFieldMetadata.id,
+ subFieldName: null,
+ order,
+ createdAt: '2024-01-01T00:00:00.000Z',
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ }),
+ ),
+ ...overrides,
+ });
+
+describe('isIndexCreationDeferrable', () => {
+ it('should defer a join column index', () => {
+ const joinColumnField = buildJoinColumnField();
+
+ expect(
+ isIndexCreationDeferrable({
+ flatIndexMetadata: buildIndex([joinColumnField]),
+ indexedFlatFieldMetadatas: [joinColumnField],
+ }),
+ ).toBe(true);
+ });
+
+ it('should not defer a unique index', () => {
+ const joinColumnField = buildJoinColumnField();
+
+ expect(
+ isIndexCreationDeferrable({
+ flatIndexMetadata: buildIndex([joinColumnField], { isUnique: true }),
+ indexedFlatFieldMetadatas: [joinColumnField],
+ }),
+ ).toBe(false);
+ });
+
+ it('should not defer a partial index', () => {
+ const joinColumnField = buildJoinColumnField();
+
+ expect(
+ isIndexCreationDeferrable({
+ flatIndexMetadata: buildIndex([joinColumnField], {
+ indexWhereClause: '"deletedAt" IS NULL',
+ }),
+ indexedFlatFieldMetadatas: [joinColumnField],
+ }),
+ ).toBe(false);
+ });
+
+ it('should not defer an index on a non relation field', () => {
+ const textField = getFlatFieldMetadataMock({
+ universalIdentifier: 'name',
+ objectMetadataId: 'timeline-activity-id',
+ type: FieldMetadataType.TEXT,
+ });
+
+ expect(
+ isIndexCreationDeferrable({
+ flatIndexMetadata: buildIndex([textField]),
+ indexedFlatFieldMetadatas: [textField],
+ }),
+ ).toBe(false);
+ });
+
+ it('should not defer an index on the one to many side of a relation', () => {
+ const oneToManyField = buildJoinColumnField({
+ type: FieldMetadataType.RELATION,
+ settings: { relationType: RelationType.ONE_TO_MANY },
+ });
+
+ expect(
+ isIndexCreationDeferrable({
+ flatIndexMetadata: buildIndex([oneToManyField]),
+ indexedFlatFieldMetadatas: [oneToManyField],
+ }),
+ ).toBe(false);
+ });
+
+ it('should not defer an index mixing a join column with another field', () => {
+ const joinColumnField = buildJoinColumnField();
+ const textField = getFlatFieldMetadataMock({
+ universalIdentifier: 'name',
+ objectMetadataId: 'timeline-activity-id',
+ type: FieldMetadataType.TEXT,
+ });
+
+ expect(
+ isIndexCreationDeferrable({
+ flatIndexMetadata: buildIndex([joinColumnField, textField]),
+ indexedFlatFieldMetadatas: [joinColumnField, textField],
+ }),
+ ).toBe(false);
+ });
+
+ it('should not defer when an indexed field cannot be resolved', () => {
+ const joinColumnField = buildJoinColumnField();
+
+ expect(
+ isIndexCreationDeferrable({
+ flatIndexMetadata: buildIndex([joinColumnField]),
+ indexedFlatFieldMetadatas: [],
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/is-index-creation-deferrable.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/is-index-creation-deferrable.util.ts
new file mode 100644
index 00000000000..610f2687ae5
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/index/utils/is-index-creation-deferrable.util.ts
@@ -0,0 +1,39 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { RelationType } from 'twenty-shared/types';
+
+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
+import { isMorphOrRelationFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/utils/is-morph-or-relation-flat-field-metadata.util';
+import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';
+
+export const isIndexCreationDeferrable = ({
+ flatIndexMetadata,
+ indexedFlatFieldMetadatas,
+}: {
+ flatIndexMetadata: Pick<
+ FlatIndexMetadata,
+ 'isUnique' | 'indexWhereClause' | 'flatIndexFieldMetadatas'
+ >;
+ indexedFlatFieldMetadatas: FlatFieldMetadata[];
+}): boolean => {
+ if (
+ flatIndexMetadata.isUnique ||
+ isNonEmptyString(flatIndexMetadata.indexWhereClause)
+ ) {
+ return false;
+ }
+
+ if (
+ !isNonEmptyArray(indexedFlatFieldMetadatas) ||
+ indexedFlatFieldMetadatas.length !==
+ flatIndexMetadata.flatIndexFieldMetadatas.length
+ ) {
+ return false;
+ }
+
+ return indexedFlatFieldMetadatas.every(
+ (flatFieldMetadata) =>
+ isMorphOrRelationFlatFieldMetadata(flatFieldMetadata) &&
+ flatFieldMetadata.settings?.relationType === RelationType.MANY_TO_ONE,
+ );
+};
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/delete-logic-function-action-handler.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/delete-logic-function-action-handler.service.ts
index dab6cce082d..fee4c2da0a5 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/delete-logic-function-action-handler.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/delete-logic-function-action-handler.service.ts
@@ -1,6 +1,7 @@
import { Inject, Injectable } from '@nestjs/common';
import { FileFolder } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
import { WorkspaceMigrationRunnerActionHandler } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface';
@@ -15,7 +16,8 @@ import {
FlatDeleteLogicFunctionAction,
UniversalDeleteLogicFunctionAction,
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/logic-function/types/workspace-migration-logic-function-action.type';
-import { type AfterCommitSideEffect } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/after-commit-side-effect.type';
+import { type DeferredWorkspaceMigrationActionPayload } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type';
+import { type DeferredWorkspaceMigrationActionExecutionArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-execution-args.type';
import {
WorkspaceMigrationActionRunnerArgs,
WorkspaceMigrationActionRunnerContext,
@@ -56,50 +58,55 @@ export class DeleteLogicFunctionActionHandlerService extends WorkspaceMigrationR
});
}
- protected override getAfterCommitSideEffects(
- context: WorkspaceMigrationActionRunnerContext<FlatDeleteLogicFunctionAction>,
- ): AfterCommitSideEffect[] {
- const { flatAction, workspaceId, allFlatEntityMaps, flatApplication } =
- context;
+ protected override getDeferredAction({
+ flatAction,
+ allFlatEntityMaps,
+ }: WorkspaceMigrationActionRunnerContext<FlatDeleteLogicFunctionAction>) {
+ return {
+ actionHandlerKey: 'delete_logicFunction' as const,
+ payload: {
+ flatLogicFunction: findFlatEntityByIdInFlatEntityMapsOrThrow({
+ flatEntityMaps: allFlatEntityMaps.flatLogicFunctionMaps,
+ flatEntityId: flatAction.entityId,
+ }),
+ },
+ };
+ }
- const flatLogicFunction = findFlatEntityByIdInFlatEntityMapsOrThrow({
- flatEntityMaps: allFlatEntityMaps.flatLogicFunctionMaps,
- flatEntityId: flatAction.entityId,
- });
+ override async executeDeferredAction({
+ workspaceId,
+ applicationUniversalIdentifier,
+ payload: { flatLogicFunction },
+ }: DeferredWorkspaceMigrationActionExecutionArgs<
+ DeferredWorkspaceMigrationActionPayload<'delete_logicFunction'>
+ >): Promise<void> {
+ const results = await Promise.allSettled([
+ this.fileStorageService.deleteFolder({
+ workspaceId,
+ applicationUniversalIdentifier,
+ fileFolder: FileFolder.Source,
+ folderPath: getLogicFunctionSubfolderForFromSource(
+ flatLogicFunction.id,
+ ),
+ }),
+ this.fileStorageService.deleteFile({
+ workspaceId,
+ applicationUniversalIdentifier,
+ fileFolder: FileFolder.BuiltLogicFunction,
+ resourcePath: flatLogicFunction.builtHandlerPath,
+ }),
+ this.logicFunctionDriverFactory
+ .getCurrentDriver()
+ .delete(flatLogicFunction),
+ ]);
- const applicationUniversalIdentifier = flatApplication.universalIdentifier;
+ const failure = results.find(
+ (result): result is PromiseRejectedResult => result.status === 'rejected',
+ );
- return [
- {
- description: `source folder for logic function ${flatLogicFunction.id} (universalIdentifier=${flatLogicFunction.universalIdentifier}, applicationUniversalIdentifier=${applicationUniversalIdentifier})`,
- run: () =>
- this.fileStorageService.deleteFolder({
- workspaceId,
- applicationUniversalIdentifier,
- fileFolder: FileFolder.Source,
- folderPath: getLogicFunctionSubfolderForFromSource(
- flatLogicFunction.id,
- ),
- }),
- },
- {
- description: `built handler for logic function ${flatLogicFunction.id} (universalIdentifier=${flatLogicFunction.universalIdentifier}, applicationUniversalIdentifier=${applicationUniversalIdentifier})`,
- run: () =>
- this.fileStorageService.deleteFile({
- workspaceId,
- applicationUniversalIdentifier,
- fileFolder: FileFolder.BuiltLogicFunction,
- resourcePath: flatLogicFunction.builtHandlerPath,
- }),
- },
- {
- description: `runtime resource for logic function ${flatLogicFunction.id} (universalIdentifier=${flatLogicFunction.universalIdentifier}, applicationUniversalIdentifier=${applicationUniversalIdentifier})`,
- run: () =>
- this.logicFunctionDriverFactory
- .getCurrentDriver()
- .delete(flatLogicFunction),
- },
- ];
+ if (isDefined(failure)) {
+ throw failure.reason;
+ }
}
async rollbackForMetadata(): Promise<void> {}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferrable-workspace-migration-actions.constant.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferrable-workspace-migration-actions.constant.ts
new file mode 100644
index 00000000000..8f6f79efb6b
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferrable-workspace-migration-actions.constant.ts
@@ -0,0 +1,6 @@
+import { type WorkspaceMigrationActionHandlerKey } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/workspace-migration-action-common';
+
+export const DEFERRABLE_WORKSPACE_MIGRATION_ACTIONS = [
+ 'create_index',
+ 'delete_logicFunction',
+] as const satisfies readonly WorkspaceMigrationActionHandlerKey[];
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferred-workspace-migration-action-max-attempts.constant.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferred-workspace-migration-action-max-attempts.constant.ts
new file mode 100644
index 00000000000..0a826b486e9
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferred-workspace-migration-action-max-attempts.constant.ts
@@ -0,0 +1 @@
+export const DEFERRED_WORKSPACE_MIGRATION_ACTION_MAX_ATTEMPTS = 3;
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferred-workspace-migration-action-statement-timeout-ms.constant.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferred-workspace-migration-action-statement-timeout-ms.constant.ts
new file mode 100644
index 00000000000..8befd85b1b8
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferred-workspace-migration-action-statement-timeout-ms.constant.ts
@@ -0,0 +1,2 @@
+export const DEFERRED_WORKSPACE_MIGRATION_ACTION_STATEMENT_TIMEOUT_MS =
+ 60 * 60 * 1000;
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/run-deferred-workspace-migration-actions-job-name.constant.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/run-deferred-workspace-migration-actions-job-name.constant.ts
new file mode 100644
index 00000000000..12f4bc01096
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/run-deferred-workspace-migration-actions-job-name.constant.ts
@@ -0,0 +1,2 @@
+export const RUN_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_JOB_NAME =
+ 'RunDeferredWorkspaceMigrationActionsJob';
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/exceptions/deferred-workspace-migration-action.exception.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/exceptions/deferred-workspace-migration-action.exception.ts
new file mode 100644
index 00000000000..1dc36b948e1
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/exceptions/deferred-workspace-migration-action.exception.ts
@@ -0,0 +1,43 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { STANDARD_ERROR_MESSAGE } from 'src/engine/api/common/common-query-runners/errors/standard-error-message.constant';
+import {
+ appendCommonExceptionCode,
+ CustomException,
+} from 'src/utils/custom-exception';
+
+export const DeferredWorkspaceMigrationActionExceptionCode =
+ appendCommonExceptionCode({
+ EXECUTION_FAILED: 'EXECUTION_FAILED',
+ HANDLER_NOT_FOUND: 'HANDLER_NOT_FOUND',
+ } as const);
+
+const getDeferredWorkspaceMigrationActionExceptionUserFriendlyMessage = (
+ code: keyof typeof DeferredWorkspaceMigrationActionExceptionCode,
+) => {
+ switch (code) {
+ case DeferredWorkspaceMigrationActionExceptionCode.EXECUTION_FAILED:
+ case DeferredWorkspaceMigrationActionExceptionCode.HANDLER_NOT_FOUND:
+ case DeferredWorkspaceMigrationActionExceptionCode.INTERNAL_SERVER_ERROR:
+ return STANDARD_ERROR_MESSAGE;
+ default:
+ assertUnreachable(code);
+ }
+};
+
+export class DeferredWorkspaceMigrationActionException extends CustomException<
+ keyof typeof DeferredWorkspaceMigrationActionExceptionCode
+> {
+ constructor(
+ message: string,
+ code: keyof typeof DeferredWorkspaceMigrationActionExceptionCode,
+ { userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
+ ) {
+ super(message, code, {
+ userFriendlyMessage:
+ userFriendlyMessage ??
+ getDeferredWorkspaceMigrationActionExceptionUserFriendlyMessage(code),
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface.ts
index d4807fb4c55..95e444b9392 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface.ts
@@ -1,6 +1,7 @@
import { Inject, SetMetadata } from '@nestjs/common';
import { AllMetadataName } from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
import { QueryRunner } from 'typeorm';
import { LoggerService } from 'src/engine/core-modules/logger/logger.service';
@@ -29,7 +30,15 @@ import {
WorkspaceMigrationRunnerException,
WorkspaceMigrationRunnerExceptionCode,
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/exceptions/workspace-migration-runner.exception';
-import { type AfterCommitSideEffect } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/after-commit-side-effect.type';
+import {
+ DeferredWorkspaceMigrationActionException,
+ DeferredWorkspaceMigrationActionExceptionCode,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/exceptions/deferred-workspace-migration-action.exception';
+import {
+ type DeferredWorkspaceMigrationAction,
+ type DeferredWorkspaceMigrationActionPayload,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type';
+import { type DeferredWorkspaceMigrationActionExecutionArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-execution-args.type';
import { type MetadataEvent } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/metadata-event';
import {
WorkspaceMigrationActionRunnerContext,
@@ -58,7 +67,7 @@ export type ActionHandlerExecuteResult<TMetadataName extends AllMetadataName> =
| MetadataToFlatEntityMapsKey<TMetadataName>
>;
metadataEvents: MetadataEvent[];
- afterCommitSideEffects: AfterCommitSideEffect[];
+ deferredActions: DeferredWorkspaceMigrationAction[];
};
export abstract class BaseWorkspaceMigrationRunnerActionHandlerService<
@@ -142,10 +151,26 @@ export abstract class BaseWorkspaceMigrationRunnerActionHandlerService<
return Promise.resolve();
}
- protected getAfterCommitSideEffects(
+ protected getDeferredAction(
_context: WorkspaceMigrationActionRunnerContext<TFlatAction>,
- ): AfterCommitSideEffect[] {
- return [];
+ ):
+ | Extract<
+ DeferredWorkspaceMigrationAction,
+ { actionHandlerKey: `${TActionType}_${TMetadataName}` }
+ >
+ | undefined {
+ return undefined;
+ }
+
+ executeDeferredAction(
+ _args: DeferredWorkspaceMigrationActionExecutionArgs<
+ DeferredWorkspaceMigrationActionPayload<`${TActionType}_${TMetadataName}`>
+ >,
+ ): Promise<void> {
+ throw new DeferredWorkspaceMigrationActionException(
+ `${this.actionType}_${this.metadataName} does not implement deferred execution`,
+ DeferredWorkspaceMigrationActionExceptionCode.HANDLER_NOT_FOUND,
+ );
}
private optimisticallyApplyActionOnAllFlatEntityMaps({
@@ -292,18 +317,24 @@ export abstract class BaseWorkspaceMigrationRunnerActionHandlerService<
allFlatEntityMaps: context.allFlatEntityMaps,
});
- const afterCommitSideEffects = this.getAfterCommitSideEffects({
+ const deferredAction = this.getDeferredAction({
...context,
flatAction,
});
+ const deferredActions: DeferredWorkspaceMigrationAction[] = isDefined(
+ deferredAction,
+ )
+ ? [deferredAction]
+ : [];
+
const partialOptimisticCache =
this.optimisticallyApplyActionOnAllFlatEntityMaps({
flatAction,
allFlatEntityMaps: context.allFlatEntityMaps,
});
- return { partialOptimisticCache, metadataEvents, afterCommitSideEffects };
+ return { partialOptimisticCache, metadataEvents, deferredActions };
}
async rollback(
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/jobs/run-deferred-workspace-migration-actions.job.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/jobs/run-deferred-workspace-migration-actions.job.ts
new file mode 100644
index 00000000000..d2a03c29edd
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/jobs/run-deferred-workspace-migration-actions.job.ts
@@ -0,0 +1,25 @@
+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';
+import { RUN_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_JOB_NAME } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/run-deferred-workspace-migration-actions-job-name.constant';
+import { DeferredWorkspaceMigrationActionRunnerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/deferred-workspace-migration-action-runner.service';
+
+export type RunDeferredWorkspaceMigrationActionsJobData = {
+ workspaceId: string;
+};
+
+@Processor(MessageQueue.workspaceQueue)
+export class RunDeferredWorkspaceMigrationActionsJob {
+ constructor(
+ private readonly deferredWorkspaceMigrationActionRunnerService: DeferredWorkspaceMigrationActionRunnerService,
+ ) {}
+
+ @Process(RUN_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_JOB_NAME)
+ async handle(
+ data: RunDeferredWorkspaceMigrationActionsJobData,
+ ): Promise<void> {
+ await this.deferredWorkspaceMigrationActionRunnerService.runPendingActions(
+ data.workspaceId,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/registry/workspace-migration-runner-action-handler-registry.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/registry/workspace-migration-runner-action-handler-registry.service.ts
index b93753beda9..51c79a612bd 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/registry/workspace-migration-runner-action-handler-registry.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/registry/workspace-migration-runner-action-handler-registry.service.ts
@@ -1,6 +1,11 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { DiscoveryService } from '@nestjs/core';
+import { type AllMetadataName } from 'twenty-shared/metadata';
+import { type QueryRunner } from 'typeorm';
+
+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
+
import { BaseWorkspaceMigrationRunnerActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface';
import {
@@ -14,6 +19,14 @@ import {
WorkspaceMigrationActionExecutionException,
WorkspaceMigrationActionExecutionExceptionCode,
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/exceptions/workspace-migration-action-execution.exception';
+import {
+ DeferredWorkspaceMigrationActionException,
+ DeferredWorkspaceMigrationActionExceptionCode,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/exceptions/deferred-workspace-migration-action.exception';
+import {
+ type DeferrableWorkspaceMigrationActionHandlerKey,
+ type PersistedDeferredWorkspaceMigrationAction,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type';
import { WorkspaceMigrationActionRunnerArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/workspace-migration-action-runner-args.type';
@Injectable()
@@ -95,4 +108,52 @@ export class WorkspaceMigrationRunnerActionHandlerRegistryService implements OnM
await handler.rollback(context);
}
+
+ getDeferredActionMetadataName(
+ actionHandlerKey: DeferrableWorkspaceMigrationActionHandlerKey,
+ ): AllMetadataName {
+ return this.getDeferredActionHandler(actionHandlerKey).metadataName;
+ }
+
+ async executeDeferredActionHandler({
+ deferredAction,
+ workspaceId,
+ applicationUniversalIdentifier,
+ allFlatEntityMaps,
+ attempt,
+ queryRunner,
+ }: {
+ deferredAction: PersistedDeferredWorkspaceMigrationAction;
+ workspaceId: string;
+ applicationUniversalIdentifier: string;
+ allFlatEntityMaps: AllFlatEntityMaps;
+ attempt: number;
+ queryRunner: QueryRunner;
+ }): Promise<void> {
+ await this.getDeferredActionHandler(
+ deferredAction.actionHandlerKey,
+ ).executeDeferredAction({
+ workspaceId,
+ applicationUniversalIdentifier,
+ payload: deferredAction.payload,
+ allFlatEntityMaps,
+ attempt,
+ queryRunner,
+ });
+ }
+
+ private getDeferredActionHandler(
+ actionHandlerKey: DeferrableWorkspaceMigrationActionHandlerKey,
+ ) {
+ const handler = this.actionHandlers.get(actionHandlerKey);
+
+ if (!handler) {
+ throw new DeferredWorkspaceMigrationActionException(
+ `No migration runner action handler found for deferred action: ${actionHandlerKey}`,
+ DeferredWorkspaceMigrationActionExceptionCode.HANDLER_NOT_FOUND,
+ );
+ }
+
+ return handler;
+ }
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/deferred-workspace-migration-action-runner.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/deferred-workspace-migration-action-runner.service.ts
new file mode 100644
index 00000000000..8ab38b98d5b
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/deferred-workspace-migration-action-runner.service.ts
@@ -0,0 +1,333 @@
+import { Injectable, Logger } from '@nestjs/common';
+import { InjectDataSource } from '@nestjs/typeorm';
+
+import { DataSource, type QueryRunner } from 'typeorm';
+
+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';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { DeferredWorkspaceMigrationActionEntity } from 'src/engine/metadata-modules/deferred-workspace-migration-action/deferred-workspace-migration-action.entity';
+import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
+import { getMetadataFlatEntityMapsKey } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-flat-entity-maps-key.util';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { DEFERRED_WORKSPACE_MIGRATION_ACTION_MAX_ATTEMPTS } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferred-workspace-migration-action-max-attempts.constant';
+import { DEFERRED_WORKSPACE_MIGRATION_ACTION_STATEMENT_TIMEOUT_MS } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferred-workspace-migration-action-statement-timeout-ms.constant';
+import { RUN_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_JOB_NAME } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/run-deferred-workspace-migration-actions-job-name.constant';
+import {
+ DeferredWorkspaceMigrationActionException,
+ DeferredWorkspaceMigrationActionExceptionCode,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/exceptions/deferred-workspace-migration-action.exception';
+import { type RunDeferredWorkspaceMigrationActionsJobData } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/jobs/run-deferred-workspace-migration-actions.job';
+import { WorkspaceMigrationRunnerActionHandlerRegistryService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/registry/workspace-migration-runner-action-handler-registry.service';
+import {
+ type DeferredWorkspaceMigrationAction,
+ type PersistedDeferredWorkspaceMigrationAction,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type';
+import { getMetadataNamesToLoadForWorkspaceMigration } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/get-metadata-names-to-load-for-workspace-migration.util';
+
+@Injectable()
+export class DeferredWorkspaceMigrationActionRunnerService {
+ private readonly logger = new Logger(
+ DeferredWorkspaceMigrationActionRunnerService.name,
+ );
+
+ constructor(
+ @InjectWorkspaceScopedRepository(DeferredWorkspaceMigrationActionEntity)
+ private readonly deferredWorkspaceMigrationActionRepository: WorkspaceScopedRepository<DeferredWorkspaceMigrationActionEntity>,
+ @InjectDataSource()
+ private readonly coreDataSource: DataSource,
+ @InjectMessageQueue(MessageQueue.workspaceQueue)
+ private readonly messageQueueService: MessageQueueService,
+ private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
+ private readonly workspaceMigrationRunnerActionHandlerRegistry: WorkspaceMigrationRunnerActionHandlerRegistryService,
+ private readonly twentyConfigService: TwentyConfigService,
+ ) {}
+
+ async persist({
+ deferredActions,
+ workspaceId,
+ applicationUniversalIdentifier,
+ queryRunner,
+ }: {
+ deferredActions: DeferredWorkspaceMigrationAction[];
+ workspaceId: string;
+ applicationUniversalIdentifier: string;
+ queryRunner: QueryRunner;
+ }): Promise<void> {
+ if (deferredActions.length === 0) {
+ return;
+ }
+
+ await queryRunner.manager
+ .getRepository(DeferredWorkspaceMigrationActionEntity)
+ .save(
+ deferredActions.map(({ actionHandlerKey, payload }, position) => ({
+ workspaceId,
+ applicationUniversalIdentifier,
+ actionHandlerKey,
+ payload,
+ position,
+ runByVersion: this.twentyConfigService.get('APP_VERSION') ?? null,
+ })),
+ );
+ }
+
+ async dispatchAfterCommit({
+ deferredActions,
+ hasPersistedDeferredActions,
+ workspaceId,
+ applicationUniversalIdentifier,
+ allFlatEntityMaps,
+ }: {
+ deferredActions: DeferredWorkspaceMigrationAction[];
+ hasPersistedDeferredActions: boolean;
+ workspaceId: string;
+ applicationUniversalIdentifier: string;
+ allFlatEntityMaps: AllFlatEntityMaps;
+ }): Promise<void> {
+ if (deferredActions.length === 0) {
+ return;
+ }
+
+ if (hasPersistedDeferredActions) {
+ await this.enqueue(workspaceId);
+
+ return;
+ }
+
+ await this.executeInProcess({
+ deferredActions,
+ workspaceId,
+ applicationUniversalIdentifier,
+ allFlatEntityMaps,
+ });
+ }
+
+ async runPendingActions(workspaceId: string): Promise<void> {
+ const pendingActions =
+ await this.deferredWorkspaceMigrationActionRepository.find(workspaceId, {
+ where: { status: 'PENDING' },
+ order: { createdAt: 'ASC', position: 'ASC' },
+ });
+
+ if (pendingActions.length === 0) {
+ return;
+ }
+
+ const allFlatEntityMaps = await this.loadFlatEntityMaps({
+ workspaceId,
+ deferredActions: pendingActions,
+ });
+
+ const deferredActionDataSource =
+ await this.createDeferredActionDataSource();
+
+ try {
+ for (const pendingAction of pendingActions) {
+ const hasSucceeded = await this.claimAndExecute({
+ pendingAction,
+ allFlatEntityMaps,
+ deferredActionDataSource,
+ });
+
+ if (!hasSucceeded) {
+ throw new DeferredWorkspaceMigrationActionException(
+ `Deferred workspace migration action ${pendingAction.id} failed for workspace ${workspaceId}, the following actions will run on retry`,
+ DeferredWorkspaceMigrationActionExceptionCode.EXECUTION_FAILED,
+ );
+ }
+ }
+ } finally {
+ await deferredActionDataSource.destroy();
+ }
+ }
+
+ private async enqueue(workspaceId: string): Promise<void> {
+ try {
+ await this.messageQueueService.add<RunDeferredWorkspaceMigrationActionsJobData>(
+ RUN_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_JOB_NAME,
+ { workspaceId },
+ {
+ id: `deferred-workspace-migration-actions.${workspaceId}`,
+ retryLimit: DEFERRED_WORKSPACE_MIGRATION_ACTION_MAX_ATTEMPTS - 1,
+ },
+ );
+ } catch (error) {
+ this.logger.error(
+ `Failed to enqueue deferred workspace migration actions for workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+
+ private async executeInProcess({
+ deferredActions,
+ workspaceId,
+ applicationUniversalIdentifier,
+ allFlatEntityMaps,
+ }: {
+ deferredActions: DeferredWorkspaceMigrationAction[];
+ workspaceId: string;
+ applicationUniversalIdentifier: string;
+ allFlatEntityMaps: AllFlatEntityMaps;
+ }): Promise<void> {
+ const queryRunner = this.coreDataSource.createQueryRunner();
+
+ try {
+ for (const deferredAction of deferredActions) {
+ try {
+ await this.workspaceMigrationRunnerActionHandlerRegistry.executeDeferredActionHandler(
+ {
+ deferredAction,
+ workspaceId,
+ applicationUniversalIdentifier,
+ allFlatEntityMaps,
+ attempt: 1,
+ queryRunner,
+ },
+ );
+ } catch (error) {
+ this.logger.warn(
+ `Deferred action ${deferredAction.actionHandlerKey} failed for workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+ } finally {
+ await queryRunner.release();
+ }
+ }
+
+ private async loadFlatEntityMaps({
+ workspaceId,
+ deferredActions,
+ }: {
+ workspaceId: string;
+ deferredActions: Pick<
+ PersistedDeferredWorkspaceMigrationAction,
+ 'actionHandlerKey'
+ >[];
+ }): Promise<AllFlatEntityMaps> {
+ const metadataNames = [
+ ...new Set(
+ deferredActions.map(({ actionHandlerKey }) =>
+ this.workspaceMigrationRunnerActionHandlerRegistry.getDeferredActionMetadataName(
+ actionHandlerKey,
+ ),
+ ),
+ ),
+ ];
+
+ return this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
+ {
+ workspaceId,
+ flatMapsKeys: getMetadataNamesToLoadForWorkspaceMigration(
+ metadataNames,
+ ).map(getMetadataFlatEntityMapsKey),
+ },
+ );
+ }
+
+ private async claimAndExecute({
+ pendingAction,
+ allFlatEntityMaps,
+ deferredActionDataSource,
+ }: {
+ pendingAction: DeferredWorkspaceMigrationActionEntity;
+ allFlatEntityMaps: AllFlatEntityMaps;
+ deferredActionDataSource: DataSource;
+ }): Promise<boolean> {
+ const { id, workspaceId } = pendingAction;
+ const attempt = pendingAction.attempts + 1;
+
+ const claimResult =
+ await this.deferredWorkspaceMigrationActionRepository.update(
+ workspaceId,
+ { id, status: 'PENDING' },
+ { status: 'IN_PROGRESS', attempts: attempt, startedAt: new Date() },
+ );
+
+ if (claimResult.affected !== 1) {
+ return true;
+ }
+
+ const queryRunner = deferredActionDataSource.createQueryRunner();
+ const executionStart = performance.now();
+
+ try {
+ await queryRunner.connect();
+
+ await this.workspaceMigrationRunnerActionHandlerRegistry.executeDeferredActionHandler(
+ {
+ deferredAction: pendingAction,
+ workspaceId,
+ applicationUniversalIdentifier:
+ pendingAction.applicationUniversalIdentifier,
+ allFlatEntityMaps,
+ attempt,
+ queryRunner,
+ },
+ );
+
+ await this.deferredWorkspaceMigrationActionRepository.delete(
+ workspaceId,
+ { id },
+ );
+
+ this.logger.log(
+ `Deferred action ${pendingAction.actionHandlerKey} ${id} completed for workspace ${workspaceId} in ${(performance.now() - executionStart).toFixed(0)}ms`,
+ );
+
+ return true;
+ } catch (error) {
+ await this.deferredWorkspaceMigrationActionRepository.update(
+ workspaceId,
+ { id },
+ {
+ status:
+ attempt >= DEFERRED_WORKSPACE_MIGRATION_ACTION_MAX_ATTEMPTS
+ ? 'FAILED'
+ : 'PENDING',
+ lastError: error instanceof Error ? error.message : String(error),
+ },
+ );
+
+ this.logger.error(
+ `Deferred action ${pendingAction.actionHandlerKey} ${id} failed for workspace ${workspaceId} (attempt ${attempt}/${DEFERRED_WORKSPACE_MIGRATION_ACTION_MAX_ATTEMPTS})`,
+ error instanceof Error ? error.stack : undefined,
+ );
+
+ return false;
+ } finally {
+ await queryRunner.release();
+ }
+ }
+
+ private async createDeferredActionDataSource(): Promise<DataSource> {
+ const coreDataSourceOptions = this.coreDataSource.options;
+
+ if (coreDataSourceOptions.type !== 'postgres') {
+ throw new DeferredWorkspaceMigrationActionException(
+ `Deferred workspace migration actions require a postgres datasource, got ${coreDataSourceOptions.type}`,
+ DeferredWorkspaceMigrationActionExceptionCode.EXECUTION_FAILED,
+ );
+ }
+
+ const deferredActionDataSource = new DataSource({
+ ...coreDataSourceOptions,
+ entities: [],
+ migrations: [],
+ subscribers: [],
+ poolSize: 1,
+ extra: {
+ ...coreDataSourceOptions.extra,
+ query_timeout: undefined,
+ statement_timeout:
+ DEFERRED_WORKSPACE_MIGRATION_ACTION_STATEMENT_TIMEOUT_MS,
+ },
+ });
+
+ return deferredActionDataSource.initialize();
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/workspace-migration-runner.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/workspace-migration-runner.service.ts
index 76e9cd65535..04cd9d81f3f 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/workspace-migration-runner.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/workspace-migration-runner.service.ts
@@ -2,9 +2,11 @@ import { Injectable } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { type AllMetadataName } from 'twenty-shared/metadata';
+import { FeatureFlagKey } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { DataSource } from 'typeorm';
+import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { LoggerService } from 'src/engine/core-modules/logger/logger.service';
import { WORKSPACE_MIGRATION_DURATION_MS_BUCKET_BOUNDARIES } from 'src/engine/core-modules/metrics/constants/workspace-migration-duration-ms-bucket-boundaries.constant';
import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
@@ -14,9 +16,6 @@ import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadat
import { AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
import { getFlatEntityMapsExceptionContext } from 'src/engine/metadata-modules/flat-entity/utils/get-flat-entity-maps-exception-context.util';
import { getMetadataFlatEntityMapsKey } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-flat-entity-maps-key.util';
-import { getMetadataRelatedMetadataNamesForValidation } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-related-metadata-names-for-validation.util';
-import { getMetadataRelatedMetadataNames } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-related-metadata-names.util';
-import { getMetadataSerializedRelationNames } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-serialized-relation-names.util';
import { withDerivedFieldMetadataMaps } from 'src/engine/metadata-modules/flat-entity/utils/with-derived-field-metadata-maps.util';
import { createSearchFieldMetadatasByTsVectorFieldIdAccessor } from 'src/engine/metadata-modules/flat-search-field-metadata/utils/create-search-field-metadatas-by-ts-vector-field-id-accessor.util';
import { WorkspaceMetadataVersionService } from 'src/engine/metadata-modules/workspace-metadata-version/services/workspace-metadata-version.service';
@@ -28,8 +27,10 @@ import {
WorkspaceMigrationRunnerExceptionCode,
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/exceptions/workspace-migration-runner.exception';
import { WorkspaceMigrationRunnerActionHandlerRegistryService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/registry/workspace-migration-runner-action-handler-registry.service';
-import { type AfterCommitSideEffect } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/after-commit-side-effect.type';
+import { DeferredWorkspaceMigrationActionRunnerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/deferred-workspace-migration-action-runner.service';
+import { type DeferredWorkspaceMigrationAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type';
import { type MetadataEvent } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/metadata-event';
+import { getMetadataNamesToLoadForWorkspaceMigration } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/get-metadata-names-to-load-for-workspace-migration.util';
import { buildPreallocatedIdByUniversalIdentifierFromActions } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/build-preallocated-id-by-universal-identifier-from-actions.util';
@Injectable()
@@ -44,6 +45,8 @@ export class WorkspaceMigrationRunnerService {
private readonly metricsService: MetricsService,
private readonly logger: LoggerService,
private readonly twentyConfigService: TwentyConfigService,
+ private readonly featureFlagService: FeatureFlagService,
+ private readonly deferredWorkspaceMigrationActionRunnerService: DeferredWorkspaceMigrationActionRunnerService,
) {}
private getLegacyCacheInvalidation(
@@ -260,12 +263,7 @@ export class WorkspaceMigrationRunnerService {
const actionsMetadataAndRelatedMetadataNames: AllMetadataName[] = [
...new Set([
- ...actionMetadataNames,
- ...actionMetadataNames.flatMap(getMetadataRelatedMetadataNames),
- ...actionMetadataNames.flatMap(getMetadataSerializedRelationNames),
- ...actionMetadataNames.flatMap(
- getMetadataRelatedMetadataNamesForValidation,
- ),
+ ...getMetadataNamesToLoadForWorkspaceMigration(actionMetadataNames),
...searchVectorRebuildMetadataNames,
]),
];
@@ -337,13 +335,21 @@ export class WorkspaceMigrationRunnerService {
const preallocatedIdByUniversalIdentifierByMetadataName =
buildPreallocatedIdByUniversalIdentifierFromActions(actions);
+ const featureFlagsMap =
+ await this.featureFlagService.getWorkspaceFeatureFlagsMap(workspaceId);
+
+ const shouldPersistDeferredActions =
+ featureFlagsMap[
+ FeatureFlagKey.IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED
+ ];
+
this.logger.perfTime('Runner', 'Transaction execution');
await queryRunner.connect();
await queryRunner.startTransaction();
const allMetadataEvents: MetadataEvent[] = [];
- const allAfterCommitSideEffects: AfterCommitSideEffect[] = [];
+ const allDeferredActions: DeferredWorkspaceMigrationAction[] = [];
const transactionStart = performance.now();
let slowestActionMs = 0;
@@ -360,11 +366,7 @@ export class WorkspaceMigrationRunnerService {
for (const action of actions) {
const actionStart = performance.now();
- const {
- partialOptimisticCache,
- metadataEvents,
- afterCommitSideEffects,
- } =
+ const { partialOptimisticCache, metadataEvents, deferredActions } =
await this.workspaceMigrationRunnerActionHandlerRegistry.executeActionHandler(
{
action,
@@ -377,6 +379,7 @@ export class WorkspaceMigrationRunnerService {
preallocatedIdByUniversalIdentifierByMetadataName,
getSearchFieldMetadatasByTsVectorFieldId:
searchFieldMetadatasByTsVectorFieldIdAccessor.get,
+ featureFlagsMap,
},
},
);
@@ -407,7 +410,16 @@ export class WorkspaceMigrationRunnerService {
}
allMetadataEvents.push(...metadataEvents);
- allAfterCommitSideEffects.push(...afterCommitSideEffects);
+ allDeferredActions.push(...deferredActions);
+ }
+
+ if (shouldPersistDeferredActions) {
+ await this.deferredWorkspaceMigrationActionRunnerService.persist({
+ deferredActions: allDeferredActions,
+ workspaceId,
+ applicationUniversalIdentifier,
+ queryRunner,
+ });
}
const commitStart = performance.now();
@@ -541,25 +553,16 @@ export class WorkspaceMigrationRunnerService {
'Runner',
);
- const sideEffectResults = await Promise.allSettled(
- allAfterCommitSideEffects.map((sideEffect) =>
- Promise.resolve().then(() => sideEffect.run()),
- ),
+ await this.deferredWorkspaceMigrationActionRunnerService.dispatchAfterCommit(
+ {
+ deferredActions: allDeferredActions,
+ hasPersistedDeferredActions: shouldPersistDeferredActions,
+ workspaceId,
+ applicationUniversalIdentifier,
+ allFlatEntityMaps,
+ },
);
- sideEffectResults.forEach((result, index) => {
- if (result.status === 'rejected') {
- this.logger.warn(
- `After-commit side effect failed (${allAfterCommitSideEffects[index].description}): ${
- result.reason instanceof Error
- ? result.reason.message
- : String(result.reason)
- }`,
- 'Runner',
- );
- }
- });
-
const hasSchemaMetadataChanged =
allFlatEntityMapsKeys.includes('flatObjectMetadataMaps') ||
allFlatEntityMapsKeys.includes('flatFieldMetadataMaps');
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/after-commit-side-effect.type.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/after-commit-side-effect.type.ts
deleted file mode 100644
index 822357f2bc6..00000000000
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/after-commit-side-effect.type.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export type AfterCommitSideEffect = {
- description: string;
- run: () => Promise<void>;
-};
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-execution-args.type.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-execution-args.type.ts
new file mode 100644
index 00000000000..976b3ebf5e5
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-execution-args.type.ts
@@ -0,0 +1,12 @@
+import { type QueryRunner } from 'typeorm';
+
+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
+
+export type DeferredWorkspaceMigrationActionExecutionArgs<TPayload> = {
+ workspaceId: string;
+ applicationUniversalIdentifier: string;
+ payload: TPayload;
+ allFlatEntityMaps: AllFlatEntityMaps;
+ attempt: number;
+ queryRunner: QueryRunner;
+};
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-status.type.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-status.type.ts
new file mode 100644
index 00000000000..cce435fc553
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action-status.type.ts
@@ -0,0 +1,4 @@
+export type DeferredWorkspaceMigrationActionStatus =
+ | 'PENDING'
+ | 'IN_PROGRESS'
+ | 'FAILED';
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type.ts
new file mode 100644
index 00000000000..94739927e03
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/deferred-workspace-migration-action.type.ts
@@ -0,0 +1,29 @@
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+import { type WorkspaceMigrationActionHandlerKey } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/workspace-migration-action-common';
+import { type DEFERRABLE_WORKSPACE_MIGRATION_ACTIONS } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/deferrable-workspace-migration-actions.constant';
+
+export type DeferrableWorkspaceMigrationActionHandlerKey =
+ (typeof DEFERRABLE_WORKSPACE_MIGRATION_ACTIONS)[number];
+
+type DeferredWorkspaceMigrationActionPayloadByHandlerKey = {
+ create_index: { indexMetadataId: string };
+ delete_logicFunction: { flatLogicFunction: FlatLogicFunction };
+};
+
+export type DeferredWorkspaceMigrationActionPayload<
+ TActionHandlerKey extends WorkspaceMigrationActionHandlerKey,
+> = TActionHandlerKey extends DeferrableWorkspaceMigrationActionHandlerKey
+ ? DeferredWorkspaceMigrationActionPayloadByHandlerKey[TActionHandlerKey]
+ : never;
+
+export type PersistedDeferredWorkspaceMigrationAction = {
+ actionHandlerKey: DeferrableWorkspaceMigrationActionHandlerKey;
+ payload: DeferredWorkspaceMigrationActionPayloadByHandlerKey[DeferrableWorkspaceMigrationActionHandlerKey];
+};
+
+export type DeferredWorkspaceMigrationAction = {
+ [TActionHandlerKey in DeferrableWorkspaceMigrationActionHandlerKey]: {
+ actionHandlerKey: TActionHandlerKey;
+ payload: DeferredWorkspaceMigrationActionPayloadByHandlerKey[TActionHandlerKey];
+ };
+}[DeferrableWorkspaceMigrationActionHandlerKey];
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/workspace-migration-action-runner-args.type.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/workspace-migration-action-runner-args.type.ts
index 524a3c1da83..8ef414cd535 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/workspace-migration-action-runner-args.type.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/workspace-migration-action-runner-args.type.ts
@@ -1,5 +1,7 @@
import { type QueryRunner } from 'typeorm';
+import { type FeatureFlagMap } from 'src/engine/core-modules/feature-flag/interfaces/feature-flag-map.interface';
+
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
import { type FlatSearchFieldMetadata } from 'src/engine/metadata-modules/flat-search-field-metadata/types/flat-search-field-metadata.type';
@@ -21,6 +23,7 @@ export type WorkspaceMigrationActionRunnerArgs<
getSearchFieldMetadatasByTsVectorFieldId?: (
tsVectorFieldMetadataId: string,
) => FlatSearchFieldMetadata[];
+ featureFlagsMap?: FeatureFlagMap;
};
export type WorkspaceMigrationActionRunnerContext<
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/get-metadata-names-to-load-for-workspace-migration.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/get-metadata-names-to-load-for-workspace-migration.util.ts
new file mode 100644
index 00000000000..b93ed882bc5
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/get-metadata-names-to-load-for-workspace-migration.util.ts
@@ -0,0 +1,16 @@
+import { type AllMetadataName } from 'twenty-shared/metadata';
+
+import { getMetadataRelatedMetadataNamesForValidation } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-related-metadata-names-for-validation.util';
+import { getMetadataRelatedMetadataNames } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-related-metadata-names.util';
+import { getMetadataSerializedRelationNames } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-serialized-relation-names.util';
+
+export const getMetadataNamesToLoadForWorkspaceMigration = (
+ metadataNames: AllMetadataName[],
+): AllMetadataName[] => [
+ ...new Set([
+ ...metadataNames,
+ ...metadataNames.flatMap(getMetadataRelatedMetadataNames),
+ ...metadataNames.flatMap(getMetadataSerializedRelationNames),
+ ...metadataNames.flatMap(getMetadataRelatedMetadataNamesForValidation),
+ ]),
+];
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/workspace-migration-runner.module.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/workspace-migration-runner.module.ts
index 8986b11bc0a..9bb078b59a1 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/workspace-migration-runner.module.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/workspace-migration-runner.module.ts
@@ -7,13 +7,16 @@ import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { DeferredWorkspaceMigrationActionEntity } from 'src/engine/metadata-modules/deferred-workspace-migration-action/deferred-workspace-migration-action.entity';
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
import { WorkspaceMetadataVersionModule } from 'src/engine/metadata-modules/workspace-metadata-version/workspace-metadata-version.module';
+import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/workspace-cache-storage.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceSchemaMigrationRunnerActionHandlersModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/workspace-schema-migration-runner-action-handlers.module';
import { FlatCacheInvalidateCommand } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/commands/flat-cache-invalidate.command';
import { WorkspaceMigrationRunnerActionHandlerRegistryService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/registry/workspace-migration-runner-action-handler-registry.service';
+import { DeferredWorkspaceMigrationActionRunnerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/deferred-workspace-migration-action-runner.service';
import { WorkspaceMigrationRunnerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/workspace-migration-runner.service';
@Module({
@@ -26,15 +29,23 @@ import { WorkspaceMigrationRunnerService } from 'src/engine/workspace-manager/wo
DiscoveryModule,
WorkspaceCacheStorageModule,
WorkspaceCacheModule,
- TypeOrmModule.forFeature([WorkspaceEntity]),
+ TypeOrmModule.forFeature([
+ WorkspaceEntity,
+ DeferredWorkspaceMigrationActionEntity,
+ ]),
WorkspaceIteratorModule,
MetricsModule,
],
providers: [
WorkspaceMigrationRunnerService,
WorkspaceMigrationRunnerActionHandlerRegistryService,
+ DeferredWorkspaceMigrationActionRunnerService,
+ provideWorkspaceScopedRepository(DeferredWorkspaceMigrationActionEntity),
FlatCacheInvalidateCommand,
],
- exports: [WorkspaceMigrationRunnerService],
+ exports: [
+ WorkspaceMigrationRunnerService,
+ DeferredWorkspaceMigrationActionRunnerService,
+ ],
})
export class WorkspaceMigrationRunnerModule {}
diff --git a/packages/twenty-server/test/integration/metadata/suites/deferred-workspace-migration-action/deferred-workspace-migration-actions.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/deferred-workspace-migration-action/deferred-workspace-migration-actions.integration-spec.ts
new file mode 100644
index 00000000000..f5d6544aced
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/deferred-workspace-migration-action/deferred-workspace-migration-actions.integration-spec.ts
@@ -0,0 +1,154 @@
+import { createOneOperation } from 'test/integration/graphql/utils/create-one-operation.util';
+import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { createOneLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/create-logic-function.util';
+import { deleteLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/delete-logic-function.util';
+import { createOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/create-one-object-metadata.util';
+import { deleteOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/delete-one-object-metadata.util';
+import { findManyObjectMetadataWithIndexes } from 'test/integration/metadata/suites/object-metadata/utils/find-many-object-metadata-with-indexes.util';
+import { updateOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/update-one-object-metadata.util';
+import { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';
+import { expectEventually } from 'test/integration/utils/expect-eventually.util';
+import { FeatureFlagKey } from 'twenty-shared/types';
+
+const OBJECT_NAME_SINGULAR = 'deferredGadget';
+const SYSTEM_RELATION_OBJECT_NAMES = [
+ 'attachment',
+ 'noteTarget',
+ 'taskTarget',
+ 'timelineActivity',
+];
+
+const findIndexNamesBySystemRelationObjectName = async (): Promise<
+ Record<string, string[]>
+> => {
+ const objects = await findManyObjectMetadataWithIndexes({
+ expectToFail: false,
+ });
+
+ return Object.fromEntries(
+ SYSTEM_RELATION_OBJECT_NAMES.map((systemRelationObjectName) => [
+ systemRelationObjectName,
+ (
+ objects.find(
+ (object) => object.nameSingular === systemRelationObjectName,
+ )?.indexMetadataList ?? []
+ ).map((index) => index.name),
+ ]),
+ );
+};
+
+describe('Deferred workspace migration actions', () => {
+ let objectMetadataId: string;
+ let indexNamesBeforeObjectCreation: Record<string, string[]>;
+
+ beforeAll(async () => {
+ await updateFeatureFlag({
+ featureFlag:
+ FeatureFlagKey.IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED,
+ value: true,
+ expectToFail: false,
+ });
+
+ indexNamesBeforeObjectCreation =
+ await findIndexNamesBySystemRelationObjectName();
+
+ const {
+ data: {
+ createOneObject: { id },
+ },
+ } = await createOneObjectMetadata({
+ expectToFail: false,
+ input: {
+ nameSingular: OBJECT_NAME_SINGULAR,
+ namePlural: `${OBJECT_NAME_SINGULAR}s`,
+ labelSingular: 'Deferred gadget',
+ labelPlural: 'Deferred gadgets',
+ icon: 'IconBox',
+ isLabelSyncedWithName: false,
+ },
+ });
+
+ objectMetadataId = id;
+ });
+
+ afterAll(async () => {
+ await updateOneObjectMetadata({
+ expectToFail: false,
+ input: {
+ idToUpdate: objectMetadataId,
+ updatePayload: { isActive: false },
+ },
+ });
+ await deleteOneObjectMetadata({
+ expectToFail: false,
+ input: { idToDelete: objectMetadataId },
+ });
+ await updateFeatureFlag({
+ featureFlag:
+ FeatureFlagKey.IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED,
+ value: false,
+ expectToFail: false,
+ });
+ });
+
+ it('should add one join column index to every system relation object', async () => {
+ const indexNamesAfterObjectCreation =
+ await findIndexNamesBySystemRelationObjectName();
+
+ for (const systemRelationObjectName of SYSTEM_RELATION_OBJECT_NAMES) {
+ const newIndexNames = indexNamesAfterObjectCreation[
+ systemRelationObjectName
+ ].filter(
+ (indexName) =>
+ !indexNamesBeforeObjectCreation[systemRelationObjectName].includes(
+ indexName,
+ ),
+ );
+
+ expect(newIndexNames).toHaveLength(1);
+ }
+ });
+
+ it('should record timeline activities for records of the new object', async () => {
+ const {
+ data: { createOneResponse },
+ } = await createOneOperation({
+ objectMetadataSingularName: OBJECT_NAME_SINGULAR,
+ input: { name: 'First deferred gadget' },
+ });
+
+ await expectEventually(async () => {
+ const response = await makeGraphqlAPIRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'timelineActivity',
+ objectMetadataPluralName: 'timelineActivities',
+ gqlFields: 'id',
+ filter: { targetDeferredGadgetId: { eq: createOneResponse.id } },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(
+ response.body.data.timelineActivities.edges.length,
+ ).toBeGreaterThan(0);
+ });
+ });
+
+ it('should delete a logic function', async () => {
+ const { data: createData } = await createOneLogicFunction({
+ input: { name: 'Deferred cleanup function' },
+ expectToFail: false,
+ });
+
+ const logicFunctionId = createData.createOneLogicFunction.id;
+
+ const { data: deleteData, errors } = await deleteLogicFunction({
+ input: { id: logicFunctionId },
+ expectToFail: false,
+ });
+
+ expect(errors).toBeUndefined();
+ expect(deleteData.deleteOneLogicFunction.id).toBe(logicFunctionId);
+ });
+});
diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.ts
index 245f1a46b54..dc088ebf59f 100644
--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts
+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts
@@ -12,4 +12,5 @@ export enum FeatureFlagKey {
IS_RECORD_SHARING_ENABLED = 'IS_RECORD_SHARING_ENABLED',
IS_INITIAL_OBJECT_VIEW_ENABLED = 'IS_INITIAL_OBJECT_VIEW_ENABLED',
IS_WEBHOOK_RATE_LIMIT_ENABLED = 'IS_WEBHOOK_RATE_LIMIT_ENABLED',
+ IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED = 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED',
}